3

I need to Use folowing code inside the method onProviderDisabled. But it doesn't last long. How can I wait until user respond ?

AlertDialog.Builder builder = new AlertDialog.Builder(Activity.this);
        builder.setMessage("Your GPS is disabled! Would you like to enable it?").setCancelable(false).setPositiveButton("Enable GPS", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                Intent gpsOptionsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(gpsOptionsIntent);
            }
        });
        builder.setNegativeButton("Do nothing", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();

Thanks in advance !!

Chrishan
  • 4,076
  • 7
  • 48
  • 67

2 Answers2

6

Try like this.

public void onProviderDisabled(String provider) {
     Message msg = handler.obtainMessage();
     msg.arg1 = 1;
     handler.sendMessage(msg);
}

private final Handler handler = new Handler() {
     public void handleMessage(Message msg) {
          if(msg.arg1 == 1){
               if (!isFinishing()) { // Without this in certain cases application will show ANR
                    AlertDialog.Builder builder = new AlertDialog.Builder(Activity.this);
                    builder.setMessage("Your GPS is disabled! Would you like to enable it?").setCancelable(false).setPositiveButton("Enable GPS", new DialogInterface.OnClickListener() {
                         public void onClick(DialogInterface dialog, int id) {
                              Intent gpsOptionsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                              startActivity(gpsOptionsIntent);
                          }
                     });
                     builder.setNegativeButton("Do nothing", new DialogInterface.OnClickListener() {
                          public void onClick(DialogInterface dialog, int id) {
                               dialog.cancel();
                          }
                     });
                     AlertDialog alert = builder.create();
                     alert.show();
               }
           }

       }
}; 
pkk
  • 3,691
  • 2
  • 21
  • 29
jainal
  • 2,973
  • 2
  • 20
  • 18
0

You should be Using AsyncTask for such operations.. see here http://developer.android.com/reference/android/os/AsyncTask.html

ngesh
  • 13,398
  • 4
  • 44
  • 60