AndroidStudio的AIDL demo

建立两个module,一个是AIDL服务,另一个是客户端。
AS的module就相当于Eclipse里面的project,AS的project相当于Eclipse的Workspace。

一。服务端
1.建立模块module1
2.在module1工程下,在module1\src\main\下建立aidl文件夹,再建立一个和AndroidManifest里面包名一样的包,
module1\src\main\aidl\interview\cchen\module1,里面建立AIDL文件
路径方法必须这样,然后编译工程。
会在module1\build\generated\source\aidl\debug\interview\cchen\module1路径下,生成与AIDL对应的java接口文件。
这个Java文件时自动生成的,最好不要手动修改,想修改接口,直接修改AIDL文件即可。
3.实现AIDL的接口


public class Service1 extends Service {
    private int mCount;
    IMyAidlInterface1.Stub binder = new IMyAidlInterface1.Stub() {
        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public String getValue() throws RemoteException {
            return mCount++ + " times";
        }

        @Override
        public void clear() throws RemoteException {
            mCount = 0;
        }
    };

    public Service1() {
    }

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



4.修改module1的gradle文件,第一行改为apply plugin: 'com.android.library',作为一个库工程,同时去掉applicationId。

二。客户端
1.建立模块module1_client
2.修改module1_client的gradle文件,在dependencies 中添加compile project(':module1'),引用module1
3.可以通过AIDL和Service1通讯

    private IMyAidlInterface1 mService1;
    ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService1 = IMyAidlInterface1.Stub.asInterface(service);
            updateFromAidl();
        }


        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService1 = null;
        }
    };


    private void updateFromAidl() {
        try {
            String fromAidl = mService1.getValue();
            txt1.setText(fromAidl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

猜你喜欢

转载自ccsosnfs.iteye.com/blog/2212276