我使用res/drawable
和Gallery
将图片从InputStream
保存到OutputStream
。它工作正常,保存图像。但问题是它不会更新图库中的图像。如果我使用ES File Explorer
检查文件夹,那么我可以在那里看到图像。我还检查了ddms
,一旦write
代码执行,它也会在那里更新图像。
如果保存服务器映像,它的工作正常。如何防止这个问题?我想在图像保存后立即更新图库。
我也尝试MediaScanner
扫描文件夹但没有效果。
我的代码:
Toast.makeText(context, "Downloading Image...\nPlease Wait.",
Toast.LENGTH_LONG).show();
File direct = new File(Environment.getExternalStorageDirectory()
+ "/Images");
if (!direct.exists()) {
direct.mkdirs();
}
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy-HHmmss");
Date date = new Date();
String CurrentDateTime = dateFormat.format(date);
InputStream input = null;
OutputStream output = null;
try {
input = context.getResources().openRawResource(
context.getResources().getIdentifier(
"@drawable/" + picName, "drawable",
context.getPackageName()));
output = new FileOutputStream(direct + "/" + "IMG-"
+ CurrentDateTime + ".jpg");
byte[] buf = new byte[1024];
int len;
while ((len = input.read(buf)) > 0) {
output.write(buf, 0, len);
}
MediaScannerConnection.scanFile(context,
new String[] { direct.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Toast.makeText(context, "Image Saved.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e("Internal Image Save Error->", e.toString());
Toast.makeText(context,
"Couldn't Save Image.\nError:" + e.toString() + "",
Toast.LENGTH_LONG).show();
} finally {
try {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
} catch (IOException ignored) {
Log.e("Internal Image Save Error->", ignored.toString());
Toast.makeText(
context,
"Couldn't Save Image.\nError:" + ignored.toString()
+ "", Toast.LENGTH_LONG).show();
}
}
答案 0 :(得分:1)
你必须广播外部目录...
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
如果你在SD卡中创建外部文件夹,然后它不显示在gallary中,那么使用下面的代码。
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
Runtime.getRuntime().exec(
"am broadcast -a android.intent.action.MEDIA_MOUNTED -d file://"
+ CommonVariable.abc_FOLDER);
} else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://" + CommonVariable.abc_FOLDER)));
}
其他扫描方法。
Uri contentUri = Uri.fromFile(destFile);
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
我希望它对你有用。