Android 6.0(Marshmallow)申请运行时权限时Package Installer崩溃求助
解决Android权限申请时“Package Installer已停止”的问题
首先,咱们先排查代码里的关键问题,你遇到的这个崩溃大概率是权限请求数组的初始化错误导致的,我帮你一步步分析和解决:
1. 先看你现有代码的核心问题
你在循环里用perms[k++] = p来收集未授权的权限,但没展示perms数组的初始化逻辑!如果perms是null、长度不够,或者初始化方式错误,就会触发数组越界异常,进而导致系统的Package Installer进程崩溃(因为权限请求是交给系统组件处理的,传递非法参数会直接导致它崩溃)。
2. 正确的权限收集方式(解决核心问题)
建议用动态集合来收集未授权的权限,彻底避免数组长度不匹配的问题,比如用ArrayList:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { List<String> unGrantedPerms = new ArrayList<>(); for(String p : arr){ if(ActivityCompat.checkSelfPermission(IntroductionSlider.this, p) != PackageManager.PERMISSION_GRANTED){ unGrantedPerms.add(p); } } if(unGrantedPerms.isEmpty()) { startActivity(new Intent(IntroductionSlider.this, oneTimeValidation.class)); finish(); }else { // 把List转成数组再发起请求 requestPerm(unGrantedPerms.toArray(new String[0])); } }
3. 其他优化与排查点
- 移除不必要的权限请求:
ACCESS_NETWORK_STATE属于Android的「正常权限」,只需要在Manifest里声明即可,不需要加入动态请求数组,你可以把它从arr里删掉,减少不必要的系统交互。 - 确认请求码合法性:
ALL_REQUEST_CODE建议用自定义正整数(比如100、200),不要用0或者系统预留的请求码。 - 重置Package Installer状态:如果调整代码后还是崩溃,可以尝试清理设备的Package Installer缓存:设置→应用→找到Package Installer→存储→清理缓存/数据(不会影响你的应用)。
- 适配低版本系统:别忘了给Android 6.0以下的设备加直接跳转的逻辑,因为低版本不需要动态权限。
4. 完整修正后的代码示例
调整后的权限数组
// 移除不需要动态申请的ACCESS_NETWORK_STATE String[] arr = new String[] { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE };
权限检查与请求逻辑
private static final int ALL_REQUEST_CODE = 100; // 自定义请求码 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { List<String> unGrantedPerms = new ArrayList<>(); for(String perm : arr) { if(ActivityCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) { unGrantedPerms.add(perm); } } if(unGrantedPerms.isEmpty()) { startActivity(new Intent(IntroductionSlider.this, oneTimeValidation.class)); finish(); } else { ActivityCompat.requestPermissions(this, unGrantedPerms.toArray(new String[0]), ALL_REQUEST_CODE); } } else { // Android 6.0以下直接跳转 startActivity(new Intent(IntroductionSlider.this, oneTimeValidation.class)); finish(); }
权限请求结果处理(别忘了加这个)
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if(requestCode == ALL_REQUEST_CODE) { boolean allGranted = true; for(int result : grantResults) { if(result != PackageManager.PERMISSION_GRANTED) { allGranted = false; break; } } if(allGranted) { startActivity(new Intent(IntroductionSlider.this, oneTimeValidation.class)); finish(); } else { // 提示用户必须授权才能使用,或者引导去设置页开启权限 Toast.makeText(this, "需要授权才能继续使用应用", Toast.LENGTH_SHORT).show(); } } }
按照上面的步骤调整后,应该就能解决Package Installer崩溃的问题了,你可以先试试用ArrayList收集权限的方式,这是最可能解决你当前问题的核心点。
内容的提问来源于stack exchange,提问作者Raj Kumar
相关产品推荐
相关产品推荐

