您的位置:首页 > 移动开发 > Android开发

Android 使用Messenger和Aidl实现跨进程通信

2018-03-30 16:03 696 查看
Android Messenger和Aidl的使用
1.怎么使用多进程
为安卓的四大组件设置process属性值例如:android:process=":test"或者 android:process="com.lz.test.process"上述指定进程方式的不同,以:号开头的进程名字是包名+:test,而后面一种是完整的进程名字。前者是应用的私有进程,其他应用组件不可访问,后者可以通过ShareUID的方式和他跑在同一进程中。
2.使用messenger实现进程间的通信 
   2.1 在service中使用handler创建messenger对象Handler serviceHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.i(TAG,msg.toString());
Messenger messenger = msg.replyTo;
if(messenger != null){
Message msgBack = new Message();
msgBack.what = 2;
try {
Log.i(TAG,"call back msg");
messenger.send(msgBack);
} catch (RemoteException e) {
e.printStackTrace();
}
}else{
Log.i(TAG,"error call back messenger == null !");
}
}
};

Messenger serviceMessenger = new Messenger(serviceHandler);   2.2 在service的onbind方法中返回messenger中的binder@Override
public IBinder onBind(Intent intent) {
Log.i(TAG,"onBind");
return serviceMessenger.getBinder();
}这样service中的处理就完成了
   2.3在需要绑定的service的组件中绑定这个service Intent intent = new Intent(MainActivity.this,TestService.class);
bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE);绑定service是我们需要传入serviceConnection对象
  2.4 创建ServiceConnectionServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.i(TAG,"onServiceConnected");
messenger= new Messenger(iBinder);
}

@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.i(TAG,"onServiceDisconnected");
}
};绑定service的时候,会回调serviceConnection的onServiceConnection方法,返回service中的binder对象
 2.5 使用onServiceConnection中返回的binder获得messenger传递数据if(messenger != null){
Log.i(TAG,"send msg");
Message msg = new Message();
//这边需要注意一下,obj不能跨进程传递
// msg.obj = "";
msg.what = 1;
try {
/*
* 如果需要service在传信息过来,就新加messenger传递过去
*/
msg.replyTo = new Messenger(new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.i(TAG,"get msg in mainActivity " + msg.toString());
}
});
messenger.send(msg);

} catch (RemoteException e) {
e.printStackTrace();
}
}else{
Log.i(TAG,"error messenger == null !");
}这边传递数据使用的是Message,这边obj是不支持跨进程通信的。
demo下载地址:点击打开链接
3.使用aidl实现跨进程的通信
  3.1 创建需要跨进程使用的类,实现parcelable接口public class Student implements Parcelable {
int id;
String name;

public Student(int id, String name) {
this.id = id;
this.name = name;
}

protected Student(Parcel in) {
id = in.readInt();
name = in.readString();
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
}

@Override
public int describeContents() {
return 0;
}

public static final Creator<Student> CREATOR = new Creator<Student>() {
@Override
public Student createFromParcel(Parcel in) {
return new Student(in);
}

@Override
public Student[] newArray(int size) {
return new Student[size];
}
};
}3.2 定义上面创建的类的aidl文件// IStudent.aidl
package com.lz.aidldemo;

// Declare any non-default types here with import statements
parcelable Student;声明这个类实现了序列化接口
3.3 定义跨进程需要处理的方法定义的aidl// Declare any non-default types here with import statements
import com.lz.aidldemo.Student;

interface IStudentManager {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
List<Student> getAllStudent();
void addStudent(in Student student);
}这边定义了添加和获取所有学生的方法定义
3.4 build下这个model,在build文件夹下就会生成IStudentManager类文件



3.5 定义service中的IStuManager的处理public class TestService extends Service {
private static final String TAG = "lz_do_TestService";
//CopyOnWriteArrayList支持并发的读写操作,内部实现了同步机制
CopyOnWriteArrayList <Student>studentList = new CopyOnWriteArrayList<Student>();

Binder binder = new IStudentManager.Stub() {
@Override
public List<Student> getAllStudent() throws RemoteException {
return studentList;
}

@Override
public void addStudent(Student student) throws RemoteException {
studentList.add(student);
}
};

@Override
public IBinder onBind(Intent intent) {
Log.i(TAG,"onBind");
return binder;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG,"onStartCommand");
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
Log.i(TAG,"onDestroy");
super.onDestroy();
}

@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG,"onUnbind");
return super.onUnbind(intent);
}
}
3.6 在需要绑定的组件中绑定这个servicepublic class MainActivity extends Activity {
private final String TAG = "lz_do_MainActivity";
IStudentManager binder;

ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.i(TAG,"onServiceConnected");
binder = IStudentManager.Stub.asInterface(iBinder);
}

@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.i(TAG,"onServiceDisconnected");
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void onClick(View v){
switch (v.getId()){
case R.id.bt:
Log.i(TAG,"bind click");
Intent intent = new Intent(MainActivity.this,TestService.class);
bindService(intent,connection, Context.BIND_AUTO_CREATE);
break;
case R.id.bt_add:
Log.i(TAG,"add click");
if(binder != null){
try {
Log.i(TAG,"add click xiao wang");
binder.addStudent(new Student(1,"xiao wang"));
} catch (RemoteException e) {
e.printStackTrace();
}
}else{
Log.i(TAG,"add click error binder == null !");
}
break;
case R.id.bt_get:
Log.i(TAG,"get click");
if(binder != null){
try {
Log.i(TAG,"get click xiao wang");
List<Student> list = binder.getAllStudent();
Log.i(TAG,"get list=" + list.toString());
} catch (RemoteException e) {
e.printStackTrace();
}
}else{
Log.i(TAG,"get click error binder == null !");
}
break;
default:

}
}
}这边添加了三个按钮,绑定service,addStudent和getAllStudent。
aidl的demo下载地址:点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: