当前位置:主页 > 移动开发 > Android代码 >

快速解决安卓7.0系统写入SD卡权限失败的问题

时间:2020-11-30 12:45:02 | 栏目:Android代码 | 点击:

如图所示,在mainfest文件中声明了SD卡的读和写权限,仍旧报错:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

安卓23.0版本以上,不仅仅要设置上面的权限,还要在对SD卡有读写操作的地方授权,下面是公共类:

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;

public class PermisionUtils {

 // Storage Permissions
 private static final int REQUEST_EXTERNAL_STORAGE = 1;
 private static String[] PERMISSIONS_STORAGE = {
  Manifest.permission.READ_EXTERNAL_STORAGE,
  Manifest.permission.WRITE_EXTERNAL_STORAGE};

 /**
 * Checks if the app has permission to write to device storage
 * If the app does not has permission then the user will be prompted to
 * grant permissions
 *
 * @param activity
 */
 public static void verifyStoragePermissions(Activity activity) {
 // Check if we have write permission
 int permission = ActivityCompat.checkSelfPermission(activity,
  Manifest.permission.WRITE_EXTERNAL_STORAGE);

 if (permission != PackageManager.PERMISSION_GRANTED) {
  // We don't have permission so prompt the user
  ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
   REQUEST_EXTERNAL_STORAGE);
 }
 }
}

然后直接在需要授权的地方调用:

verifyStoragePermissions(this);

this指的是当前的Activity,程序运行会出现以下结果:

点击ALLOW之后,程序获取SD卡读写权限,就算你把代码里的

verifyStoragePermissions(this);语句删了,只要不卸载应用程序,权限就仍然存在。

您可能感兴趣的文章:

相关文章