我对android缓存有些困惑,在运行时android app cache需要外部存储读写权限。任何人都可以帮助我解决这个困惑。例如,
File tempFile = File.createTempFile("img", ".png", getExternalCacheDir());
String imgPath = tempFile.getAbsolutePath();
答案 0 :(得分:0)
您必须在运行时https://developer.android.com/training/permissions/requesting.html,示例,
询问权限public void requestPermissionForExternalStorage() {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(activity, "External Storage permission needed. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
}
}
答案 1 :(得分:0)
试试这个,
存储权限
private static final int REQUEST_STORAGE = 112;
if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE,android.Manifest.permission.READ_EXTERNAL_STORAGE};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST_STORAGE );
} else {
File tempFile = File.createTempFile("img", ".png", getExternalCacheDir());
imgPath = tempFile.getAbsolutePath();
}
} else {
File tempFile = File.createTempFile("img", ".png", getExternalCacheDir());
imgPath = tempFile.getAbsolutePath();
}
获取权限结果
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
File tempFile = File.createTempFile("img", ".png", getExternalCacheDir());
imgPath = tempFile.getAbsolutePath();
}
}
}
}
检查marshmallow的权限
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}