在android LocationListener中的onProviderDisabled中显示警告对话框

时间:2011-08-17 09:08:58

标签: android geolocation locationlistener android-alertdialog

我需要在方法onProviderDisabled中使用以下代码。但它不会持续很长时间。 我怎么能等到用户回复?

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();

提前致谢!!

2 个答案:

答案 0 :(得分:6)

试试这样。

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

       }
}; 

答案 1 :(得分:0)

您应该使用AsyncTask进行此类操作..请参阅此处http://developer.android.com/reference/android/os/AsyncTask.html

相关问题