我正在开发一个墙纸应用程序,其中我保存了一个具有相同名称的图像并将其发送到图库意图。
因为用相同的名称保存每个图像,所以我每次在图库意图中都遇到获取相同图像的问题。
发生的是新图像正在替换,但是我在图库意图中得到了较旧的图像。新图像替换旧图像,但画廊意图仍显示旧图像而不是新图像
所以我想每次都用新名称保存图像,但也要删除较旧的保存图像。
注意:始终将图像保存为image ++,但也要删除先前的图像。
我的代码:
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();
}
}
如果您没有图片的原始名称,则可以将其作为参数发送给您的方法。然后,通过以下方法生成随机文件名:
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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句