使用 Android Marshmallow,即使您已在 Manifest 文件中指定了权限,您也必须明确向用户请求权限。
因此,您必须以这种方式请求位置权限:
首先,您为位置创建一个请求代码
public static final int LOCATION_REQUEST_CODE = 1001; //Any number
然后检查是否已经授予权限,如果没有,则代码将请求权限,这将显示一个本机弹出窗口,要求拒绝/允许位置权限
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_REQUEST_CODE);
} else {
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER
,1000*60,2,this);
Location location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
}
上述代码应在请求任何位置之前编写,最好在活动的onCreate() 中。然后根据用户在弹窗上的操作,你会得到一个回调,你可以根据你的要求执行。
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case LOCATION_REQUEST_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER
,1000*60,2,this);
Location location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
}
}
}
}
此外,无论您在何处尝试获取位置,都应检查是否已将位置权限授予您的应用程序,然后再获取位置。
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER
,1000*60,2,this);
Location location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
}
您可以请求Manifest.permission.ACCESS_FINE_LOCATION 或Manifest.permission.ACCESS_COARSE_LOCATION 或两者。这取决于您的要求。