[英]Save Image in External Storage
my problem is , When I click on picture , it shows the saved message But the photo will not be saved.I also allowed access to external storage WRITE_EXTERNAL_STORAGE我的问题是,当我点击图片时,它显示已保存的消息但照片不会被保存。我还允许访问外部存储 WRITE_EXTERNAL_STORAGE
public void onClick(View v) {
if(isExternalStorageWriteable()) {
FileOutputStream outputStream;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.img3);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MyImage.png");
try {
outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this,"Pic Created : "+file,Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(this,"SDCard Not is Ready",Toast.LENGTH_SHORT)
.show(); } }
public boolean isExternalStorageWriteable()
{
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state); }
"I also allowed access to external storage WRITE_EXTERNAL_STORAGE" in the manifest or you asked for the permission at runtime? “我还允许访问清单中的外部存储 WRITE_EXTERNAL_STORAGE”,或者您在运行时要求获得许可?
I guess you are having this problem only on devices with Android version >= 23 (6.0).我猜您只有在 Android 版本 >= 23 (6.0) 的设备上才会遇到这个问题。 You should check if you have the permission to write in the external storage before doing it, and in case you should ask for permission:你应该在做之前检查你是否有权限在外部存储中写入,如果你应该请求权限:
ContextCompat.checkSelfPermission(thisActivity, Manifest.permission. WRITE_EXTERNAL_STORAGE);
ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
https://developer.android.com/training/permissions/requesting.html https://developer.android.com/training/permissions/requesting.html
If permission is granted check for stacktrace and post it here, for sure the "Pic Created" toast should stay inside the try-catch at the end of the block, and inside the catch blocks you would have to launch a negative toast.如果获得许可,检查堆栈跟踪并将其发布在这里,确保“Pic Created”toast 应保留在块末尾的 try-catch 内,而在 catch 块内,您将不得不启动否定 Toast。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.