如何使用Intent.ACTION_VIEW打开保存到内部存储的私有文件?

 手机用户2502853355 发布于 2023-01-31 19:39

我正在尝试一个示例程序将文件存储在内部存储中,并使用Intent.ACTION_VIEW打开它.

为了以私密模式存储文件,我按照这里提供的步骤操作.

我能够在/data/data/com.storeInternal.poc/files的内部存储中找到创建的文件.*

但是当我试图打开文件时,它无法打开.

请在下面找到我用于它的代码.

public class InternalStoragePOCActivity extends Activity {
    /** Called when the activity is first created. */
    String FILENAME = "hello_file.txt";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        createFile();
        openFile(FILENAME);
    }

    public FileOutputStream getStream(String path) throws FileNotFoundException {
        return openFileOutput(path, Context.MODE_PRIVATE);
    }

    public void createFile(){

        String string = "hello world!";
        FileOutputStream fout = null;
        try {
            //getting output stream
            fout = getStream(FILENAME);
            //writng data
            fout.write(string.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fout!=null){
                //closing the output stream
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

    public void openFile(String filePath) {
        try {
            File temp_file = new File(filePath);

            Uri data = Uri.fromFile(temp_file);
            String type = getMimeType(data.toString());

            Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
            intent.setDataAndType(data, type);
            startActivity(intent);

        } catch (Exception e) {
            Log.d("Internal Storage POC ", "No Supported Application found to open this file");
            e.printStackTrace();

        }
    }

    public static String getMimeType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);

        if (extension != null) {
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            type = mime.getMimeTypeFromExtension(extension);
        }

        return type;
    }
}

如何打开由任何其他现有/适当的应用程序使用Context.MODE_PRIVATE存储的文件.例如:file.pdf应该由PDF阅读器,视频播放器等打开.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有