我正在尝试使用BroadcastReceiver来获取Internet连接状态。

接收器类是这样的:

public class ConnectivityReceiver extends BroadcastReceiver {

    WebView mWebView;



    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.d(MSResearch.LOG_TAG, "Connectivity action: " + intent.getAction());
        if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
            WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            Log.e(MSResearch.LOG_TAG, "Setting wifistate: " + wm.getWifiState());
        } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            NetworkInfo ni = intent.getParcelableExtra  (ConnectivityManager.EXTRA_NETWORK_INFO);
            Log.e(MSResearch.LOG_TAG, "Setting isConnected: " + ni.isConnected());
        }
    }
}


我在onCreate()函数中实例化了Receive,并尝试在Activity类的onResume()中注册接收者,并在onPause()中取消注册。

public onCreate(){
...
conReceiver = new ConnectivityReceiver();
itFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
itFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
...
}

@Override
public void onResume(){
    registerReceiver(conReceiver,itFilter);
}

@Override
public void onPause(){
   unregisterReceiver(conReceiver);
}


我在onResume调用后就收到运行时异常。谁能告诉我我做错了什么?我什至尝试只在清单xml文件中添加接收者标签,而不是在活动中注册,但是我仍然遇到运行时异常。我已经在2.2和2.3模拟器上进行了尝试,但遇到了同样的问题。

Thread [<1> main] (Suspended (exception RuntimeException))
    ActivityThread.performResumeActivity(IBinder, boolean) line: 3128
    ActivityThread.handleResumeActivity(IBinder, boolean, boolean) line: 3143
    ActivityThread.handleLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2684
    ActivityThread.access$2300(ActivityThread, ActivityThread$ActivityRecord, Intent) line: 125
    ActivityThread$H.handleMessage(Message) line: 2033
    ActivityThread$H(Handler).dispatchMessage(Message) line: 99
    Looper.loop() line: 123
    ActivityThread.main(String[]) line: 4627
    Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
    Method.invoke(Object, Object...) line: 521
    ZygoteInit$MethodAndArgsCaller.run() line: 868
    ZygoteInit.main(String[]) line: 626
    NativeStart.main(String[]) line: not available [native method]

最佳答案

我在连接到服务时遇到了类似的问题,并且由于在绑定完成之前进行了远程调用而引发了错误。

我建议您在调用registerReceiver之前检查所有对象是否已初始化。

10-05 23:41