我正在尝试从我的应用程序中共享图像,而该图像位于设备的外部存储中。问题在于,如果用户已将图像从外部存储中手动删除,他们仍然可以选择共享图像。我如何检查他们是否先删除了它?这是我的分享方法:
@SuppressLint("NewApi")
private void shareImage(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
//create new files
File f = new File(mExternalImagePath);
if (f.exists()) {
//Do action
f.setReadable(true, false);
//create new file in the system
try {
f.createNewFile();
} catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
//create new file object from the absolute path
File f1 = f.getAbsoluteFile();
f1.setReadable(true, false);
Uri path = Uri.fromFile(f1);
intent.putExtra(Intent.EXTRA_STREAM, path );
Intent mailer = Intent.createChooser(intent, null);
//mailer.setType("image/*");
startActivity(mailer);
}else{
Log.d("not exist", "not exist");
}
}
它可以工作,但总是共享,所以如果图像被手动删除,它会尝试发送空白图像。
最佳答案
我不确定您的问题是否是因为您正在通过调用 f.createNewFile()
创建新文件或者别的什么。
无论哪种方式,您都应该能够极大地简化您的代码以获取流并像这样发送 Intent :
private void shareImage(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
//create new files
File f = new File(mExternalImagePath);
if (f.exists()) {
Uri path = Uri.fromFile(f);
intent.putExtra(Intent.EXTRA_STREAM, path);
Intent mailer = Intent.createChooser(intent, null);
startActivity(mailer);
}else{
Log.d("not exist", "not exist");
}
}
这有望解决您的问题,或者使问题更加明显并帮助您解决问题。
您还可以添加对文件长度的检查,以确保在您通过调用 .length()
发送 Intent 之前它以某种可读的形式存在。在 f
.
if (f.length() == 0){
Log.d("File Empty", "File does not have any content");
}else{
// create the intent and send
}
关于android - 检查 SD 卡上是否存在图像 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21530362/