我指的是这个优秀的教程Android Architecture Tutorial: Developing an App with a Background Service (using IPC),它讲述了在单独的过程中运行服务。
在Remote Service中,有一种方法可以删除从Activity传递的侦听器。
@Override
public void removeListener(TweetCollectorListener listener)
throws RemoteException {
synchronized (listeners) {
listeners.remove(listener);
}
}
private TweetCollectorListener.Stub collectorListener = new TweetCollectorListener.Stub() {
@Override
public void handleTweetsUpdated() throws RemoteException {
updateTweetView();
}
};
@Override
protected void onDestroy() {
super.onDestroy();
try {
api.removeListener(collectorListener);
unbindService(serviceConnection);
} catch (Throwable t) {
// catch any issues, typical for destroy routines
// even if we failed to destroy something, we need to continue destroying
Log.w(TAG, "Failed to unbind from the service", t);
}
Log.i(TAG, "Activity destroyed");
}
我怀疑removeListener
是否能正常运作。我通过在远程服务中使用以下代码进行快速测试。
@Override
public void removeListener(TweetCollectorListener listener)
throws RemoteException {
synchronized (listeners) {
Log.i("CHEOK", "before removing listner -> " + listeners.size());
listeners.remove(listener);
Log.i("CHEOK", "after removing listner -> " + listeners.size());
}
}
我得到以下结果。
before removing listner -> 1
after removing listner -> 1
我的猜测是,即使Activity在TweetCollectorListener.Stub
和addListener
期间传递removeListner
的同一个实例,但在服务中构建了TweetCollectorListener
的2个不同实例方addListener
和removeListner
。
我可以通过以下日志进一步确认这一点。
Activity calls service's addListener, by passing in com.mindtherobot.samples.tweetservice.TweetViewActivity$2@427c1190
In service's addListener, TweetCollectorListener is com.mindtherobot.samples.tweetservice.TweetCollectorListener$Stub$Proxy@427d68b0
Activity calls service's removeListener, by passing in com.mindtherobot.samples.tweetservice.TweetViewActivity$2@427c1190
In service's removeListener, TweetCollectorListener is com.mindtherobot.samples.tweetservice.TweetCollectorListener$Stub$Proxy@427d7188
那么,有什么办法可以从远程服务中删除监听器吗?有时,我想删除一个老听众,并附上新的听众。
答案 0 :(得分:1)
在远程服务中,为了比较TweetCollectorListener
个对象,您需要使用基础Binder
对象,如下所示:
@Override
public void removeListener(TweetCollectorListener listener)
throws RemoteException {
synchronized (listeners) {
Log.i("CHEOK", "before removing listner -> " + listeners.size());
for (TweetCollectorListener tcl : listeners) {
if (tcl.asBinder() == listener.asBinder()) {
listeners.remove(tcl);
break;
}
}
Log.i("CHEOK", "after removing listner -> " + listeners.size());
}
}