【发布时间】:2018-08-22 14:39:07
【问题描述】:
在运行时请求所有权限后,我正在尝试将文件写入/读取到外部存储中。
清单:
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
运行时:
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE.
Java代码:
public class FilesUtil {
public static String saveImageToFile(Bitmap image ,String employeeId){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/AppName");
myDir.mkdirs();
String filename = String.format("EMPLOYEE_%s.png", employeeId);
File file = new File (myDir, filename);
if (file.exists()){
file.delete(); // here i'm checking if file exists and if yes then i'm deleting it but its not working
}
FileOutputStream out = null;
try {
out = new FileOutputStream(file,false);
image.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return filename;
}
public static String getImagePath(String employeeId){
String result = Environment.getExternalStorageDirectory().toString() + "/AppName/";
String filename = String.format("EMPLOYEE_%s.png", employeeId);
return result + filename;
}
}
加载文件:
private Bitmap getCurrentPhoto() {
File image = new File(FilesUtil.getImagePath(getCurrentEmployeeId()));
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
return bitmap;
}
我第一次运行应用程序时打开失败:EACCES(权限被拒绝)仅在 Android 6.0.1 上,但是,在其他版本的操作系统中,该功能运行良好。如果我在 6.0.1 上杀死并重新打开该应用程序,该功能运行正常。
【问题讨论】:
-
同时上传您的代码。
-
我将代码添加到问题中。 @SusmitAgrawal
-
你在哪里请求运行时权限?
-
在每个活动的 OnCreate 中。如果任何权限被拒绝,应用程序将进入禁用模式,您无法执行任何操作。因此,不允许权限不是一种选择。我必须补充一点:在我以 API 22 为目标并在“安装”对话框中请求权限之前,该应用程序在所有设备上都运行良好。
标签: android permissions android-6.0.1-marshmallow