您的位置:首页 > 大数据 > 人工智能

Aidl 实现进程之间的通讯

2016-03-24 01:38 543 查看
遇到进程之间相互通讯的问题时,谷歌官方给我们提供了一种aidl 的方式,通过service 使用,使用方式如下:
first step :
在as project main 目录下 新建一个 aidl 文件,将文件名改为和包名不一样(因为这个包名和类名也要用在另一个项目中),可以建完之后新建一个包,将接口文件拷贝过去即可。

Next:
在另一个app 中同样目录下copy 上边aidl 文件,   并新建service类, service 类中代码,主要是 在onBind() 方法中返回一个,自定义的实现了 Ibinder 接口的类, aidl接口内部 stub内部抽象类 实现了这个接口,可作为 Bind的参数返回,代码如下:


package com.example.liyang.aidluse;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.jash.aidl.IMyAidlInterface;
import com.jash.aidl.IMyAidlInterface.Stub;

public class MyService extends Service {

private static final  String text ="我是来自service 的";
private static final String TAG =MyService.class.getSimpleName();

public MyService() {
}

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new MyBind();
}

class MyBind extends IMyAidlInterface.Stub{

@Override
public String getText() throws RemoteException {
return text;
}

@Override
public void printText(String text) throws RemoteException {

Log.d(TAG, "printText: -------->"+"使用我aidl 的界面 调用我喽");

}
}

}


next :

在other app 的MainActivity ,绑定firstActivity 的服务,并从aidl 接口实现方法中获取值 代码如下:

package com.example.testaidl;

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.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.jash.aidl.IMyAidlInterface;

public class MainActivity extends AppCompatActivity implements ServiceConnection {

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

//start bind servie where is in other app
Intent intent = new Intent();
intent.setClassName("com.example.liyang.aidluse","com.example.liyang.aidluse.MyService");

//you can get HowTOgetit  from parameter
bindService(intent,this,BIND_AUTO_CREATE);
}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {

//when connnect
IMyAidlInterface iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
try {
String text = iMyAidlInterface.getText();
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();

//call service
iMyAidlInterface.printText("回调你喽");
} catch (RemoteException e) {
e.printStackTrace();
}

}

@Override
public void onServiceDisconnected(ComponentName name) {

}
/**
* unbind method
*/
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(this);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: