【问题标题】:Check if user has enabled GPS after prompted提示后检查用户是否启用了 GPS
【发布时间】:2011-08-27 05:22:08
【问题描述】:

简单明了。我开始一个活动并检查手机是否启用了 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模块的状态。

【问题讨论】:

    标签: android gps location locationmanager


    【解决方案1】:

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

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

    还是我错过了什么?

    【讨论】:

    • 使用我上面写的代码,onActivityResults 在启动设置意图后立即触发......所以它不会等待用户执行他的操作。奇怪的行为,但我用调试器看过它。
    • 奇怪地启动设置意图:startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);使 onActivityResult 正确触发
    • 可能是 FLAG_ACTIVITY_NEW_TASK 阻止了您需要的行为。
    • 是的,你缺少常识。设置活动将提供结果代码是完全合乎逻辑的。
    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 2014-09-10
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多