The use of AIDL for interprocess communication

First create two new projects: a remote service process (A), and the other (B) to call the methods in the remote service

In A: 1. New service 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. In the A process, extract the methods in the remote service as interfaces, create a new AIDL file, and generate an interface file; the intermediate human inherits the Stub class;

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 implements Service AIDL

3. Add an Intent-filter entry for RemoteService in the Androidmanifest file

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

In the B process:
1. In the B process, copy the AIDL file in A to B (guarantee the same package name), and generate the interface file;

PublicBuinise pb = Stub.asInterface(service);


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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325805438&siteId=291194637