Binder实现进程间通讯(定义AIDL文件)

Binder实现进程间通讯:
服务端:
1、新建一个AIDL文件,自定义需要的函数,编译,在gen目录生成同名的Java文件
2、新建一个service,内部基于AIDL文件定义一个IBinder对象
public class MyService extends Service {
    public MyService() {
    }


    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return mBinder;
    }


    private IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub() {
        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {


        }


        @Override
        public int add(int x, int y) throws RemoteException {
            return x + y;
        }


        @Override
        public int min(int x, int y) throws RemoteException {
            return x - y;
        }
    };
}


3、声明:(action的name随便定义)
<service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.administrator.ipcdemo.wlj"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </service>


4、开启服务 startService(new Intent(MainActivity.this,MyService.class));






客户端:
1、拷贝服务端用AIDL文件生成的Java文件到客户端,切记:包名也要是服务端的包名
2、自定义ServiceConnection,得到Binder驱动
private IMyAidlInterface iMyAidlInterface;


    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("wanlijun","onServiceConnected");
            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
        }


        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("wanlijun","onServiceDisconnected");
            iMyAidlInterface = null;
        }
    };

3、绑定服务(action为服务端定义的,这里一定要指定服务端的包名,不然找不到服务,提示Service Intent must be explicit的错误 )
 Intent intent = new Intent();
                intent.setAction("com.example.administrator.ipcdemo.wlj");
                intent.setPackage("com.example.administrator.ipcdemo");
                bindService(intent,connection,BIND_AUTO_CREATE);

   解除绑定unbindService(connection);
   调用方法
   if(iMyAidlInterface != null){
                    try {
                        int add = iMyAidlInterface.add(7,8);
                        Toast.makeText(MainActivity.this,add+"",Toast.LENGTH_LONG).show();
                    }catch (RemoteException e){
                        e.printStackTrace();
                    }


                }
   

猜你喜欢

转载自blog.csdn.net/u010015933/article/details/80936530