- 定义一个AIDL接口(扩展名.aidl):
package com.example.aidlservice;
interface ICat {
String getColor();
double getWeigth();
}
- 定义一个service
public class AidlService extends Service {
private String color;
private double weight;
private CatBinder catBinder;
Timer timer = new Timer();
String[] colors = new String[]{"红色","白色","黑色"};
@Override
public IBinder onBind(Intent arg0) {
return catBinder;
}
public class CatBinder extends Stub{
@Override
public String getColor() throws RemoteException {
return color;
}
@Override
public double getWeigth() throws RemoteException {
return weight;
}
}
@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 = Math.random()*100;
}
}, 0, 800);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
timer.cancel();
}
}
- Manifest文件
<service android:name=".AidlService">
<intent-filter >
<action android:name="com.example.aidlservice.AIDL_SERVICE"/>
</intent-filter>
</service>
这样,远程调用的servcie就定义好了,在开发工具中,是单独的一个项目哦,然后生成apk,安装。
- Activity调用,要新建一个工程,然后将aidl文件复制到新的项目中。
- activity代码:
public class AIDLActivity extends Activity {
ICat catService;
TextView tView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activitylist);
Button button4 = (Button) this.findViewById(R.id.activitylistbutton4);
tView = (TextView) this.findViewById(R.id.tvw);
Intent intent = new Intent();
intent.setAction("com.example.aidlservice.AIDL_SERVICE");
bindService(intent, connection, Service.BIND_AUTO_CREATE);
button4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
tView.setText(catService.getColor()+"----"+catService.getWeigth());
} catch (RemoteException e) {
e.printStackTrace();
}
Toast.makeText(AIDLActivity.this, "服务已经启动", Toast.LENGTH_LONG).show();
}
});
}
@Override
protected void onStart() {
super.onStart();
}
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
System.err.println("service is unconnected");
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//System.err.println(ICat==null);
catService = ICat.Stub.asInterface(service) ;
System.err.println("service is connected");
}
};
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
};
}