首先解释一下什么是AIDL
AIDL就是Android Interface Defind Language 安卓接口定义语言。
在Android中的主要作用是跨进程通信。
1.首先要使用AIDL必须要有.aidl文件,里面定义的是一些接口。
2.如果.aidl文件没有错误,将会在gen包下生成这个.audl文件的.java文件
a.生成的.Java文件是一个接口,这个接口会继承android.os.Interface这个类
b.在这个接口中会自动生成一个Stub的抽象类,这个类继承了android.os.Binder这个类,实现了我们aidl文件接口
3.实现aidl文件中的内部抽象类Stub
4.实现service中的onBinder方法
5. 在要绑定到该Service的Activity中 创建ServiceConnection对象的onServiceConnected方法中调用 AIDL接口.Stub
的asInterface(binder)将绑定后返回的binder对象转换为AIDL接口对象
首先在我们的工程中创建一个自定义的.aidl文件。
这里我写的代码如下:
package com.example.aidl;
interface MyAIDL{
void onCreate();
void onStart();
void onStop();
}
然后在Service中的代码:
package com.example.service;
import com.example.aidl.MyAIDL;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class MyService extends Service {
public class MyBinder extends MyAIDL.Stub{
@Override
public void onCreate() throws RemoteException {
// TODO Auto-generated method stub
}
@Override
public void onStart() throws RemoteException {
// TODO Auto-generated method stub
}
@Override
public void onStop() throws RemoteException {
// TODO Auto-generated method stub
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
测试我们的跨进程:
在activity中的代码如下:
package com.example.test_aidl_activity;
import com.example.aidl.MyAIDL;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;
public class MainActivity extends Activity {
private MyAIDL my_aidl;
ServiceConnection sconn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
my_aidl = MyAIDL.Stub.asInterface(service);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("com.example.action.BIND_SERVICE");
bindService(intent, sconn, BIND_AUTO_CREATE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}