android - 没有连接时如何弹出默认连接失败对话框?

标签 android

每当应用程序需要互联网但连接失败时,我会收到一个消息对话框

Connection failed<br/> This application requires network access. Enable mobile network or Wi-Fi to download data.

还有两个按钮,设置,取消。

如何检测没有互联网连接?
如何在我的应用程序中弹出相同的对话框?

最佳答案

/**
 * Checks if we have a valid Internet Connection on the device.
 * @param ctx
 * @return True if device has internet
 *
 * Code from: http://www.androidsnippets.org/snippets/131/
 */
public static boolean haveInternet(Context ctx) {

    NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

    if (info == null || !info.isConnected()) {
        return false;
    }
    if (info.isRoaming()) {
        // here is the roaming option you can change it if you want to
        // disable internet while roaming, just return false
        return true;
    }
    return true;
}
/**
     * Display a dialog that user has no internet connection
     * @param ctx1
     *
     * Code from: http://osdir.com/ml/Android-Developers/2009-11/msg05044.html
     */
    public static void showNoConnectionDialog(Context ctx1) {
        final Context ctx = ctx1;
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        builder.setCancelable(true);
        builder.setMessage(R.string.no_connection);
        builder.setTitle(R.string.no_connection_title);
        builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                return;
            }
        });

        builder.show();
    }

关于android - 没有连接时如何弹出默认连接失败对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2817798/

相关文章:

android - 此类文件的 Jar 属于容器 'Android Dependencies',该容器不允许修改其条目上的源附件

android - onFinishInflate() 永远不会被调用

android - native 应用程序登录

android - 以编程方式在谷歌地图 flutter 上选择标记

android - 以编程方式更改后如何设置布局常量的背景颜色?

Android Intent 对象在目标 Activity 中额外丢失原始值

java - 如何从 ActivityScenarioRule 访问 Activity

android opengl 2.0 模板缓冲区不工作

java - 在 Android SQLite 中处理 "complex"数据库

android - 进入电话 session 时如何识别?