1.新建aidl文件
2.Build->Make Project
在该目录下可以发现生成后的IMyAidlInterface.java文件。
3.新建Service并实现IMyAidlInterface定义的方法,onBind中返回实例。
public class MyRemoteService extends Service { public MyRemoteService() { } IMyAidlInterface.Stub myAidlInterface = new IMyAidlInterface.Stub() { @Override public String SayHello(String world) throws RemoteException { return world; } }; @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. return myAidlInterface; } }4.Manifest 中修改定义
<service android:name=".MyRemoteService" android:enabled="true" android:exported="true" android:process=":remote" > <intent-filter> <action android:name="my.test.com.servicedemo.MyService" /> </intent-filter> </service>5.Activity中调用
楼主下午一直报null因为在bindService后直接调用myAidlInterface 的方法了,此时应该并没有执行完onServiceConnected,
所以最好在onServiceConnected后再调用方法!
intent_aidl = new Intent(this, MyRemoteService.class);
bindService(intent_aidl, aidl_ServiceConnection, BIND_AUTO_CREATE);
private IMyAidlInterface myAidlInterface = null; ServiceConnection aidl_ServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { Log.i("MainActivity", "ComponentName:"+componentName); myAidlInterface = (IMyAidlInterface.Stub.asInterface(iBinder)) ; if(myAidlInterface==null) Log.i("MainActivity", "myAidlInterface==null"); else { try { String temp=myAidlInterface.SayHello("fuck uuuuuuu!!!!!!"); Toast.makeText(MainActivity.this,temp,Toast.LENGTH_SHORT).show(); } catch (RemoteException e) { e.printStackTrace(); } } } @Override public void onServiceDisconnected(ComponentName componentName) { } };