Android 5.0运行时权限请求无弹窗,仅手动开GPS可用问题求助
问题分析与解决方案
嘿,我来帮你拆解下这个问题!你遇到的权限弹窗不出现的情况,核心原因是Android 5.0(API 21)并不支持运行时权限机制——这个机制是从Android 6.0(API 23)才正式引入的。
为什么弹窗不出现?
你代码里用的ActivityCompat.requestPermissions()方法,在Android 5.0及以下的设备上是不会触发权限请求弹窗的。因为这个版本的权限是在应用安装阶段就一次性授予的,不需要在运行时动态请求。所以你的权限检查逻辑在5.0设备上会直接走到else分支去获取位置,但这时候如果GPS没开启,自然拿不到位置信息,就出现了你说的“只有手动开GPS才正常运行”的现象。
怎么解决?
我们需要针对Android 5.0的特性调整代码,同时如果要兼容更高版本也可以保留对应的逻辑:
先确认Manifest里的权限声明
首先确保你已经在AndroidManifest.xml中添加了定位权限,这是所有版本都需要的:<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />添加GPS状态检查逻辑
在5.0设备上,权限已经安装时授予,所以我们需要检查的是GPS是否开启,如果没开就引导用户去设置开启:private boolean isGpsEnabled() { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); }修改getLocation()方法
针对不同Android版本做适配,同时处理GPS未开启的情况:private void getLocation() { // 针对Android 6.0及以上版本,检查运行时权限 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION); return; } } // 检查GPS是否开启,不管哪个版本都需要这一步 if (!isGpsEnabled()) { // 跳转到GPS设置页面 Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); Toast.makeText(this, R.string.please_enable_gps, Toast.LENGTH_SHORT).show(); return; } // 正常获取位置 mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { if (location != null) { mLastLocation = location; txt_latitude.setText(getString(R.string.location_latitude, mLastLocation.getLatitude())); txt_longitude.setText(getString(R.string.location_longitude, mLastLocation.getLongitude())); txt_timestamp.setText(getString(R.string.timestamp, mLastLocation.getTime())); } else { txt_latitude.setText(R.string.no_latitude); txt_longitude.setText(R.string.no_longitude); txt_timestamp.setText(R.string.no_timestamp); } } }); }
额外说明
- 如果你只需要适配Android 5.0,那可以去掉版本判断的部分,直接检查GPS状态后获取位置即可。
onRequestPermissionsResult()方法可以保留,用于处理6.0及以上版本用户拒绝权限的情况。
内容的提问来源于stack exchange,提问作者clinewton
相关产品推荐
相关产品推荐

