Search code examples
androidtelephonymanager

Listener invoked despite unregistering from TelephonyManager from non-UI thread


I registered a PhoneStateListener using the code:

mTm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
mTm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE
                | PhoneStateListener.LISTEN_CELL_LOCATION
                | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);

and unregistered it using the code:

mTm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);

But in rare occasions, the listener is invoked even after it is unregistered.

Important Note:
Both the registration & unregistration are done from the same thread that is not the UI thread.

Questions:

  1. If a telephony state has changed and the change is "posted" to the listener and the listener is unregistered before it could be called, will the listener be invoked anyway? Or will the "posted message" be removed from the "queue"?

  2. Does the fact that the registration & unregistration are done from a non-UI thread matter?


Solution

  • As per the API documentation, the listener is invoked at registration with the current value. I found that when the listener is unregistered before this initial invocation, it is still invoked.

    I solved the problem by using a boolean. It's an ugly workaround. Hope Google would fix this.