安卓通过AlertDialog激活gps:如何等待用户采取行动



我读过不同的帖子,说当显示AlertDialog时,没有办法等待用户采取行动,因为它会阻塞UI。

然而,像Facebook这样的应用程序显示Gps当前已禁用。你想启用gps吗 alert对话框,等待用户按yes/no。我认为可以使用两种不同的活动,第一种只包含gps警报对话框,但这似乎不对,而且显然不是facebook的做法。

有人能告诉我怎样才能做到这一点吗?

这是我的代码:

       @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    InitializeComponents();
    EnableGPSIfPossible();

        ListAsync lAsync = new ListAsync(this);
        lAsync .execute();
    }

    private void EnableGPSIfPossible()
{   
    final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
     if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
            buildAlertMessageNoGps();
        }
}
 private  void buildAlertMessageNoGps() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Yout GPS seems to be disabled, do you want to enable it?")
               .setCancelable(false)
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                     startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                   }
               })
               .setNegativeButton("No", new DialogInterface.OnClickListener() {
                   public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        dialog.cancel();
                   }
               });
        final AlertDialog alert = builder.create();
        alert.show();
    }

因此,在我的代码中,AsynTask立即启动,而无需等待用户激活gps。(这是正常行为)

谢谢!

您实际可以做的是:

GPSManager.java:

public class GPSManager {
    private Activity activity;
    private LocationManager mlocManager;
    private LocationListener gpsListener;
    public GPSManager(Activity activity) {
        this.activity = activity;
    }
    public void start() {
        mlocManager = (LocationManager) activity
                .getSystemService(Context.LOCATION_SERVICE);
        if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            setUp();
            findLoc();
        } else {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    activity);
            alertDialogBuilder
                    .setMessage("GPS is disabled in your device. Enable it?")
                    .setCancelable(false)
                    .setPositiveButton("Enable GPS",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    Intent callGPSSettingIntent = new Intent(
                                            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                    activity.startActivity(callGPSSettingIntent);
                                }
                            });
            alertDialogBuilder.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alert = alertDialogBuilder.create();
            alert.show();
        }
    }
    public void setUp() {
        gpsListener = new GPSListener(activity, mlocManager);
    }
    public void findLoc() {
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1,
                gpsListener);
        if (mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) == null)
            Toast.makeText(activity, "LAST Location null", Toast.LENGTH_SHORT)
                    .show();
        else {
            gpsListener.onLocationChanged(mlocManager
                    .getLastKnownLocation(LocationManager.GPS_PROVIDER));
        }
    }
}

GPSListener.java:

public class GPSListener implements LocationListener {
    private Activity activity;
    private LocationManager lm;
    private int numberOfUpdates;
    public static final int MAX_NUMBER_OF_UPDATES = 10;
    public GPSListener(Activity activity, LocationManager lm) {
        this.activity = activity;
        this.lm = lm;
    }
    @Override
    public void onLocationChanged(Location loc) {
        if (numberOfUpdates < MAX_NUMBER_OF_UPDATES) {
            numberOfUpdates++;
            Log.w("LAT", String.valueOf(loc.getLatitude()));
            Log.w("LONG", String.valueOf(loc.getLongitude()));
            Log.w("ACCURACY", String.valueOf(loc.getAccuracy() + " m"));
            Log.w("PROVIDER", String.valueOf(loc.getProvider()));
            Log.w("SPEED", String.valueOf(loc.getSpeed() + " m/s"));
            Log.w("ALTITUDE", String.valueOf(loc.getAltitude()));
            Log.w("BEARING", String.valueOf(loc.getBearing() + " degrees east of true north"));
            String message;
            if (loc != null) {
                message = "Current location is:  Latitude = "
                        + loc.getLatitude() + ", Longitude = "
                        + loc.getLongitude();
                // lm.removeUpdates(this);
            } else
                message = "Location null";
            Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
        } else {
            lm.removeUpdates(this);
        }
    }
    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(activity, "Gps Disabled", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(activity, "Gps Enabled", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
}

然后从你的活动:

GPSManager gps = new GPSManager(
                                    yourActivity.this);
                            gps.start();

我通过使用简单的功能做到了这一点,但没有显示警报框,我将用户控制重定向到设置页面

这是我使用的函数

public void isGPSEnable(){
        LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean enabled = service
          .isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!enabled) {
          Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
          startActivity(intent);
        } 
}

我设法让它工作起来。我在stackoverlfow上发现的这篇文章给了我灵感。http://developmentality.wordpress.com/2009/10/31/android-dialog-box-tutorial/

我基本上移动了警报对话框的"是"one_answers"取消"按钮上需要执行的逻辑。在执行了Yes和Cancel按钮所需的逻辑之后,我开始异步逻辑执行。

这是我的代码:

public interface ICommand
{
    void execute();
}

用于警报对话框的启用Gps和取消按钮的两个具体命令:

public class CancelCommand implements ICommand
{
    protected Activity m_activity;
    public CancelCommand(Activity activity)
    {
        m_activity = activity;
    }
    public void execute()
    {
        dialog.dismiss();
        //start asyncronous operation here
    }
}

public class EnableGpsCommand extends CancelCommand
{
    public EnableGpsCommand( Activity activity) {
        super(activity);
    }
    public void execute()
    {
        // take the user to the phone gps settings and then start the asyncronous logic.
        m_activity.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        super.execute();
    }
}

现在,从活动:

//returns true if the GpsProviderIsDisabled
//false otherwise
private boolean EnableGPSIfPossible()
{   
    final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
    if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
        buildAlertMessageNoGps();
        return true;
    }
    return false;
}

private  void buildAlertMessageNoGps()
{
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Yout GPS seems to be disabled, do you want to enable it?")
        .setCancelable(false)
        .setPositiveButton("Yes", new CommandWrapper(new EnableGpsCommand(this)))
        .setNegativeButton("No", new CommandWrapper(new CancelCommand(this))); 
    final AlertDialog alert = builder.create();
    alert.show();
}

现在,从"创建活动"方法中,我只需调用:

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.newfriendlist);
    InitializeComponents();
    if (!EnableGPSIfPossible())
    {
        //then gps is already enabled and we need to do StartFriendRetrievalAsync from here.
        //otherwise this code is being executed from the EnableGpsIfPossible() logic.

        //Asyncronous logic here.
    }
}

我真的希望这能在你陷入困境时对你有所帮助:)。

干杯

   final AlertDialog.Builder builder = new AlertDialog.Builder(this);
         final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
         final String message = "your message";
         builder.setMessage(message)
             .setPositiveButton("OK",
                 new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface d, int id) {
                         getActivity().startActivity(new Intent(action));
                         d.dismiss();
                     }
             })
             .setNegativeButton("Cancel",
                 new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface d, int id) {
                         d.cancel();
                     }
             });
         builder.create().show();

(对不起我的英语)当我看到你的问题和你的问题给出答案时,我正在寻找解决方案。

问题是,该活动在对话框警报打开时继续启动,当用户按下"是"时,一个新的活动将启动"gps设置……"。当用户在打开gps后返回到第一个活动或忽略您时,该活动不会进行任何更新,也不会认为发生了什么事情(如打开gps),因为它已经加载,所以你必须听取更新并应用更改,或者在用户"回来"时重新启动活动,对我来说,我刚刚添加了:

<activity
    ...
    android:noHistory="true"
    ... /> </activity>

现在,每次用户按下"后退"按钮时,您的活动都会重新开始,并考虑到新的更新它对我很有效,希望这能帮助你或帮助其他人

最新更新