Android - How do I open a file in another app via Intent?

后端 未结 2 1725
礼貌的吻别
礼貌的吻别 2021-02-15 07:42

I\'m trying to open a file using another app, i.e. opening a .jpg with Gallery, .pdf with Acrobat, etc.

The problem I\'m having with this is when I try to open the file

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-15 08:42

    Posting my changes here in case it can help someone else. I ended up changing the download location to an internal folder and adding a content provider.

    public void open_file(String filename) {
        File path = new File(getFilesDir(), "dl");
        File file = new File(path, filename);
    
        // Get URI and MIME type of file
        Uri uri = FileProvider.getUriForFile(this, App.PACKAGE_NAME + ".fileprovider", file);
        String mime = getContentResolver().getType(uri);
    
        // Open file with user selected app
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, mime);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
    }
    

提交回复
热议问题