在需要大量并发请求时,Messenger就显得不够用了,Messenger的作用主要是为了传递消息,很多时候我们可能需要跨进程调用服务端的方法,这种情形用Messenger就无法使用了,所以可以使用AIDL来实现跨进程的方法调用。
使用AIDL,需要先创建接口
IBookManager .aidl
package com.cmz_one.aidl;
import com.cmz_one.aidl.Book;
import com.cmz_one.aidl.IOnNewBookArrivedListener;
interface IBookManager {
List<Book> getBookList();
void addBook(in Book book);
void registerListener(IOnNewBookArrivedListener listener);
void unregisterListener(IOnNewBookArrivedListener listener);
}
IOnNewBookArrivedListener.aidl
package com.cmz_one.aidl;
import com.cmz_one.aidl.Book;
interface IOnNewBookArrivedListener {
void onNewBookArrived(in Book newBook);
}
AIDL文件默认支持的数据类型包括:
Java中的八种基本数据类型,包括 byte,short,int,long,float,double,boolean,char。
String 类型。
CharSequence类型。
List:只支持ArrayList,里面的每个元素都必须能被AIDL支持。
Map:只支持HashMap,里面的每个元素都必须能被AIDL支持,包括key和value。
Parcelable:所有实现了Parcelable接口的对象。
AIDL:所有的AIDL接口本身也可在AIDL文件中使用。
需要注意的是,如果AIDL文件使用了自定义的Parcelable对象,必须新建一个和它同名的AIDL文件(Android Studio中需要创建一个别的名字的AIDL文件再Rename成同名的)。
AIDL除了基本的数据类型,其他类型的参数必须标上方向: in(输入型参数,可理解为客户端到服务端)、out(输出型,可理解为是服务端到客户端)、inout(输入输出型参数)。需要根据实际需求去指定参数类型,不能一概使用out或inout,因为在底层会造成开销。
Book.aidl
package com.cmz_one.aidl;
parcelable Book;
自定义的Parcelable对象和AIDL对象必须显示的import进来,不管她们是否和当前的AIDL文件位于同一个包。
Android Studio会出现找不到类的问题,需要在build.gradle的android中添加:
sourceSets{
main {
java.srcDirs = ['src/main/java', 'src/main/aidl']
}
}
book.java
public class Book implements Parcelable {
public int bookId;
public String bookName;
public Book(int bookId, String bookName) {
this.bookId = bookId;
this.bookName = bookName;
}
protected Book(Parcel in) {
bookId = in.readInt();
bookName = in.readString();
}
public static final Creator<Book> CREATOR = new Creator<Book>() {
@Override
public Book createFromParcel(Parcel in) {
return new Book(in);
}
@Override
public Book[] newArray(int size) {
return new Book[size];
}
};
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(bookId);
dest.writeString(bookName);
}
@Override
public String toString() {
return "Book{" +
"bookId=" + bookId +
", bookName='" + bookName + '\'' +
'}';
}
}
在Android Studio中生成Parcelable类很方便,只需implements Parcelable,添加参数,然后根据提示就能自动生成。
服务端
BookManagerService.java
public class BookManagerService extends Service {
private static final String TAG = "BookManagerService";
private CopyOnWriteArrayList<Book> mBookList = new CopyOnWriteArrayList<Book>();
private AtomicBoolean mIsServiceDestoryed = new AtomicBoolean(false);
private RemoteCallbackList<IOnNewBookArrivedListener> mListenerList = new RemoteCallbackList<IOnNewBookArrivedListener>();
private Binder mBinder = new IBookManager.Stub() {
@Override
public List<Book> getBookList() throws RemoteException {
SystemClock.sleep(5000);//模拟服务端耗时操作
return mBookList;
}
@Override
public void addBook(Book book) throws RemoteException {
mBookList.add(book);
}
@Override
public void registerListener(IOnNewBookArrivedListener listener) throws RemoteException {
mListenerList.register(listener);
}
@Override
public void unregisterListener(IOnNewBookArrivedListener listener) throws RemoteException {
mListenerList.unregister(listener);
}
};
@Override
public void onCreate() {
super.onCreate();
mBookList.add(new Book(1, "围城"));
mBookList.add(new Book(2, "解忧杂货店"));
new Thread(new ServiceWorker()).start();
}
@Override
public IBinder onBind(Intent intent) {
//定义权限验证,验证不通过就直接返回null
int check = checkCallingOrSelfPermission("com.cmz_one.aidl.permission.ACCESS_BOOK_SERVICE");
if (check != PackageManager.PERMISSION_DENIED){
return null;
}
return mBinder;
}
@Override
public void onDestroy() {
mIsServiceDestoryed.set(true);
super.onDestroy();
}
private void onNewBookArrived(Book book) throws RemoteException {
mBookList.add(book);
Log.d(TAG, "注册数量:" + mBookList.size());
final int N = mListenerList.beginBroadcast();
for (int i = 0; i < N; i++) {
IOnNewBookArrivedListener l = mListenerList.getBroadcastItem(i);
if (l != null) {
try {
l.onNewBookArrived(book);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
mListenerList.finishBroadcast();
}
private class ServiceWorker implements Runnable {
@Override
public void run() {
while (!mIsServiceDestoryed.get()) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int bookId = mBookList.size() + 1;
Book newBook = new Book(bookId, "new book#" + bookId);
try {
onNewBookArrived(newBook);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
}
}
<service
android:name=".BookManagerService"
android:process=":remote"></service>
<permission android:name="com.cmz_one.aidl.permission.ACCESS_BOOK_SERVICE" android:protectionLevel="normal"/>
CopyOnWriteArrayList支持并发读/写,自动为我们进行线程同步。
RemoteCallbackList是系统专门提供的用于删除跨进程listener的接口,当客户端进程终止后,它能自动移除客户端所注册的listener。RemoteCallbackList内部自动实现了线程同步功能,所以使用它来注册和解注册时,不需要做额外的线程同步工作。
使用RemoteCallbackList要注意,不能像List一样去操作,遍历RemoteCallbackList需要按下面的方式进行。
final int N = mListenerList.beginBroadcast();
for (int i = 0; i < N; i++) {
IOnNewBookArrivedListener l = mListenerList.getBroadcastItem(i);
if (l != null) {
//
}
}
mListenerList.finishBroadcast();
beginBroadcast和finishBroadcast必须要配对使用。
客户端
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final int MESSAGE_NEW_BOOK_ARRIVED = 1;
private IBookManager mRemoteBookManager;
private Handler mhandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_NEW_BOOK_ARRIVED:
Log.d(TAG, "新书通知:" + msg.obj);
break;
default:
super.handleMessage(msg);
}
}
};
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
IBookManager bookManager = IBookManager.Stub.asInterface(service);
try {
mRemoteBookManager = bookManager;
bookManager.registerListener(mOnNewBookArrivedListener);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
mRemoteBookManager = null;
Log.e(TAG, "binder died.");
}
};
private IOnNewBookArrivedListener mOnNewBookArrivedListener = new IOnNewBookArrivedListener.Stub() {
@Override
public void onNewBookArrived(Book newBook) throws RemoteException {
mhandler.obtainMessage(MESSAGE_NEW_BOOK_ARRIVED, newBook).sendToTarget();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, BookManagerService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//访问服务端耗时操作需开启子线程
new Thread(new Runnable() {
@Override
public void run() {
if(mRemoteBookManager!=null){
List<Book> list = null;
try {
list = mRemoteBookManager.getBookList();
String listStr = "";
for (int i = 0; i < list.size(); i++) {
listStr += list.get(i).toString();
}
Log.d(TAG, "Book list:" + listStr);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
}
@Override
protected void onDestroy() {
if (mRemoteBookManager != null && mRemoteBookManager.asBinder().isBinderAlive()) {
try {
mRemoteBookManager.unregisterListener(mOnNewBookArrivedListener);
Log.d(TAG,"解注册成功"+mOnNewBookArrivedListener);
} catch (RemoteException e) {
e.printStackTrace();
}
}
unbindService(mConnection);
super.onDestroy();
}
}
客户端调用远程服务的方法,被调用的方法运行在服务端的Binder线程池中,同时服务端线程会被挂起,如果服务端方法执行比较耗时,会导致客户端线程长时间阻塞,如果这个客户端线程是UI线程,则会导致ANR。因此明确服务端哪个方法是耗时的,可以开启子线程钱访问。
客户端的onServiceConnected和onServiceDisconnected方法都是运行在UI线程中,所以也不可以直接调用远程服务端的耗时方法。