AIDL 用来实现跨进程通信,由处在不同进程的两个服务端和客户端组成。使用起来并不怎么复杂,跟我们平常定义接口、调用差不多,不过在创建 AIDL 接口时有一些细节要注意。下面的内容主要分三部分:AIDL 接口创建;客户端向服务端发送数据;服务端向客户端返回数据。
-
AIDL支持以下数据类型
1.基本数据类型:int、long、char、boolean、double;
2.String 和 CharSequence;
3.ArrayList HashMap ;
4.实现 Parcelable 的对象
5.AIDI本身也可以在AIDL 文件中使用;
先看看Demo中的文件结构:
- AIDL实现三步走
服务端
1)创建Service监听客户端的连接请求;
2)创建AIDL文件,声明要暴露在客户端处理的接口;
3)实现AIDL 接口;客户端
1)绑定Service;
2)将服务端的Binder对象转成AIDL接口所属类型;
3)调用AIDL中的方法;AIDL接口创建
创建AIDL文件:定义了一个接口和相关方法
package com.lisheny.aidl;
import com.lisheny.aidl.Book;
import com.lisheny.aidl.IOnNewBookArrivedListener;
interface IMyBookmanager {
List<Book> getBooks();
void addBook(in Book book);
void registerListener (IOnNewBookArrivedListener listener);
void unRegisterListener (IOnNewBookArrivedListener listener);
}
上面 AIDL 文件中用到了自定义Parcelable对象 Book
和 IOnNewBookArrivedListener
,需要创建一个同名的 AIDL 文件 Book.aidl
和 IOnNewBookArrivedListener.aidl
package com.lisheny.aidl;
parcelable Book;
定义一个新书添加监听接口
package com.lisheny.aidl;
import com.lisheny.aidl.Book;
interface IOnNewBookArrivedListener {
void onNewBookArrived (in Book newBook);
}
AIDL 文件的包结构在服务端和客户端中要保持一致,为了方便开发,建议所有AIDL文件全部放入同一包中。
服务端 Service 的实现:
public class AIDLService extends Service {
//CopyOnWriteArrayList 支持并发读写(多个客户端同时连接时可以处理线程同步)
private CopyOnWriteArrayList<Book> mBooks = new CopyOnWriteArrayList<>();
private AtomicBoolean isServieceDestoryed = new AtomicBoolean(false);
private RemoteCallbackList<IOnNewBookArrivedListener> listeners = new RemoteCallbackList<>();
private Binder mBinder = new IMyBookmanager.Stub() {
@Override
public List<Book> getBooks() throws RemoteException {
return mBooks;
}
@Override
public void addBook(Book book) throws RemoteException {
mBooks.add(book);
}
@Override
public void registerListener(IOnNewBookArrivedListener listener) throws RemoteException {
listeners.register(listener);
}
@Override
public void unRegisterListener(IOnNewBookArrivedListener listener) throws RemoteException {
listeners.unregister(listener);
}
};
@Override
public void onCreate() {
super.onCreate();
//为了更直观展示,开个线程,5秒添加一本新书,发出一次通知
new Thread(new Runnable() {
@Override
public void run() {
while (!isServieceDestoryed.get()){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Book newBook = new Book("boook",1);
try {
onNewBookArrived(newBook);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
}).start();
}
private void onNewBookArrived (Book book) throws RemoteException{
mBooks.add(book);
//RemoteCallbackList 并不是一个 List,遍历要用下面方式,beginBroadcast 、finishBroadcast 函数要配对使用
final int N = listeners.beginBroadcast();
for (int i =0; i < N ; i++){
IOnNewBookArrivedListener listener = listeners.getBroadcastItem(i);
if (listener != null){
listener.onNewBookArrived(book);
}
}
listeners.finishBroadcast();
}
@Override
public void onDestroy() {
isServieceDestoryed.set(true);
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
然后在 AndroidManifest.xml 中注册:
<service android:name=".AIDLService">
<intent-filter>
<!--是客户端用于访问AIDL服务的ID -->
<action android:name="com.lisheny.service" />
</intent-filter>
</service>
再看看客户端的实现:
public class MainActivity extends AppCompatActivity {
private IMyBookmanager myBookmanager;
private List<Book> mBooks;
private Button btnGet,btnSet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//绑定Service
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.lisheny.service"); //识别服务
serviceIntent.setComponent(new ComponentName("com.lisheny.service","com.lisheny.aidl.AIDLService"));
bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);
btnGet = (Button)findViewById(R.id.btn_get);
btnSet = (Button)findViewById(R.id.btn_set);
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
mBooks = myBookmanager.getBooks();
for (Book book : mBooks){
Log.i("从服务端得到数据:",book.getName());
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
btnSet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
myBookmanager.addBook(new Book("php",45));
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
//取消接收服务端通知
if (myBookmanager != null && myBookmanager.asBinder().isBinderAlive()){
try {
myBookmanager.unRegisterListener(listener);
} catch (RemoteException e) {
e.printStackTrace();
}
}
unbindService(connection);
}
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
myBookmanager = IMyBookmanager.Stub.asInterface(iBinder);
try {
//注册新书添加通知
myBookmanager.registerListener(listener);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
// TODO: 2018/6/15 0015 dosomething
//服务端挂了,可以在这里做一些重新连接的操作
}
};
private IOnNewBookArrivedListener listener = new IOnNewBookArrivedListener.Stub() {
@Override
public void onNewBookArrived(Book newBook) throws RemoteException {
Log.d("客户端:","收到通知了"+ newBook.getName());
}
};
}
注意: onServiceConnected 、 onServiceDisconnected 都是运行在 UI 线程中,所以不要在其中做耗时操作;调用远程方法时也要注意耗时导致程序ANR问题,如给 getBooks 加个休眠,运行就会发生ANR:
@Override
public List<Book> getBooks() throws RemoteException {
SystemClock.sleep(5000);
return mBooks;
}
解决办法就是:处理这种问题不要放到UI线程中。
关于AIDL就到这里,这是Demo。