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

后端 未结 2 1731
礼貌的吻别
礼貌的吻别 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条回答
  • 2021-02-15 08:35

    I used this piece of code and it worked perfectly fine on android 6 and below not tested on the higher version

    public void openFile(final String fileName){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(new File(android.os.Environment.getExternalStorageDirectory()
                .getAbsolutePath()+ File.separator+"/Folder/"+fileName));
        intent.setDataAndType(uri, "audio/mpeg");
        startActivity(intent);
    }
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
提交回复
热议问题