Android: 网络断开后立即显示 AlertDialog

Android: Show AlertDialog as soon as internet is disconnected

我有一个必须连接互联网的应用程序。所以,我想要的是,每当用户与互联网(Wifi 或手机)断开连接时,Activity 应该能够检测到网络状态并且应该显示 AlertDialog 提示用户检查其连接。我曾尝试使用广播接收器实现此功能,但我的应用程序崩溃了。以下是相同的代码片段:

以下代码在onCreate()方法

  c = this.getApplicationContext();
  broadcastReceiver = new BroadcastReceiver() {

    AlertDialog.Builder builder;

    @Override
    public void onReceive(Context context, Intent intent) {

        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo activeNetWifi = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        boolean isConnectedMobile = activeNetInfo != null
                && activeNetInfo.isConnectedOrConnecting();
        boolean isConnectedWifi = activeNetWifi != null
                && activeNetWifi.isConnectedOrConnecting();
        AlertDialog alert = alertNoNetwork();
        if (isConnectedMobile || isConnectedWifi) {
            if (alert != null && alert.isShowing()) {
                alert.dismiss();
            }
        } else {
            if (alert != null && !alert.isShowing()) {
                alert.show();
            }
        }

    }

    public AlertDialog alertNoNetwork() {
        builder = new AlertDialog.Builder(c);
        builder.setMessage(R.string.err_network_failure_title)
                .setMessage(R.string.err_network_failure_message)
                .setCancelable(false)
                .setPositiveButton("Quit",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                            }
                        });
        return builder.create();
    }
};

声明 cbroadcastReceiver 为:

private Context c;  
private BroadcastReceiver broadcastReceiver ;

并在onResume()方法中注册broadcastReceiver

registerReceiver(broadcastReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));

我的错误日志是:

02-25 15:53:35.836: E/AndroidRuntime(24768): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4000010 (has extras) } in com.example.ActivityCapturImg@1bca6ea7 02-25 15:53:35.836: E/AndroidRuntime(24768): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:880) 02-25 15:53:35.836: E/AndroidRuntime(24768): at android.os.Handler.handleCallback(Handler.java:739) 02-25 15:53:35.836: E/AndroidRuntime(24768): at android.os.Handler.dispatchMessage(Handler.java:95) 02-25 15:53:35.836: E/AndroidRuntime(24768): at android.os.Looper.loop(Looper.java:135) 02-25 15:53:35.836: E/AndroidRuntime(24768): at android.app.ActivityThread.main(ActivityThread.java:5312) 02-25 15:53:35.836: E/AndroidRuntime(24768): at java.lang.reflect.Method.invoke(Native Method) 02-25 15:53:35.836: E/AndroidRuntime(24768): at java.lang.reflect.Method.invoke(Method.java:372) 02-25 15:53:35.836: E/AndroidRuntime(24768): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901) 02-25 15:53:35.836: E/AndroidRuntime(24768): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) 02-25 15:53:35.836: E/AndroidRuntime(24768): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application 02-25 15:53:35.836: E/AndroidRuntime(24768): at android.view.ViewRootImpl.setView(ViewRootImpl.java:583) 02-25 15:53:35.836: E/AndroidRuntime(24768): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:272) 02-25 15:53:35.836: E/AndroidRuntime(24768): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) 02-25 15:53:35.836: E/AndroidRuntime(24768): at android.app.Dialog.show(Dialog.java:298) 02-25 15:53:35.836: E/AndroidRuntime(24768): at com.swachhmap.ActivityCapturImg.onReceive(ActivityCapturImg.java:235) 02-25 15:53:35.836: E/AndroidRuntime(24768): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:870) 02-25 15:53:35.836: E/AndroidRuntime(24768): ... 8 more

请帮忙。

谢谢, 阿比特

编辑:传入AlertDialog.BuilderContext c应该是

 c = ActivityName.this;

而不是getApplicationContext()

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

因为在 AlertDialog.Builder

中传递 getApplicationContext()

AlertDialog.Builder 需要当前活动组件上下文而不是应用程序上下文。

使用调用Dialog.show()创建AlertDialog.Builder对象的Activity上下文:

builder = new AlertDialog.Builder(CurrentActivityName.this);