Android系统中,目前Dangerous级别的权限都需要动态申请。步骤如下;
1、AndroidManfiest.xml中申明需要的动态权限
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.plbear.yyj.dangerouspermission"> <!-- 声明权限 --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
2、代码中检查权限、申请权限
如下方法执行之后,会弹出提示框,提示要申请该权限
fun onClick_requestPermission(v: View) { if (ContextCompat.checkSelfPermission(applicationContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 0); } }
3、获取结果
1 override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { 2 var i = 0; 3 while (i < permissions.size) { 4 Log.e(TAG, "permission:" + permissions[i] + " grantResult:" + grantResults[i]) 5 i++ 6 } 7 super.onRequestPermissionsResult(requestCode, permissions, grantResults) 8 }
转载请注明链接:http://www.cnblogs.com/yanyojun/p/8013003.html
本文所有代码已放置到GitHub:https://github.com/YanYoJun/DangerousPermission/