Android如何查看用户是否真的启用了GPS定位?
How to check if the user really enables the GPS location in Android?
我的应用程序需要 GPS,因此当执行特定操作时,我检查 GPS 是否已启用,如下所示(以及 Marcus 在 this 其他问题中的建议):
if (!locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER )) {
buildAlertMessageNoGps();
}
rootView = inflater.inflate(R.layout.fragment_alert, container, false);
[...]
问题是用户无法从位置设置启用 GPS(例如,通过单击 "back" 按钮并返回到应用程序)。在这种特殊情况下,片段会为相应的进程注入布局,但 GPS 仍处于禁用状态。如何解决?
我想这就是您正在寻找的方法。
您必须检查 KitKat 以上的 android 版本。
@SuppressLint("InlinedApi") @SuppressWarnings("deprecation")
public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}else{
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
我通过在 buildAlertMessageNoGps()
方法中将 startActivity(...)
替换为 startActivityForResult(...)
来解决。这样做,我可以再次检查是否已在回调函数中启用 GPS onActivityResult(...)
。
我的应用程序需要 GPS,因此当执行特定操作时,我检查 GPS 是否已启用,如下所示(以及 Marcus 在 this 其他问题中的建议):
if (!locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER )) {
buildAlertMessageNoGps();
}
rootView = inflater.inflate(R.layout.fragment_alert, container, false);
[...]
问题是用户无法从位置设置启用 GPS(例如,通过单击 "back" 按钮并返回到应用程序)。在这种特殊情况下,片段会为相应的进程注入布局,但 GPS 仍处于禁用状态。如何解决?
我想这就是您正在寻找的方法。 您必须检查 KitKat 以上的 android 版本。
@SuppressLint("InlinedApi") @SuppressWarnings("deprecation")
public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}else{
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
我通过在 buildAlertMessageNoGps()
方法中将 startActivity(...)
替换为 startActivityForResult(...)
来解决。这样做,我可以再次检查是否已在回调函数中启用 GPS onActivityResult(...)
。