AIDL使用

2020-10-10 14:00:40

一.新建一個專案AIDLservice,建立Person類並繼承Parcelable介面。

public class Person implements Parcelable {
    private String name;
    private int grade;
    public Person(String name ,int grade){
        this.name = name;
        this.grade = grade;
    }
    protected Person(Parcel in){
        this.name = in.readString();
        this.grade = in.readInt();
    }
    public static final Creator<Person> CREATOR = new Creator<Person>() {
        @Override
        public Person createFromParcel(Parcel in) {
            return new Person(in);
        }

        @Override
        public Person[] newArray(int size) {
            return new Person[size];
        }
    };
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
    }
}

二.建立Person.aidl

     只有將類在AIDL中宣告後,AIDL才能呼叫該Person類。
在這裡插入圖片描述
三.建立MyAidl.aidl(作用:設定讓使用者端允許呼叫的介面)

在這裡插入圖片描述

四.建立AidlService.java並註冊這個Service

public class AidlService extends Service {
    private ArrayList<Person> persons;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        persons = new ArrayList<>();
        Log.e("AidlService","success onBind");
        return iBinder;
    }

    private IBinder iBinder = new Myaidl.Stub() {
        @Override
        public void addPerson(Person person) throws RemoteException {
            persons.add(person);
        }

        @Override
        public List<Person> getPersonList() throws RemoteException {
            return persons;
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("AidlService","onCreate success");
    }
}

     因為伺服器端的Service需要被使用者端來遠端繫結,所以使用者端要能夠找到這個Service,可以通過先指定包名,之後再設定Action值或者直接指定Service類名的方式來繫結Service。本文將在使用者端通過指定Action值的方式來繫結Service,所以需要將Service在專案AIDLclient的AndroidManifest.xml中進行如下注冊:

<service android:name=".AidlService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="myAidlService"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
 </service>

     此時伺服器端的程式碼就寫完了,下面來寫使用者端的程式碼。
五.再次新建一個專案AIDLclient,把專案AIDLservice中的aidl那個資料夾複製到專案AIDLclient中,把專案AIDLservice中的Person.java複製到專案AIDLclient中,注意這兩次複製時要保證包名不能改變,保證是原封不動的複製。
在這裡插入圖片描述
六.直接修改MainActivity的程式碼:

public class MainActivity extends AppCompatActivity {

    private final String TAG = "AIDLclient";
    private Myaidl myAidl;
    private Button btn;
    private boolean connected;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(TAG,"onServiceConnected success");
            myAidl = Myaidl.Stub.asInterface(service);
            connected = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG,"onServiceDisconnected success");
            myAidl = null;
            connected = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        bindService();
    }

    private void initView(){
        btn = findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if(connected){
                        myAidl.addPerson(new Person("Van",59));
                        List<Person> persons = myAidl.getPersonList();
                        Log.e(TAG,persons.toString());
                    }
                    else {
                        Log.e(TAG,"未連線");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    private void bindService(){
        Intent intent = new Intent();
//        intent.setComponent(new ComponentName("com.example.aidlservice","com.example.aidlservice.AidlService"));
        intent.setPackage("com.example.aidlservice");
        intent.setAction("myAidlService");
        bindService(intent,connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(connected)
            unbindService(connection);
    }
}

七.結果
     先啟動服務APP,再啟動使用者端APP,當用戶端APP啟動後,伺服器端APP的紀錄檔如下:
在這裡插入圖片描述點選使用者端按鈕後用戶端APP紀錄檔如下:
在這裡插入圖片描述