Pentium10
Pentium10

Reputation: 207893

How can I popup when no connection the default Connection Failed dialog?

Whenever a application needs internet and connection fails, I get a message dialog

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

and two buttons, Settings, Cancel.

How do I detect there is no internet connection?
How do I popup a same dialog in my application?

Upvotes: 2

Views: 6083

Answers (2)

Pentium10
Pentium10

Reputation: 207893

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

Upvotes: 17

RoflcoptrException
RoflcoptrException

Reputation: 52229

Here you can find a reference on how to build dialogs

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

Here is a code snippet that should help you detecting internet access:

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

btw: wasn't it you that asked this question already on 15. Nov. 2009? http://groups.google.com/group/android-beginners/browse_thread/thread/715cedfc5fd6f020?utoken=QyP-dzQAAACEe9Lph6eUOAakqA3-BnR-KvPfK0ltyCETgVsCM3D7GeEWTAM9S5G8WBs1q2tBppm1FwwMIvCGKnxkm-CrwSdp

Upvotes: 3

Related Questions