checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) returns 即使我的 GPS 关闭也是如此

checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) returns true even though my GPS is off

如果未授予权限,我会尝试提示用户激活 GPS。 我无法到达请求部分,因为即使我的 GPS 关闭,检查也始终 returning 为真。

这是我的代码:

if (ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{ACCESS_FINE_LOCATION}, 1);
}

由于我的 GPS 已关闭,我希望条件 return 为真,但它 return 为假。

你能给我解释一下为什么我会误会吗?

预先感谢您的帮助。

ContextCompat.checkSelfPermission returns true 如果用户已授予您的应用程序 ACCESS_FINE_LOCATION 的权限。它与设备上的 GPS 状态无关。查看此 link 以了解有关其工作原理的更多信息。

但是,如果您想访问或检测 GPS 的当前状态,如果它在应用程序中打开或关闭,您可以使用以下代码实现:

if ( (context.getSystemService(Context.LOCATION_SERVICE) as LocationManager).isProviderEnabled(LocationManager.GPS_PROVIDER) ) 
{
  //gps is on in the device
}

正如 Payam 所说,启用 GPS 和检查位置权限是两个不同的事情。您可以随时从 phone 设置中打开您的 GPS 位置。但是要使用位置 api,您必须在代码中获得权限。

还有一件事,如果您 phone 的 android 版本是 6.0 或更高版本,那么您需要使用 checkSelfPermissions() 方法以及在 Manifest 文件中明确获得权限。 但是如果你的 android 版本低于 6.0 ,那么你只需要在 android Manifest.
中添加权限即可 如果我的回答对您有帮助,请点击我回答左侧的 "Tick mark" 符号接受我的回答。

您要求用户授予您的应用位置权限。要打开 gps,您需要另一个代码,因此在获得 true 值后,请执行以下操作:

Intent gpsOptionsIntent = new Intent(  
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
startActivity(gpsOptionsIntent);