以前的一篇文章說過了Binder機制的總結與應用,裏面的是《Android開發藝術探索》一書的例子,今天特地將Binder機制應用到雙應用之間的通訊上,看是否能夠實現跨進程的通訊。java
一、首先建立兩個aidl文件,分別爲Phone.aidl
、IPhoneManager.aidl
,分別表示一個實體類和一個管理類。以下圖所示: android
Phone.aidl的具體代碼以下:ios
// Phone.aidl
package com.example.runningh.myapplication.phone;
// Declare any non-default types here with import statements
parcelable Phone;
複製代碼
IPhoneManager.aidl的具體代碼以下:bash
// IPhoneManager.aidl
package com.example.runningh.myapplication.phone;
import com.example.runningh.myapplication.phone.Phone;
// Declare any non-default types here with import statements
interface IPhoneManager {
List<Phone> getPhoneList();
void addPhone(in Phone phone);
}
複製代碼
二、而後建立Phone.java
類,Phone.java
類的package路徑必需要和上面建立的Phone.aidl
路徑保持一致,不然即便IPhoneManager.java
類編譯出來了仍是會報錯。上面的例子,Phone.java
的package路徑爲com.example.runningh.myapplication.phone,以下圖所示: app
Phone.java的代碼以下所示:ide
package com.example.runningh.myapplication.phone;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by RunningH on 2018/1/11.
*/
public class Phone implements Parcelable {
public String phoneName;
public int price;
public int density;
public Phone(String phoneName, int price, int density) {
this.phoneName = phoneName;
this.price = price;
this.density = density;
}
protected Phone(Parcel in) {
this.phoneName = in.readString();
this.price = in.readInt();
this.density = in.readInt();
}
public static final Creator<Phone> CREATOR = new Creator<Phone>() {
@Override
public Phone createFromParcel(Parcel in) {
return new Phone(in);
}
@Override
public Phone[] newArray(int size) {
return new Phone[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(phoneName);
dest.writeInt(price);
dest.writeInt(density);
}
}
複製代碼
三、接着執行build命令,生成IPhoneManager.java
文件,具體能夠在build/generated/source/aidl/debug/xxx下面找到,例如我本身的就是在build/generated/source/aidl/debug/com.example.runningh.myapplication/phone目錄下,以下圖所示: 佈局
四、最後就是編寫客戶端和服務端的通訊類了,咱們使用PhoneActivity啓動服務端的遠程服務來和服務端進行通訊。以下是PhoneActivity類的代碼:ui
package com.example.runningh.myapplication.phone;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.TextView;
import com.example.runningh.myapplication.R;
import java.util.List;
/**
* Created by RunningH on 2018/1/11.
*/
public class PhoneActivity extends Activity {
TextView phoneListView;
TextView phonePriceView;
private TextView phoneDensityView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.phone_activity);
phoneListView = (TextView) findViewById(R.id.phone_list);
phonePriceView = (TextView) findViewById(R.id.phone_price);
phoneDensityView = (TextView) findViewById(R.id.phone_density);
getDataFromRemote();
}
private void getDataFromRemote() {
//這裏的」com.example.runningh.phoneservice"是後面服務端Service定義的action的名字 Intent intent = new Intent("com.example.runningh.phoneservice"); //這裏的"com.example.runningh.myapplicationtest"爲服務端APP的包名,不設置會報錯 intent.setPackage("com.example.runningh.myapplicationtest"); bindService(intent, new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { //獲取服務端的IPhoneManager對象的代理 IPhoneManager iPhoneManager = IPhoneManager.Stub.asInterface(service); try { final List<Phone> phoneList = iPhoneManager.getPhoneList(); //獲取服務端的Phone列表 if (phoneList != null && phoneList.size() > 0) { final StringBuilder nameBuilder = new StringBuilder(); final StringBuilder priceBuilder = new StringBuilder(); final StringBuilder densityBuilder = new StringBuilder(); for (Phone phone : phoneList) { nameBuilder.append("phoneName=" + phone.phoneName + "; "); priceBuilder.append("price=" + phone.price + "; "); densityBuilder.append("density=" + phone.density + "; "); } //因爲這裏是在子線程,因此展現信息時要在主線程運行 runOnUiThread(new Runnable() { @Override public void run() { phoneListView.setText(nameBuilder.toString()); phonePriceView.setText(priceBuilder.toString()); phoneDensityView.setText(densityBuilder.toString()); } }); //客戶端將新建一個Phone類添加到服務端 iPhoneManager.addPhone(new Phone("vivo", 2900, 2000)); } } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { } }, BIND_AUTO_CREATE); } } 複製代碼
上面簡單地在Activity中開啓了一個遠程服務,鏈接到了服務端,並獲取服務端的代理對象,而後獲取服務端的信息,同時也實現了將客戶端的信息添加到服務端。 佈局文件的代碼就不貼出來了,也就是幾個TextView,來對服務端的信息進行展現。this
特別須要注意的是,客戶端鏈接服務端對象時,還要設置服務端的包名,不然會報錯。如上面的代碼所示,使用intent.setPackage設置了服務端的包名。spa
一、將客戶端的兩個aidl文件,Phone.aidl
、IPhoneManager.aidl
複製到服務端,而且保持package路徑一致。以下圖所示:
二、將客戶端的實體類Phone.java
複製到服務端,而且保持package路徑一致。以下圖所示:
三、定義一個服務類,PhoneService.java
,客戶端開啓的服務就是這個服務,在這個服務中返回服務端的代理對象給到客戶端。代碼以下所示:
package com.example.runningh.myapplication;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import com.example.runningh.myapplication.phone.IPhoneManager;
import com.example.runningh.myapplication.phone.Phone;
import java.util.ArrayList;
import java.util.List;
/**
* Created by RunningH on 2018/1/12.
*/
public class PhoneService extends Service {
private Binder myBinder = new IPhoneManager.Stub() {
@Override
public List<Phone> getPhoneList() throws RemoteException {
Phone phone = new Phone("android", 1000, 500);
List<Phone> phones = new ArrayList<>();
phones.add(phone);
phones.add(new Phone("ios", 5000, 1000));
return phones;
}
@Override
public void addPhone(Phone phone) throws RemoteException {
Intent intent = new Intent();
intent.putExtra("phone", phone);
intent.setAction("test");
sendBroadcast(intent); //將客戶端發過來的信息經過廣播的形式發送給Activity,Activity再進行展現。
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return myBinder; //返回一個代理對象給客戶端
}
}
複製代碼
還記得客戶端鏈接服務端Service的代碼嗎?該Service就是客戶端須要啓動的對象。咱們須要在Manifest中註冊該Service,而且設置過濾的Action。以下所示:
<service android:name="com.example.runningh.myapplication.PhoneService">
<intent-filter>
<action android:name="com.example.runningh.phoneservice" />
</intent-filter>
</service>
複製代碼
四、新建一個Activity,叫作MainActivity好了。裏面要作的事情是註冊一個廣播並監聽PhoneService發過來的內容,對客戶端的信息進行展現。具體代碼以下:
package com.example.runningh.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.example.runningh.myapplication.phone.Phone;
import com.example.runningh.myapplicationtest.R;
public class MainActivity extends AppCompatActivity {
private TextView infoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoView = (TextView) findViewById(R.id.info);
registerReceiver(new MyReceiver(), new IntentFilter("test"));
}
class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("test")) {
final Phone phone = intent.getParcelableExtra("phone");
runOnUiThread(new Runnable() {
@Override
public void run() {
infoView.setText("phone.name=" + phone.phoneName + "; phone.price=" + phone.price + "; phone.desity=" + phone.density);
}
});
}
}
}
}
複製代碼
通過了上述客戶端和服務端兩步,咱們完成了客戶端和服務端的邏輯代碼,分別啓動安裝上述的客戶端和服務端的APP,從客戶端能夠看到服務端的信息,而從服務端能夠看到從客戶端傳遞過來的信息,從而使用Binder實現了應用間的跨進程通訊。最後看一下客戶端和服務端的截圖: