if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
}
// Request the permission ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, PERMISSION_REQUEST_CODE);
@Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == PERMISSION_REQUEST_CODE) { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission granted, do the task you need to do. // ... } else { // Permission denied, show a message to the user to explain // why you need this permission. } } }
注意:在 Android 11 及其以上版本上,您需要特定的权限(ACCESS_BACKGROUND_LOCATION),以便在应用程序处于后台时获取位置信息。您可以在 AndroidManifest.xml 中添加此权限声明。