检查与广播接收器的网络连接,并在丢失时启动警报对话框

时间:2019-06-13 10:12:32

标签: android broadcastreceiver alertdialog android-alertdialog

关于如何检查网络连接的大量StackOverflow问题,可以通过阅读Android文档https://developer.android.com/training/basics/network-ops/managing#check-connection

轻松回答。

但这不是此问题的目的。我在这里需要知道的是如何监听应用程序所有活动中的连接变化,以便每当网络完全丢失时(让我们通过“完全丢失”了解Wifi或移动数据),应用程序必须向用户发出警告AlertDialog,需要网络才能继续使用该应用程序。

我试图通过在扩展android.app.Application的类中动态注册的BroadcastReceiver来实现此目的,但是当应用失去网络时,它将关闭,并且在Logcat中出现以下错误提示:

E/Auth: [GoogleAccountDataServiceImpl] getToken() -> BAD_AUTHENTICATION. Account: <ELLIDED:267257377>, App: com.google.android.gms, Service: oauth2:https://www.googleapis.com/auth/contextcontroller

这是我的BroadcastReceiver类:

public class NetworkBroadcastReceiver extends BroadcastReceiver {

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


        if(!isConnected(context)) {

            buildDialog(context).show();
        }

    }


    public boolean isConnected(Context context) {

        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    public AlertDialog.Builder buildDialog(Context c) {

        AlertDialog.Builder builder = new AlertDialog.Builder(c);
        builder.setTitle("No Internet Connection");
        builder.setMessage("You need to have Mobile Data or wifi to access this. Press ok to Exit");

        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
            }
        });

        return builder;
    }
}

这是扩展android.app.Application的类:

public class MyApp extends Application {

    private NetworkBroadcastReceiver mNetworkBroadcastReceiver = new NetworkBroadcastReceiver();

    @Override
    public void onCreate() {
        super.onCreate();

        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetworkBroadcastReceiver, filter);

    }

}

是的,我确实在应用程序的清单文件中声明了ACCESS_NETWORK_STATE权限。

您认为错误是由于在MyApp中声明BroadcastReceiver引起的,还是您认为它源自我的BroadcastReceiver类内部的AlertDialog?

警告:我不想在我的所有活动中注册和注销BroadcastReceiver,这个问题的全部目的是找到一种快捷解决方案,以便可以从一个地方为所有活动一劳永逸地注册BroadcastReceiver。

0 个答案:

没有答案