在Android系统中,各应用程序都运行在各自的系统中,进程之间无法直接进行数据的交换。如果需要通信,就需要使用AIDL。
一、创建AIDL文件
package com.example.aidlexample;
interface Dog{
String getDogName();
String getDogWeight();
}
二、将Service里的数据暴露出来
当访问者启动DogDescribe 服务时,将返回一个IBinder对象给访问者。访问者利用这个对象,就可以进行数据访问。
package com.example.aidlexample;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import com.example.aidlexample.Dog.Stub;
public class DogDescribe extends Service {
private String dogweight;
private String dogname;
private DogBinder dogbinder;
//将IBinder对象返回给访问者
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return dogbinder;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
dogbinder = new DogBinder();
}
// 继承自动代码生成的类Stub(实现了IBinder接口)
public class DogBinder extends Stub {
@Override
public String getDogName() throws RemoteException {
// TODO Auto-generated method stub
return "xiaokeai";
}
@Override
public String getDogWeight() throws RemoteException {
// TODO Auto-generated method stub
return "30kg";
}
}
}
三、访问者访问service提供的数据
访问者利用bindService(),在一个activity中,以bind方式启动一个Service。同时拿到一个Binder对象。
package com.example.aidlexample;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
public class MainActivity extends Activity {
private Dog doginfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent it = new Intent();
ComponentName comp = new ComponentName(MainActivity.this,
DogDescribe.class);
it.setComponent(comp);
bindService(it, conn, Service.BIND_AUTO_CREATE);
}
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
System.out.println("service disconn");
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
doginfo = Dog.Stub.asInterface(service);
try {
System.out.println("serviceconnected" + doginfo.getDogName()
+ doginfo.getDogWeight());
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
this.unbindService(conn);
System.out.println("service unbind");
}
}