service的远程调用

客户端
1.manifest.xml中添加
<!-- AIDL完整路径名。必须指明,客户端能够通过AIDL类名查找到它的实现类 -->
(1)<uses-permission android:name="com.androd.roteservicename.PERMISSION"/>
(2)<action android:name="com.android.roteservicename" />
2.在代码中添加
ServiceConnection conn;
Service mService;
conn = new ServiceConnection() {
public void onServiceConnected(ComponentName name,
IBinder service) {
Log.i(TAG, "Service bound ");
mService = ServiceBinder.Stub.asInterface(service);
}

public void onServiceDisconnected(ComponentName arg0) {
Log.i(TAG, "Service Unbound ");
mService = null;
}
};

bindService(new Intent("aidl目录+servicename"), conn,
Context.BIND_AUTO_CREATE);
}
3.使用时直接调用
mService

服务器端

4.举例介绍
ItestService.aidl内容如下
package com.lifeblood;
// See the list above for which classes need
// import statements (hint--most of them)
// Declare the interface.
interface ITestService {
   // Methods can take 0 or more parameters, and
   // return a value or void.
   int getAccountBalance();
   void setOwnerNames(in List<String> names);
   // Methods can even take other AIDL-defined parameters.
   //BankAccount createAccount(in String name, int startingDeposit, in IAtmService atmService);
   // All non-Java primitive parameters (e.g., int, bool, etc) require
   // a directional tag indicating which way the data will go. Available
   // values are in, out, inout. (Primitives are in by default, and cannot be otherwise).
   // Limit the direction to what is truly needed, because marshalling parameters
   // is expensive.
   int getCustomerList(in String branch, out String[] customerList);
  
   void showTest();
}
java中调用时
public class TestService extends Service {
private Context mContext = null;

//实现AIDL接口中各个方法
private ITestService.Stub binder = new Stub(){
private String name = null;
public int getAccountBalance() throws RemoteException {
// TODO Auto-generated method stub
return 100000;
}

public int getCustomerList(String branch, String[] customerList)
throws RemoteException {
// TODO Auto-generated method stub
customerList[0] = name;
System.out.println("Name:"+branch);
return 0;
}

public void setOwnerNames(List<String> names) throws RemoteException {
// TODO Auto-generated method stub
name = names.get(0);
System.out.println("Size:"+names.size()+"=="+names.get(0));
}

public void showTest() throws RemoteException {
// TODO Auto-generated method stub
Intent intent = new Intent(mContext, AidlTtest.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
};
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
mContext = this;
return binder; //返回AIDL接口实例化对象
}
}

你可能感兴趣的:(xml)