导航远离应用程序时的BroadcastReceiver空指针

时间:2014-01-13 14:47:21

标签: android broadcastreceiver

我正在通过BroadcastReceiver(下面)检测互联网连接。我有一个TextView切换可见/不可见,以显示是否有互联网连接。因为BroadcastReceiver是静态的,所以TextView必须是静态的。但是,如果我离开应用程序(最小化它)并打开/关闭互联网连接,我偶尔会在internetConnect.setVisibility上收到空指针。有什么方法解决这个问题?

static TextView internetConnect;

in onCreate ---> internetConnect = (TextView) findViewById(R.id.internet);

public static class NetworkStateReceiver extends BroadcastReceiver {
    private static final String TAG = "MainActivity.NetworkStateReceiver";
    @Override
    public void onReceive(final Context context, final Intent intent) {
        Log.d(TAG, "Network connectivity change");
        if (intent.getExtras() != null) {
            final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            final NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
            if (ni != null && ni.isConnectedOrConnecting()) {
                internetConnect.setVisibility(View.INVISIBLE);
            } else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
                internetConnect.setVisibility(View.VISIBLE);
            }
            internetConnect.bringToFront();
        }
    }
}

编辑:

private final BroadcastReceiver receiver = new NetworkStateReceiver();

public void onResume() {
    super.onResume();
    if(receiver != null) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, filter);
    }
}

public void onPause() {
    super.onPause();
     if (receiver != null) {
         this.unregisterReceiver(receiver);
     }
}

1 个答案:

答案 0 :(得分:1)

当您的应用在后台时,您需要为广播接收器调用unregisterReceiver。您可以在onPause或onStop中执行此操作。