我在尝试在后台线程中的*回调方法上运行PhoneStateListener时遇到问题。这是我到目前为止所做的:
首先,我编写了PhoneStateListener实现。有点像:
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);
}
}
然后我创建了一个Handler类:
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;
}
}
}
最后,在Service
内,我开始新HandlerThread
并将PhoneStateHandler
附加到其HandlerThread mThread = new HandlerThread("PhoneStateListenerThread");
mThread.start();
PhoneStateHandler mHandler = new PhoneStateHandler(this, mThread.getLooper());
mHandler.sendMessage(Message.obtain(mHandler, PhoneStateHandler.MESSAGE_START));
。活套:
MyPhoneStateListener.onCallStateChanged()
我期望的是,mThread
等方法可以在PhoneStateHandler.onHandleMessage()
线程而不是UI线程上执行。我正在利用这样一个事实:当首次创建PhoneStateListener时,它被绑定到其当前线程的Looper。这是没有记录的,但那是what actually happens。
然而,我观察到的是,尽管在HandlerThread
的循环中调用了MyPhoneStateListener.onCallStateChanged()
方法(正如我所料),{{1}}仍会被调用UI线程。
有关我的代码有什么问题的任何线索?
由于