service进阶之跨进程调用

Android系统中,各应用都运行在自己的进程中,进程之间要进行数据交换,可使用AIDL服务,AIDL是进程之间定义的通信接口。
1、定义AIDL远程接口,以.aidl结尾。Android SDK目录下的platform-tools子目录下的aidl.exe为该接口提供实现,如果是adt开发工具,会自动生成。生成的接口中包含一个Stub内部类,该内部类实现了IBinder、ICat两个接口,这个Stub类将会作为远程service的回调类——它实现了IBinder接口,因此可作为Service的onBind()方法的返回值。
例:定义com\service\ICat.aidl
package com.service;
interface ICat {
String getColor();
double getWeigth();
}
2、将接口暴露给客户端,在A应用(确保定义了如上的aidl接口)中定义一个service类代码,代码如下:
public class AidlService extends Service{
private CatBinder catBinder;
Timer timer = new Timer();
String[] colors = new String[]{"红色","黄色","黑色"};
double[] weights = new double[]{2.3,3.1,1.58};
@Override
public IBinder onBind(Intent intent) {
return catBinder;
}


@Override
public void onCreate() {
super.onCreate();
catBinder = new CatBinder();
timer.schedule(new TimerTask() {

@Override
public void run() {
int rand = (int)(Math.random()*3);
color = colors[rand];
weight = weights[rand];
System.out.println(rand+"=========rand");
}
}, 0, 800);
}
@Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
}
private String color;
private double weight;
public class CatBinder extends Stub{

@Override
public String getColor() throws RemoteException {
return color;
}

@Override
public double getWeigth() throws RemoteException {
return weight;
}
}
}
该service类开发完后,需要配置:
        <service android:name="com.service.AidlService">
            <intent-filter>
                <action android:name="com.service.aidl.action.AIDL_SERVICE"/>
            </intent-filter>
        </service>
3、B应用访问AIDLService,B应用也务必定义AIDL接口,和1步骤中一样:
public class AidlClient extends Activity{
private ICat catService;
private Button get;
EditText color,weight;

private ServiceConnection conn = new ServiceConnection() {

@Override
public void onServiceDisconnected(ComponentName name) {
catService = null;
}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//获取远程Service的onBind方法返回的对象的代理
catService = ICat.Stub.asInterface(service);

}
};
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aild_client);
get = (Button) findViewById(R.id.getService);
color = (EditText) findViewById(R.id.color);
weight = (EditText) findViewById(R.id.weight);
//创建所需绑定的Intent
Intent intent = new Intent("com.service.aidl.action.AIDL_SERVICE");
//绑定远程服务
bindService(intent, conn, Service.BIND_AUTO_CREATE);
get.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
try {
color.setText(catService.getColor());
weight.setText(catService.getWeigth()+"");
} catch (RemoteException e) {
// TODO: handle exception
}

}
});
};
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(conn);
}
}

你可能感兴趣的:(service远程调用,AIDL服务)