我正在构建一个应用程序,允许用户保存位图或共享它而不保存它。第二个功能不太起作用。我知道应用程序需要先将文件保存到设备上,然后才能在社交媒体应用程序上共享它,所以我的想法就是在文件成功共享后立即自动从设备中删除文件。我已经构建了一个尝试两种不同方法的删除方法,但都没有工作:
第一种方法:
public void deleteFile(String path){
File file = new File(path);
try {
file.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
}
第二种方法:
public void deleteFile(String path){
File file = new File(path);
boolean deleted = file.delete();
}
我从分享方法中调用deleteFile(String)
:
public void shareMeme(Bitmap bitmap) {
String path = MediaStore.Images.Media.insertImage(Objects.requireNonNull(getContext()).getContentResolver(), bitmap, "Meme", null);
Uri uri = Uri.parse(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.putExtra(Intent.EXTRA_TEXT, "This is my Meme");
getContext().startActivity(Intent.createChooser(share, "Share Your Meme!"));
deleteFile(path);
}
关于你陈述的问题,insertImage()
返回Uri
的字符串表示。那Uri
不是文件。在它上面调用getPath()
是没有意义的,你不能删除任何基于该路径的东西。
更广泛地说,如果您打算立即删除内容:
MediaStore
如果要共享,但删除它:
MediaStore
要在不使用MediaStore
的情况下与其他应用分享图像:
getCacheDir()
中的文件(在Context
上调用,例如Activity
或Service
)FileProvider
将该文件提供给其他应用程序除此之外:
ACTION_SEND
中使用通配符MIME类型。您是提供要发送内容的人。您知道实际的MIME类型。用它。ACTION_SEND
活动同时尊重EXTRA_TEXT
和EXTRA_STREAM
。大多数人似乎这样做,但这种行为超出了ACTION_SEND
规范。insertImage()
在Android Q上已弃用。首先,你需要检查你的file
是否存在,(也许你设置了错误的路径?)。然后删除file
File file = new File(path);
if (file.exists()){
if (file.delete()) {
Toast.makeText(this, "file Deleted :" + path, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "file not Deleted :" + path, Toast.LENGTH_SHORT).show();
}
}