赞
踩
相关代码:
<!--Android 6-10 权限适配--> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!--Android 10以上 权限适配--> <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:requestLegacyExternalStorage="true" android:supportsRtl="true" android:theme="@style/Theme.AndroidProGuard" tools:targetApi="31"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
// 工具类配置 Utils.init(this) // 请求权限 private fun requestFilePermission() { when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {// Android 10以上 if (!Environment.isExternalStorageManager()) { AlertDialog.Builder(this) .setTitle("提示") .setMessage("开启文件访问权限!") .setNegativeButton( "取消" ) { dialog, _ -> dialog.dismiss() } .setPositiveButton("前往") { dialog, _ -> dialog.dismiss() startActivity(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)) }.create().show() } } Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> {// Android 6以上 if (!PermissionUtils.isGranted( Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE ) ) { PermissionUtils.permission( Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE ).callback { isAllGranted, _, _, _ -> if (!isAllGranted) { ToastUtils.showShort("没有开启文件权限") } }.request() } } else -> {} } }
PermissionUtils的工具类导入
implementation "com.blankj:utilcodex:1.30.0"
// 获取根目录
private fun getExternalStorageDirectory(): String? {
val extFileStatus = Environment.getExternalStorageState()
val extFile = Environment.getExternalStorageDirectory()
// 判断是否处于挂载状态
if (extFileStatus == Environment.MEDIA_MOUNTED && extFile.exists() && extFile.isDirectory
&& extFile.canWrite()
) {
return extFile.absolutePath
}
return null
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。