Android 11中ActivityCompat.requestPermissions自动拒权无弹窗问题
问题解决:Android 11中权限请求不弹框且自动拒绝
问题根源
在Android 11(API 30)中,系统对位置权限的请求有严格的顺序规则:不能同时请求前台位置权限(如ACCESS_FINE_LOCATION)和后台位置权限(ACCESS_BACKGROUND_LOCATION)。你的代码一次性将两个权限加入请求列表,违反了该规则,导致系统直接拒绝请求,不会弹出授权对话框。
解决方案
需要分两步请求权限:先获取前台位置权限,用户同意后再请求后台位置权限。
修改后的MainActivity.java代码如下:
package com.example.robotito_calibration; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; public class MainActivity extends AppCompatActivity { private static final int REQUEST_FINE_LOCATION = 100; private static final int REQUEST_BACKGROUND_LOCATION = 101; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkForegroundLocationPermission(); } // 第一步:请求前台位置权限 private void checkForegroundLocationPermission() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION); } else { // 前台权限已授予,请求后台权限 checkBackgroundLocationPermission(); } } // 第二步:请求后台位置权限 private void checkBackgroundLocationPermission() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, REQUEST_BACKGROUND_LOCATION); } else { Toast.makeText(this, "所有位置权限已授予", Toast.LENGTH_LONG).show(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_FINE_LOCATION: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "前台位置权限已授予", Toast.LENGTH_LONG).show(); checkBackgroundLocationPermission(); } else { Toast.makeText(this, "前台位置权限被拒绝", Toast.LENGTH_LONG).show(); } break; case REQUEST_BACKGROUND_LOCATION: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "后台位置权限已授予", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "后台位置权限被拒绝", Toast.LENGTH_LONG).show(); } break; } } }
补充说明
- 你的
AndroidManifest.xml和build.gradle配置无需修改,已经符合Android 11的权限声明要求。 - 请求后台位置权限时,系统会弹出单独的授权对话框,建议在请求前通过Toast或弹窗向用户说明权限用途,提升授权通过率。
内容的提问来源于stack exchange,提问作者Santiago Hitta
相关产品推荐
相关产品推荐

