krakig
krakig

Reputation: 1555

Best way to handle a network disconnection

I am quite new to android and I created a little app that needs to be connected to the wifi network (streaming purpose).

I created an alert dialog that spawns when the connection is lost.

new AlertDialog.Builder(this)
            .setTitle("Network connection problem ")
            .setMessage("Your network connection is down, please go to settings")
            .setPositiveButton("settings", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent dialogIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(dialogIntent);
                }
            })
            .setNegativeButton("quit", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    System.exit(0);
                }
            })
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();

Let's say that I enable wifi again on my phone, and that I go back to the interface when the wi-fi is not reconnected yet. How can I make my dialog box dissapear when the device is connected again to the wifi? Should I create a sort of timer that checks each x seconds the state of the network?

Upvotes: 0

Views: 211

Answers (1)

sonic
sonic

Reputation: 1904

Read the monitor connectivity chnage of the android documentation.

It suggest you register a receiver for the "android.net.conn.CONNECTIVITY_CHANGE" action. In this receiver you can decide if the user is connected or not to wifi.

So when you launch your app, detect if wifi is connected or not. And register your receiver for this action. Then whenever the connection status change (connection or deconnection) you will be notified.

Upvotes: 1

Related Questions