0

我正在开发适用于 Android 的标签栏应用程序,我需要更新用户的状态,我想将整个应用程序注册到 aBroadcastReceiverToast在所有屏幕上显示有关网络状态的信息。

我想出了下面的代码,但它只适用于一个Activity。我的注册onResume方式与我在所有活动中的注册方式相同,但我currentNetworkInfo在第二个选项卡中获得了一个空指针。任何想法如何解决这个问题?

this.registerReceiver(this.mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
            String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
            boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

            currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

            if (currentNetworkInfo.isConnected()) {
                Toast.makeText(getApplicationContext(), "Network connected", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "No Network connection", Toast.LENGTH_LONG).show();
            }
        }
    };
4

0 回答 0