进程间通讯AIDL的使用

首先新建两个工程:一个远程服务进程(A),另一个(B)调用远程服务中的方法

在A中:1、新建服务 RemoteService.java

package com.itheima.my;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class RemoteService extends Service {
    public RemoteService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //throw new UnsupportedOperationException("Not yet implemented");
        System.out.println("onBind方法");
        return new MySservice();

    }
    class MySservice extends PublicBuisess.Stub{
        public void Qianxian(){
            Banzheng();
        }
    }

    public void Banzheng(){
        System.out.println("·········办证·········");
    }
    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("Creat方法");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("Destroy方法");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("onStartCommand方法");
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("onUnbind方法");
        return super.onUnbind(intent);
    }


}

2、在A进程中,把远程Service里面的方法抽取为接口,新建AIDL文件,生成接口文件;中间人类继承Stub类;

package com.itheima.my;

// Declare any non-default types here with import statements

interface PublicBuisess {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void Qianxian();
}

Android Studio实现Service AIDL

3、Androidmanifest文件中为RemoteService 添加Intent-filter入口

<service
            android:name=".RemoteService"
            android:enabled="true"
            android:exported="true" >
            <intent-filter>
                <action android:name="oom.itheima.remote"/>
            </intent-filter>
        </service>

在B进程中:
1、在B进程中,把A中AIDL文件复制到B中(保证包名相同),生成接口文件;

PublicBuinise pb = Stub.asInterface(service);


intent = new Intent();
intent.setAction("oom.itheima.remote");
cnn = new MyServiceConnection();

猜你喜欢

转载自blog.csdn.net/a987687115/article/details/50392441