android - 检查 SD 卡上是否存在图像 - Android

标签 android file share

我正在尝试从我的应用程序中共享图像,而该图像位于设备的外部存储中。问题在于,如果用户已将图像从外部存储中手动删除,他们仍然可以选择共享图像。我如何检查他们是否先删除了它?这是我的分享方法:

@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/

相关文章:

python - 我应该使用python文件的 `readinto`方法吗?

java - 调用 ioException 抛出函数

file - 如何将可视模式下的文本 block 保存到 Vim 中的文件中?

java - 从文件中删除某些数据

android - 使用 Flutter 接收共享文件 Intent

ios - swift分享功能在iphone中有效,但在ipad2中出错

android - 使用 onBackPressed 仅从第一个 fragment 退出应用程序

三星 S4 API 21 上的 android ormlite NoClassDefFoundError

java - 使用 C++ 时找不到 native 方法

Android:通过消息、G+、twitter、facebook 可靠地分享来自 Assets 的图像?