我正在尝试在我的应用程序中使用 BroadcastReceiver 获取互联网连接状态。如果没有可用的互联网,我想显示一个警报对话框。
这是我的广播接收器:
public class ConnectivityChangedReceiver extends BroadcastReceiver{
@Override
public void onReceive( Context context, Intent intent )
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
} else {
showInternetAlertDialog(context);
}
}
public void showInternetAlertDialog(Context context){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("You have no internet connection.")
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
}
});
builder.show();
return;
}
}
我也在清单中定义了这个接收器。我已经在清单中定义了访问网络状态的权限。
<receiver android:name="com.lisnx.service.ConnectivityChangedReceiver"
android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
但是当互联网消失并且 AlertDialog 框尝试打开时,我得到以下异常:
10-19 16:25:21.474 E/AndroidRuntime( 6864): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
10-19 16:25:21.474 E/AndroidRuntime( 6864): at android.view.ViewRoot.setView(ViewRoot.java:509)
10-19 16:25:21.474 E/AndroidRuntime( 6864): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
10-19 16:25:21.474 E/AndroidRuntime( 6864): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
10-19 16:25:21.474 E/AndroidRuntime( 6864): at android.app.Dialog.show(Dialog.java:241)
我认为这是一个上下文问题,但我无法找出究竟是什么问题。请帮助我。任何解决方案将不胜感激。提前谢谢。