0

I'm trying to use handler in the purpose of waiting for my wifi connection. This the piece of code I'm using :

    final AlertDialog alertDialog2 = new AlertDialog.Builder(new android.view.ContextThemeWrapper(context, R.style.AlertDialogCustom)).create();
    alertDialog2.setTitle("Loading...");
    alertDialog2.setIcon(R.drawable.check);
    alertDialog2.show();
    Handler handler = new Handler();
    int count = 0;
    while (!isConnected() /*Check wifi connection*/) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                alertDialog2.dismiss();
                // do other thing
            }
        }, 200);
        count++;
        /*stop the loop after 20s*/
        if (count > 100) {
            break;
        }
    }

As you can see in the piece of code, I want to show a loading alertDialog during the operation and when it's finished I'd like to stop it to notify the user for his wifi connection.

Kevin Vincent
  • 587
  • 13
  • 28

1 Answers1

0

you will need to use WIFI broad cast receiver.

First you will need to display the dialog and then register the wifi broad cast receiver which tell you when the WIFI status change and when you receive the status you want dismiss the dialog.

refer the the below link to know how to detect WIFI status changes

How to detect when WIFI Connection has been established in Android?

final AlertDialog alertDialog2 = new AlertDialog.Builder(new android.view.ContextThemeWrapper(context, R.style.AlertDialogCustom)).create();
alertDialog2.setTitle("Loading...");
alertDialog2.setIcon(R.drawable.check);
alertDialog2.show();

private final BroadcastReceiver myReceiver = new BroadcastReceiver() {

@Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equalsIgnoreCase("android.net.wifi.STATE_CHANGE")) {
            Log.d(TAG,"WIFI STATE CHANGED");
alertDialog2. dismiss();
        }
    }
};

IntentFilter intent = new IntentFilter("");
registerReceiver(myReceiver, intent);
Community
  • 1
  • 1
  • Thanks for your answer but the issue is that I will be notified only when the Wifi is connected. But How can I know if it failed ? That's why I wanted a timer. – Kevin Vincent Oct 03 '16 at 00:00