I'm having an issue in trying to run a PhoneStateListener on* callback methods in a backround thread. Here's what I did so far:
First, I wrote my PhoneStateListener implementation. Something on the lines of:
public MyPhoneStateListener extends PhoneStateListener {
private TelephonyManager mTelephonyManager;
public MyPhoneStateListener(Context context) {
mTelephonyManager = (TelephonyManager) context.getSystemServices(Context.TELEPHONY_SERVICE);
}
@Override
public void onCallStateChanged(int state, String incomingNumber) { ... }
public void startListening() {
mTelephonyManager.listen(this, PhoneStateListener.LISTEN_CALL_STATE);
}
}
Then I created a Handler class:
public PhoneStateHandler extends Handler {
private Context mContext;
private MyPhoneStateListener mListener;
public static final int MESSAGE_START = 0;
public PhoneStateHandler(Context context, Looper looper) {
super(looper);
mContext = context;
}
@Override
public void onHandleMessage(Message message) {
if (mListener == null) {
mListener = new MyPhoneStateListener(mContext);
}
switch (message.what) {
case MESSAGE_START:
mListener.startListening();
break;
}
}
}
Finally, from within a Service
I start a new HandlerThread
and attach my PhoneStateHandler
to its' looper:
HandlerThread mThread = new HandlerThread("PhoneStateListenerThread");
mThread.start();
PhoneStateHandler mHandler = new PhoneStateHandler(this, mThread.getLooper());
mHandler.sendMessage(Message.obtain(mHandler, PhoneStateHandler.MESSAGE_START));
What I expect, is that methods such as MyPhoneStateListener.onCallStateChanged()
to be executed on the mThread
thread instead of the UI thread. I'm exploiting the fact that when a PhoneStateListener is first created, it is bound to the Looper of its current thread. This is undocumented, but that's what actually happens.
What I observed, however, is that despite the PhoneStateHandler.onHandleMessage()
method gets called in the HandlerThread
's looper (as I expect), the MyPhoneStateListener.onCallStateChanged()
still gets called in the UI thread.
Any clue about what's wrong with my code?
Thanks