1

我指的是这个优秀的教程Android Architecture Tutorial: Developing an App with a Background Service (using IPC),它讨论了在单独的进程中运行服务。

在远程服务中,有一种方法可以删除从 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.StubduringaddListener和的同一个实例,但是在服务端和构造了removeListner2 个不同的实例。TweetCollectorListeneraddListenerremoveListner

我可以通过以下日志进一步确认这一点。

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

那么,有什么办法可以从远程服务中删除监听器?有时,我想删除一个旧的监听器,并附加新的监听器。

4

1 回答 1

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());
    }
}
于 2013-02-20T17:06:29.290 回答