Android aidl基本使用

AIDL是Android中IPC(Inter-Process Communication)方式中的一种,AIDL是Android Interface definition language的缩写,AIDL的作用是让你可以跨进程通讯。常用于主进程和Service进程的数据通讯或者,两个app之间的通讯。

1.先写一个aidl文件接口(写完记得Build->Make Project,这样用的地方才能找到接口名字)

interface IMyAidlInterface {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);

    String getInfor(String s,int arg1);

}

2.自定义一个Service (IBinder记得在 onBind方法返回)

public class MyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Utils.log_out("MyService:onBind");
        return binder;
    }


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

        }

        @Override
        public String getInfor(String s, int arg1) {
            Utils.log_out("MyService:"+s+":"+arg1);
            return "success!!!";
        }

    };

    @Override
    public void onCreate() {
        super.onCreate();
        Utils.log_out("MyService:onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Utils.log_out("MyService:onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Utils.log_out("MyService:onDestroy");

    }

    @Override
    public boolean onUnbind(Intent intent) {
        Utils.log_out("MyService:onUnbind");
        return super.onUnbind(intent);
    }

}

3.在MainActivity中(即主线程中)

    private void startAndBindService(){
        Intent service = new Intent(MainActivity.this, MyService.class);
        bindService(service,serviceConnection, Context.BIND_AUTO_CREATE);
    }
    
private IMyAidlInterface myInterface;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myInterface = IMyAidlInterface.Stub.asInterface(service);
            Utils.log_out("Main:链接Service成功");
            try {
                String d = myInterface.getInfor("1",90);
                Utils.log_out("Main:"+d);

            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Utils.log_out("Main:链接Service失败");
        }
    };


4.注意aidl文件位置包名要保持一致(如果是在两个app进程中的话,或者客户端和服务器通讯的话)

发布了11 篇原创文章 · 获赞 0 · 访问量 128

猜你喜欢

转载自blog.csdn.net/qq_32898021/article/details/105432675