title: PhoneStateListener in background thread
body: <p>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:</p>
  
  <p>First, I wrote my PhoneStateListener implementation. Something on the lines of:</p>
  
  <pre><code>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);
      }
  }
  </code></pre>
  
  <p>Then I created a Handler class:</p>
  
  <pre><code>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;
          }
      }
  }
  </code></pre>
  
  <p>Finally, from within a <code>Service</code> I start a new <code>HandlerThread</code> and attach my <code>PhoneStateHandler</code> to its' looper:</p>
  
  <pre><code>HandlerThread mThread = new HandlerThread("PhoneStateListenerThread");
  mThread.start();
  PhoneStateHandler mHandler = new PhoneStateHandler(this, mThread.getLooper());
  mHandler.sendMessage(Message.obtain(mHandler, PhoneStateHandler.MESSAGE_START));
  </code></pre>
  
  <p>What I expect, is that methods such as <code>MyPhoneStateListener.onCallStateChanged()</code> to be executed on the <code>mThread</code> 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 <a href="http://androidxref.com/4.4.4_r1/xref/frameworks/base/telephony/java/android/telephony/PhoneStateListener.java#349" rel="noreferrer">what actually happens</a>. </p>
  
  <p>What I observed, however, is that despite the <code>PhoneStateHandler.onHandleMessage()</code> method gets called in the <code>HandlerThread</code>'s looper (as I expect), the <code>MyPhoneStateListener.onCallStateChanged()</code> still gets called in the UI thread.</p>
  
  <p>Any clue about what's wrong with my code?</p>
  
  <p>Thanks</p>