一、AIDL简介
在Android平台中,各个组件运行在自己的进程中,他们之间是不能互相访问的,但是在程序之间是不可避免的要传递一些对象,在进程之间互相通信。为了实现进程之间的互相通信,Android采用了一种轻量级的实现方式RPC(Remote Procedure Call远程进程调用)来完成进程之间的通信,并且通过AIDL(Android interface definition language 安卓接口定义语言)来实现两个进程之间互相访问代码,例如,你在activity里的代码需要访问Service中的一个方法,那么就可以通过这种方式来实现了。
一句话,总之要想使用别的应用里面的service,就要用到AIDL。
二、AIDL使用步骤
将我们定义的接口,改为aidl 文件,然后将这个aidl文件copy到调用者工程内即可。
注意:这个aidl文件copy过去后,包名需要与服务工程内aidl文件的包名一致。
三、远程服务中使用AIDL
步骤:1、创建一个服务这个服务里面有一个要调用的方法。
2、定义一个接口IService,接口里面的抽象方法就是去调用service里面的方法,把Iservice的.java的后缀改为 aidl,把接口中的访问权限全部去掉
3、定义一个mybinder对象 extends Iservice.stub,在onbind方法里面把mybinder返回回去
4、在activity里面通过bindeservice的方法开启服务
5、创建出来一个我们Myconn实现ServiceConnection接口onserviceConnected的方法,这个方法会有一个参 数,这个参数就是mybinder的对象
6、Iservice=Iservice.stub.asInterface(mybinder)
7、调用IService的方法
代码演示:
package com.itheima.remote;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
/**
* 远程需要的服务
* @author LBK
*
*/
public class RemoteService extends Service {
/**
* 定义一个内部类实现Iservice中的方法,调用service的方法methodInService();
* @author LBK
*
*/
private class MyBinder extends IService.Stub{
@Override
public void callMethodInService() {
methodInService();
}
}
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
@Override
public void onCreate() {
System.out.println("远程服务被创建了...");
super.onCreate();
}
@Override
public void onDestroy() {
System.out.println("远程服务被销毁了...");
super.onDestroy();
}
public void methodInService(){
System.out.println("我是远程服务的方法,我被调用了....");
}
}
package com.itheima.caller;
import com.itheima.remote.IService;
import android.app.Activity;
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.view.View;
/**
* 远程调用服务者
* @author LBK
*
*/
public class MainActivity extends Activity {
private MyConn conn;
private IService iService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void bind(View view){
Intent intent = new Intent();
intent.setAction("com.itheima.remote");
conn = new MyConn();
bindService(intent, conn, BIND_AUTO_CREATE);
}
private class MyConn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//通过aidl的生成的子类stub拿到service
iService = IService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
public void call(View view){
try {
iService.callMethodInService();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
aidl的代码:
package com.itheima.remote;
interface IService {
void callMethodInService();
}
一定注意两个应用中aidl所在的包名要一致哦。