以前的一篇文章说过了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实现了应用间的跨进程通讯。最后看一下客户端和服务端的截图: