gpt4 book ai didi

android - BroadcastReceiver 后的运行时异常

转载 作者:行者123 更新时间:2023-11-30 04:44:48 28 4
gpt4 key购买 nike

我正在尝试使用 BroadcastReceiver 获取互联网连接状态。

接收类是这样的:

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 调用后立即收到运行时异常。谁能告诉我我做错了什么?我什至尝试简单地在 list xml 文件中添加接收者标签,而不是在我的 Activity 中注册,但是我仍然遇到运行时异常。我在 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]

最佳答案

我在连接到服务时遇到了类似的问题,并且抛出了错误,因为我在绑定(bind)完成之前进行了远程调用。

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

关于android - BroadcastReceiver 后的运行时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5248791/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com