12

干净利落。我开始一个活动并检查手机是否启用了 GPS 模块。如果未启用,我会通过对话框提示用户并询问他是否要手动启用它。在是我激活位置设置。现在用户可以根据需要启用它,但我需要检查他做了什么。

try {
    isGPSEnabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {}
if (isGPSEnabled) {
    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
} else {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(
            "Your GPS module is disabled. Would you like to enable it ?")
            .setCancelable(false)
            .setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int id) {
                            // Sent user to GPS settings screen
                            final ComponentName toLaunch = new ComponentName(
                                    "com.android.settings",
                                    "com.android.settings.SecuritySettings");
                            final Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            intent.addCategory(Intent.CATEGORY_LAUNCHER);
                            intent.setComponent(toLaunch);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivityForResult(intent, 1);
                            dialog.dismiss();
                        }
                    })
            .setNegativeButton("No",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int id) {
                            dialog.cancel();
                        }
                    });
    AlertDialog alert = builder.create();
    alert.show();
}

当他回来时,我需要知道用户在位置设置中选择了什么,以便继续我的代码逻辑。基本上我需要等待用户做出选择并返回我的活动,并再次重新检查gps模块的状态。

4

1 回答 1

22

为什么不检查LocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)您的onActivityResult()方法?当用户返回时,应该调用此方法,因为您调用了startActivityForResult(). 如果用户启用了 GPS,那么isProviderEnabled()现在应该返回不同的结果。

或者,始终在您的 onResume 方法中进行 GPS 检查。如果用户从位置设置返回并且没有启用 GPS,那么他们只会收到相同的提示,直到启用GPS 。

还是我错过了什么?

于 2011-05-17T14:34:44.020 回答