我正在开发一个壁纸应用程序,我在其中保存一个具有相同名称的图像并将其发送到图库意图。
因为保存了每个具有相同名称的图像,所以每次在图库意图中都会遇到相同图像的问题。
正在发生的事情是新图像正在取代,但我在画廊意图中变老了。 新图像替换旧图像,但仍然库图像意图显示旧图像而不是新图像
因此我希望每次都使用新名称保存图像,但也会删除较旧的已保存图像。
注意:始终将图像保存为图像++,但也删除以前的图像。
我的代码:
public void setAsWallpaper(Bitmap bitmap) {
String dirname2 = "/Wallpaper/";
File myDir2 = new File(Environment.getExternalStorageDirectory()
.getPath() + dirname2);
myDir2.mkdirs();
String fname2 = "image" + ".jpg";
File file2 = new File(myDir2, fname2);
if (file2.exists())
file2.delete();
try {
FileOutputStream out = new FileOutputStream(file2);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
success = true;
} catch (Exception e) {
Toast.makeText(_context, "failed", Toast.LENGTH_SHORT).show();
}
if (success) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(Uri.parse("file://"
+ "/sdcard/Wallpaper/image.jpg"), "image/*");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(intent);
} else {
Toast.makeText(_context, "failed", Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:0)
如果您没有可以作为参数发送到方法的图像的原始名称。然后,以下方法生成随机文件名:
public String random() {
Random generator = new Random();
StringBuilder randomStringBuilder = new StringBuilder();
int randomLength = generator.nextInt(MAX_LENGTH);
char tempChar;
for (int i = 0; i < randomLength; i++){
tempChar = (char) (generator.nextInt(96) + 32);
randomStringBuilder.append(tempChar);
}
return randomStringBuilder.toString();
}
我通常循环抛出我文件夹中的所有文件并删除那里的所有图像(总是一个图像)。然后使用随机名称保存新的名称,如下所示:
public void setAsWallpaper(Bitmap bitmap) {
String dirname2 = "/Wallpaper/";
File myDir2 = new File(Environment.getExternalStorageDirectory()
.getPath() + dirname2);
// delete folder and all files in it. then re-create it.
if(myDir2.exists()) {
String[] myFiles = myDir2.list();
for (int i=0; i<myFiles.length; i++) {
File myFile = new File(myDir2, myFiles[i]);
myFile.delete();
}
myDir2.delete();
}
myDir2.mkdirs();
String fname2 = random() + ".jpg";
File file2 = new File(myDir2, fname2);
if (file2.exists())
file2.delete();
try {
FileOutputStream out = new FileOutputStream(file2);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
success = true;
} catch (Exception e) {
Toast.makeText(_context, "failed", Toast.LENGTH_SHORT).show();
}
if (success) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(Uri.parse("file://"
+ "/sdcard/Wallpaper/" + fname2), "image/*");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(intent);
} else {
Toast.makeText(_context, "failed", Toast.LENGTH_SHORT).show();
}
}