Android中實現(xiàn)跨進程通信(IPC)的方式(三)之觀察者模式
前言
????在Android中實現(xiàn)跨進程通信(IPC)的幾種方式(一)中介紹了什么是多進程胸嘴,為什么需要多進程,多進程的優(yōu)缺點等击蹲。這篇我們將會使用AIDL來實現(xiàn)跨進程通信
在Android中實現(xiàn)跨進程通信(IPC)的幾種方式(二)中講解了怎么用AIDL實現(xiàn)跨進程通信纽绍。如果還不了解什么AIDL,那么可以看一下這篇文章蕾久。
背景
???? 現(xiàn)在有一個需求是在另外一個進程中進行數(shù)據(jù)處理,我們需要獲取它的處理結果拌夏。所以這個時候我們需要另一個進程在處理完數(shù)據(jù)過后主動告訴我們僧著。說到這里很多開發(fā)者肯定就馬上想到了觀察者模式。想到了接口回調障簿。下面我們就用接口回調來實現(xiàn)當前需求盹愚。
實現(xiàn)接口
回調接口 IBookListener實現(xiàn)
// IBookListener.aidl
package com.example.huangjie.aidl3;
// Declare any non-default types here with import statements
import com.example.huangjie.aidl3.Book;
interface IBookListener {
void onBookChange(in Book book);
}
實現(xiàn)接口的注冊與取消注冊
// IBookManager.aidl
package com.example.huangjie.aidl3;
// Declare any non-default types here with import statements
import com.example.huangjie.aidl3.Book;
import com.example.huangjie.aidl3.IBookListener;
interface IBookManager {
void addBook(in Book book);
List<Book> getBookList();
void registerListener(IBookListener listener);
void unregisterListener(IBookListener listener);
}
服務端實現(xiàn)
package com.example.huangjie.aidl3;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by huangjie on 2018/6/3.
*/
public class BookService extends Service {
private ArrayList<IBookListener> mListenerList;
private static final String TAG = "BookService";
private ArrayList<Book> mBookList;
private boolean destory;
@Override
public void onCreate() {
super.onCreate();
mListenerList = new ArrayList<>();
mBookList = new ArrayList<>();
new Thread() {
@Override
public void run() {
super.run();
while (!destory) {
try {
Thread.sleep(6000);
String bookId = "id:" + mBookList.size() + 1;
String bookName = "書名" + bookId;
Book book = new Book(bookId, bookName);
mBookList.add(book);
onNewBookArrived(book);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
/**
* 當新書到達
* @param book
*/
public void onNewBookArrived(Book book) {
for (IBookListener listener : mListenerList) {
try {
listener.onBookChange(book);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBookBinder;
}
private IBinder mBookBinder = new IBookManager.Stub() {
@Override
public void addBook(Book book) throws RemoteException {
mBookList.add(book);
onNewBookArrived(book);
}
@Override
public List<Book> getBookList() throws RemoteException {
return mBookList;
}
@Override
public void registerListener(IBookListener listener) throws RemoteException {
if (!mListenerList.contains(listener)) {
mListenerList.add(listener);
}
Log.e(TAG, "registerListener success" + mListenerList.size());
}
@Override
public void unregisterListener(IBookListener listener) throws RemoteException {
if (mListenerList.contains(listener)) {
mListenerList.remove(listener);
Log.e(TAG, "unregisterListener success" + mListenerList.size());
}
}
};
@Override
public void onDestroy() {
super.onDestroy();
destory = true;
}
}
客戶端實現(xiàn)
package com.example.huangjie.aidl3;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import java.lang.ref.WeakReference;
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivity";
private ServiceConnection connection;
private IBookManager mBookManager;
private IBookListener.Stub mListener;
private MyHander mHandler = new MyHander(this);
public static class MyHander extends Handler {
private WeakReference<Context> reference;
public MyHander(Context context) {
reference = new WeakReference<>(context);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (reference.get() != null) {
Toast.makeText(reference.get(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
}
}
}
;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
Intent intent = new Intent(this, BookService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
private void init() {
connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBookManager = IBookManager.Stub.asInterface(service);
try {
mBookManager.registerListener(mListener);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
mListener = new IBookListener.Stub() {
@Override
public void onBookChange(Book book) throws RemoteException {
mHandler.obtainMessage(0x12, book).sendToTarget();
}
};
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mBookManager != null && mBookManager.asBinder().isBinderAlive()) {
try {
mBookManager.unregisterListener(mListener);
} catch (RemoteException e) {
e.printStackTrace();
}
}
unbindService(connection);
}
}
????通過以上我們已經(jīng)實現(xiàn)了跨進程通信中的觀察者模式,但是我們是否發(fā)現(xiàn)了一個問題站故,那就是客戶端解綁監(jiān)聽器的時候發(fā)現(xiàn)居然解綁失敗皆怕。也就是說服務端找不到我們注冊的監(jiān)聽器。但是客戶端傳遞的明明是同一個監(jiān)聽器對象啊西篓。其實出現(xiàn)這種情況也是意料之中的愈腾。因為這種回調模式只適用于我們在同一個進程中進行回調,而在跨進程中這種模式是不會奏效的岂津。因為Binder會把客戶端傳遞的對象是從新轉轉換虱黄,并且生成一個新的對象,雖然我們在注冊和接觸注冊的時候傳遞的對象是同一個客戶端對象吮成。但是通過Binder傳遞到服務端后礁鲁,卻會產生兩個全新的對象。因為對象是不能直接進行跨進程中傳輸赁豆。對象的跨進程傳輸本質上都是序列化與反序列化的過程仅醇。這就是為什么AIDL中自定義對象都必須實現(xiàn)Parcelable接口的原因。說了那么多魔种,到底怎么才能實現(xiàn)跨進程通信的觀察者模式呢析二?
什么是RemoteCallbackList
????簡單一句話概括就是RemoteCallbackList是系統(tǒng)提供的用于刪除跨進程listener的接口。RemoteCallbackList是一個范型节预,支持管理任意的AIDL接口叶摄。
具體可以看Android官方文檔
修改過后的服務端代碼
package com.example.huangjie.aidl3;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by huangjie on 2018/6/3.
*/
public class BookService extends Service {
private RemoteCallbackList<IBookListener> mListenerList;
private static final String TAG = "BookService";
private ArrayList<Book> mBookList;
private boolean destory;
@Override
public void onCreate() {
super.onCreate();
mListenerList = new RemoteCallbackList<>();
mBookList = new ArrayList<>();
new Thread() {
@Override
public void run() {
super.run();
while (!destory) {
try {
Thread.sleep(6000);
String bookId = "id:" + mBookList.size() + 1;
String bookName = "書名" + bookId;
Book book = new Book(bookId, bookName);
mBookList.add(book);
onNewBookArrived(book);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
/**
* 當新書到達
*
* @param book
*/
public void onNewBookArrived(Book book) {
final int count = mListenerList.beginBroadcast();
for (int i = 0; i < count; i++) {
IBookListener broadcastItem = mListenerList.getBroadcastItem(i);
if (broadcastItem != null) {
try {
broadcastItem.onBookChange(book);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
mListenerList.finishBroadcast();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBookBinder;
}
private IBinder mBookBinder = new IBookManager.Stub() {
@Override
public void addBook(Book book) throws RemoteException {
mBookList.add(book);
onNewBookArrived(book);
}
@Override
public List<Book> getBookList() throws RemoteException {
return mBookList;
}
@Override
public void registerListener(IBookListener listener) throws RemoteException {
mListenerList.register(listener);
}
@Override
public void unregisterListener(IBookListener listener) throws RemoteException {
mListenerList.unregister(listener);
}
};
@Override
public void onDestroy() {
super.onDestroy();
destory = true;
}
}
注意事項
????客戶端在調用遠程服務的方法,被調用的方法運行在服務端的Binder線程池中安拟,同時客戶端線程會被掛起蛤吓,這個時候如果服務端方法執(zhí)行比較耗時的話,就會導致客戶端線程長時間阻塞在這里糠赦,如果這個時候客戶端調用服務端方法的方法所在線程是UI線程的話会傲,就會導致客戶端ANR,這當然是不行的锅棕,如果我們知道服務端方法是個耗時的方法,這個時候我們要避免在客戶端UI線程中去訪問遠程方法淌山。由于onServiceConnected和onServiceDisconnected方法都是運行在UI線程中裸燎,所以不可以在它們里面直接調用服務端耗時方法。特別需要注意的是:由于服務端的方法本身就運行在服務端的Binder線程池中泼疑,所以服務端方法本身就可以執(zhí)行大量的耗時操作德绿。這個時候不要在服務端中開線程去進行異步任務。