AIDL接口描述语言,在android中用来实现IPC非常方便。
一.服务端
1.在工程A中是实现AIDL文件IMyService.aidl,写法无误会在gen目录下自动生成IMyService.java
package com.jyc.aidl.demo;
interface IMyService{
String getValue(String key);
}
2.创建Service,onBind()函数需要返回IMyService.Stub对象,AIDL中定义的函数在Stub中实现,最后在AndroidMainifest.xml中注册此Service,需要定义此Service的action,这样客户端才能用Intent来绑定此Service。
package com.jyc.demo.outmode;
import com.jyc.aidl.demo.IMyService;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class MyService extends Service {
int i =0;
@Override
public IBinder onBind(Intent arg0) {
return new IMyService.Stub(){
@Override
public String getValue(String key) throws RemoteException {
i++;
return "from service:"+i;
}};
}
}
二.客户端
1.拷贝服务端中gen下面由aidl自动生成的java文件(连带包路径一起)至客户端的src中,这样才可以调用服务端的接口
2.用bindServiced的方式启动service代码如下
package com.jyc.aidl.client.demo;
import com.jyc.aidl.demo.IMyService;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
public class AIDLClientActivity extends Activity {
private Button but;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bindMyService();
but = (Button)findViewById(R.id.button1);
but.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
but.setText(myService.getValue("aa"));
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
private void bindMyService(){
this.bindService(new Intent("com.jyc.MYSERVICE.AIDL"), conn, Context.BIND_AUTO_CREATE);
}
IMyService myService = null;
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
myService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myService = IMyService.Stub.asInterface(service);
}
};
}
工程下载地址: