前言
之前的一篇文章说过了Binder机制的总结与应用,里面的是《Android开发艺术探索》一书的例子,今天特意将Binder机制应用到双应用之间的通信上,看是否可以实现跨进程的通信。
客户端
1、首先创建两个aidl文件,分别为Phone.aidl
、IPhoneManager.aidl
,分别表示一个实体类和一个管理类。如下图所示:
Phone.aidl的具体代码如下:
// Phone.aidl
package com.example.runningh.myapplication.phone;
// Declare any non-default types here with import statements
parcelable Phone;
IPhoneManager.aidl的具体代码如下:
// 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 getPhoneList();
void addPhone(in Phone phone);
}
2、然后创建Phone.java
类,Phone.java
类的package路径必须要和上面创建的Phone.aidl
路径保持一致,否则即使IPhoneManager.java
类编译出来了还是会报错。上面的例子,Phone.java
的package路径为com.example.runningh.myapplication.phone,如下图所示:
Phone.java的代码如下所示:
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 CREATOR = new Creator() {
@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);
}
}
3、接着执行build命令,生成IPhoneManager.java
文件,具体可以在build/generated/source/aidl/debug/xxx下面找到,例如我自己的就是在build/generated/source/aidl/debug/com.example.runningh.myapplication/phone目录下,如下图所示:
4、最后就是编写客户端和服务端的通信类了,我们使用PhoneActivity启动服务端的远程服务来和服务端进行通信。如下是PhoneActivity类的代码:
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 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,来对服务端的信息进行展示。
特别需要注意的是,客户端连接服务端对象时,还要设置服务端的包名,否则会报错。如上面的代码所示,使用intent.setPackage设置了服务端的包名。
服务端
1、将客户端的两个aidl文件,Phone.aidl
、IPhoneManager.aidl
复制到服务端,并且保持package路径一致。如下图所示:
2、将客户端的实体类Phone.java
复制到服务端,并且保持package路径一致。如下图所示:
3、定义一个服务类,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 getPhoneList() throws RemoteException {
Phone phone = new Phone("android", 1000, 500);
List 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。如下所示:
4、新建一个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实现了应用间的跨进程通信。最后看一下客户端和服务端的截图: