PhoneStateListener in the background thread

I had a problem trying to run PhoneStateListener in * callback methods in the background thread. Here is what I have done so far:

First, I wrote my implementation of PhoneStateListener. Something in the lines:

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 the 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 the inside, ServiceI launched a new one HandlerThreadand attached mine PhoneStateHandlerto his "looper":

HandlerThread mThread = new HandlerThread("PhoneStateListenerThread");
mThread.start();
PhoneStateHandler mHandler = new PhoneStateHandler(this, mThread.getLooper());
mHandler.sendMessage(Message.obtain(mHandler, PhoneStateHandler.MESSAGE_START));

I expect such methods as MyPhoneStateListener.onCallStateChanged()to be executed in a thread mThreadinstead of a user interface thread. I use the fact that when PhoneStateListener is first created, it is bound to the Looper of the current thread. This is undocumented, but what really happens .

, , , PhoneStateHandler.onHandleMessage() HandlerThread ( ), MyPhoneStateListener.onCallStateChanged() .

- , ?

+4

All Articles