1

我注册了一个广播来获取ConnectivityManager.CONNECTIVITY_ACTION,代码是:

registerReceiver(mNetwrokBroadcastReceiver, new IntentFilter(
            ConnectivityManager.CONNECTIVITY_ACTION));

接收者是:

private BroadcastReceiver mNetwrokBroadcastReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

        boolean isConnected = false;
        NetworkInfo mNetworkInfo = intent
                .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        NetworkInfo.State state = (mNetworkInfo == null ? NetworkInfo.State.UNKNOWN
                : mNetworkInfo.getState());

        switch (state) {
        case CONNECTED:
            isConnected = true;
            break;

        case DISCONNECTING:
            if (intent.getBooleanExtra(
                    ConnectivityManager.EXTRA_NO_CONNECTIVITY, false))
                isConnected = false;
            else {
                isConnected = true;
            }
            break;

        default:
            break;
        }


        if (isConnected) {
            mPopwin.onDismiss();
            init();

        }
    }
};

但是我发现当网络总是连接时,它也发送广播,为什么???有同样的问题,我不明白。

编辑:我的意思是,我在活动的初始化中注册了一个过滤器为“ConnectivityManager.CONNECTIVITY_ACTION”的广播,当网络始终连接时,我启动活动,执行函数“onReceive”;在谷歌文档中说“网络连接发生了变化”,但网络没有变化,为什么要执行 onReceive ?

4

1 回答 1

1

由于 CONNECTIVITY_ACTION 是棒广播,因此它会继续调用 onRecevie 将其删除,您可以使用 removeStickyBroadcast(Intent Intent)DOC

于 2014-08-27T06:06:05.363 回答