android 程序通訊--aidl
阿新 • • 發佈:2019-02-01
最近學習了一下 AIDL 程序通訊,下面是遇到的一些問題簡單羅列一下,好記性不如爛筆頭:
一.程序通訊中傳輸實體(必須是可以 Parcelable)
1.基本資料型別:int,long,short...都可以,其他的List 和Map 也是可以的。
2.包裝類:Integer,Long,Shot 是不可以
3.自定義的資料結構,必須實現Parcelable介面,而且需要在對應的包名目錄下建立相應的實體AIDl檔案:
第一步繼承Parcelable介面
第二步:建立相應地 Person.aidl 檔案:package com.rltx.testndk; import android.os.Parcel; import android.os.Parcelable; public class Person implements Parcelable { private String userName; private Long userId; public Person(){ } public Person(Parcel source){ userId = source.readLong(); userName = source.readString(); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public static Creator<Person> CREATOR = new Creator<Person>() { @Override public Person createFromParcel(Parcel source) { return new Person(source); } @Override public Person[] newArray(int size) { return new Person[0]; } } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(userId); dest.writeString(userName); } }
// Person.aidl
package com.rltx.testndk;
// Declare any non-default types here with import statements
parcelable Person;
4.如何傳輸介面建立介面回撥實現二.ServiceConnection 的啟動,使用了aidl,需要進行服務繫結:// ICallback.aidl package com.rltx.testndk; // Declare any non-default types here with import statements interface ICallback { void onsuccess(in String data); void onfail(in String error); }
第一步需要宣告在Manifest:
第二步需要顯示繫結服務:<service android:name=".task.CoreService" android:process=":person" > <intent-filter> <action android:name="com.rltx.testndk.core"/> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </service>
/**
* 繫結 跨程序服務
*
* @param context 上下文
*/
public void bindService(Context context) {
Intent intent = new Intent(context, CoreService.class);
intent.setAction("com.rltx.<span style="font-size: 9pt; font-family: 宋體;">testndk</span><span style="font-size: 9pt; font-family: 宋體;">.core");</span>
context.bindService(intent, mConn, Context.BIND_AUTO_CREATE);
}