其他分享
首页 > 其他分享> > android-所有活动中的“通用”对话框

android-所有活动中的“通用”对话框

作者:互联网

我想对所有活动进行网络检查,以便如果没有可用的网络,将出现一个对话框,必须完成当前活动.

为此,我创建了一个ConnectionDetector文件来检查连接.
在这个Java文件中,我创建了一个对话框.
当我单击对话框按钮时,调用活动必须完成.

如何发送当前活动作为参数?

我的活动

if (!ConnectionDetector.isConnectingToInternet()) {
       ConnectionDetector.noConnectionDialog(getApplicationContext(), this);
}

ConnectionDetector.java

public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context) {
        this._context = context;
    }

    public static boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) AppController.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }

        }
        return false;
    }

    public static void noConnectionDialog(final Context context, final Activity activity) {
        final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
        dialog.setTitle("Network error");
        dialog.setMessage("There seems to be a connection problem. Please check your network connection and try again");
        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                activity.finish();
            }
        });
        dialog.show();
    }
}

它正在获取空指针异常,活动尚未完成.

解决方法:

如果您总是要使用显示此对话框表单活动,那么您也可以

public static void noConnectionDialog(final Context context) {
        final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
        dialog.setTitle("Network error");
        dialog.setMessage("There seems to be a connection problem. Please check your network connection and try again");
        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {                
                 dialog.dismiss();
                 ((Activity)context).finish();
            }
        });
        dialog.show();
    }

标签:dialog,android-dialog,android
来源: https://codeday.me/bug/20191027/1945411.html