AIDL進程間通訊java
service端android
聲明一個DataService.aidl接口(aidl中不要忘了添加包名)this
interface DataService{ int getString(String str); boolean getList(in List<String> list,out List<String> list2); void showPeron(in Person perosn); }
參數中的in:表示接收數據;out:表示發送數據;也能夠是inoutspa
該類在gen目錄下會自動生成一個DataService.java的文件,DataService.Stub在client中得到DataService的實體類和 IBinder對像code
聲明一個Servicexml
Public class ServiceService{ Binder binder = DataService.Stub(){ //DataService的抽象方法,處理要輸入輸出的數據 int getString(String str){ if("hello".equals("hello")){ return 1; } return 0; } boolean getList(int List<String> list,List<String> list2){ //輸出list查看 list2.add("name"); if(list.getSize()>0){ return true; } return false; } showPerson(Person person){ //輸出perons的數據 } }; onCreate(){} onDestroy(){} onBinder(){ return binder; } }
Activity中啓動service對象
Intent intent = new Intent(this,ServiceSerivice.class); startService(intent);
配置文件中註冊ServiceService,繼承
<service android:name=".ServiceService"> <intent-filter> <action android:name="DataService.aidl的包名+接口名字"/> </intent-filter> </service>
client端接口
新建一個DataService.aidl,包名跟service端的DataService.aidl包名相同進程
Activity綁定service,而後調用服務數據交互
Intent intent = new Intent(DataService.class.getName()); bindService(intent,connection,Context.BIND_AUTO_CREATE); ServiceConnection connection = new ServiceConncetion(){ onServiceDisconnceted(ComponentName name){} onServiceConnected(ComponentName name, Ibinder servcie){ DataService dataService = DataService.Stub.asInterface(service); int result = dataService.getString("hello"); ArrayList<String> list = new ArrayList<String>{}; list.add("a"); ArrayList<String> list2 = new ArrayList<String>{}; boolean result2 = dataService.getList(list,list2); //輸出result、result一、lsit2 } }
若是須要傳遞自定義的實體類,實體類需序列化(Serializable、Parcelable),二者之間的區別:(java中)Serializable, 這個接口序列化內部操做看不到,不能更改。android中認爲Serializable中的機制不符合咱們的需求。
Service端和客戶端須要在.aidl的包下建立實體類和它的aidl文件。如:Person.java和Person.aidl
Person.aidl中內容
Parcelable Person;//用來約束Person這個對象
PerSon.java序列化繼承Parcelable
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>(){ Person createFromParcel(Parcel source){ return new Person(source); } Person[] newArray(int size){ return new Person[size]; } };//公有靜態 void writeToParcel(Parcel dest,int flags){ dest.writeInt(age); dest.writeString(name); } public Person(Parcel parcel){ readFromParcel(parcel); } void readFromParcel(Parcel in){ age = in.readInt(); name = in.readString(); }