Android PhoneStateListener在主线程上运行?

时间:2015-02-23 13:34:47

标签: java android multithreading phone-state-listener

我已经尝试构建一段代码来验证"数据连通性; 假设用户已打开数据,我想等待"等待"因为它回来了,时间有限:

final PhoneStateListener phoneStateListener = new PhoneStateListener() {
        // occurs also when network state changes
        @Override
        public void onDataConnectionStateChanged(int state) {
            if (state == TelephonyManager.DATA_CONNECTED) {
                synchronized (lock) {
                    lock.notifyAll();
                }

            }
        }
    };

我注册了听众:

telMgr.listen(phoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);

然后我等待锁定:

synchronized (lock) {
            if (telMgr.getDataState() != TelephonyManager.DATA_CONNECTED)
                lock.wait(timeMS);
        }

似乎总是等待整个timeMS毫秒,即使我很久以前打开数据。在调试时,似乎只有在等待结束后,活动流程才会继续,我才会收到有关" OnDataConnectionState"的通知。只是稍后改变,好几次,好像监听器在同一个主线程上运行,一旦主线程阻塞,没有"事件"收到并且" OnDataStateChange"方法未被调用。 听众的确如何运作,是否有可能以某种方式解决这个问题?

甲基的完整代码

public static boolean verifyDataConnectivity(long timeMS, Context context)
{
    final Object lock= new Object();
    final Context mainContext = context;
    final TelephonyManager telMgr = (TelephonyManager)(mainContext
            .getSystemService(Context.TELEPHONY_SERVICE));
   // Handler handler = new Handler(Looper.getMainLooper());
   // Handler handler = new Handler( mainContext.getMainLooper());
    final PhoneStateListener phoneStateListener = new PhoneStateListener() {
        // occurs also when network state changes
        @Override
        public void onDataConnectionStateChanged(int state) {
            if (state == TelephonyManager.DATA_CONNECTED) {
                synchronized (lock) {
                    lock.notifyAll();
                }

            }
        }
    };

    try {

        telMgr.listen(phoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);

        Runnable rListener = new Runnable() {

            @Override
            public void run() {
                // Register phone state listener:
                telMgr.listen(phoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);

            }
        };

       // handler.post(rListener);

        synchronized (lock) {
            if (telMgr.getDataState() != TelephonyManager.DATA_CONNECTED)
                lock.wait(timeMS);
        }
        if (telMgr.getDataState() != TelephonyManager.DATA_CONNECTED)
            return false;

        return true;

    } catch (Exception e) {
        Log.e(ANDROID_COMMON_TAG, e.getMessage());
        e.printStackTrace();
        return false;
    }
    finally
    {
        if (phoneStateListener != null)
            telMgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
    }
}

0 个答案:

没有答案