如果没有连接默认的连接失败对话框,我如何弹出?

时间:2010-05-12 10:15:13

标签: android

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

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

和两个按钮,设置,取消。

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

2 个答案:

答案 0 :(得分:17)

/**
 * 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();
    }

答案 1 :(得分:3)

在这里,您可以找到有关如何构建对话框的参考资料

http://developer.android.com/guide/topics/ui/dialogs.html

以下是一段代码片段,可帮助您检测互联网访问:

http://www.androidsnippets.org/snippets/131/

顺便问一下:你是不是已经在2009年11月15日问了这个问题? http://groups.google.com/group/android-beginners/browse_thread/thread/715cedfc5fd6f020?utoken=QyP-dzQAAACEe9Lph6eUOAakqA3-BnR-KvPfK0ltyCETgVsCM3D7GeEWTAM9S5G8WBs1q2tBppm1FwwMIvCGKnxkm-CrwSdp