简体   繁体   中英

Open file with external Intent/Application

After creating a file in the app's fileDirectory I would like to open it with an external app like the Adobe Reader etc. To achive this I tried to use an Intent like in the code below.

ContextWrapper cw = new ContextWrapper(getApplicationContext());
java.io.File fileItem = new java.io.File(cw.getFilesDir() + "/sync/arbitraryFileName.extension");

MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent newIntent = new Intent(Intent.ACTION_VIEW);
String fileExtension = StaticHelper.fileExt(((File) item).getFileName());
if (fileExtension != null) {
    String mimeType = myMime.getMimeTypeFromExtension(fileExtension);
    String bb = Uri.fromFile(fileItem).toString();
    newIntent.setDataAndType(Uri.fromFile(fileItem), mimeType);
    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try {
        getApplicationContext().startActivity(newIntent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
    }
} else {
    Toast.makeText(getApplicationContext(), "no extension found", Toast.LENGTH_SHORT).show();
}

But sadly this code does not work: The apps are always saying that the file does not exist - but in the device's ADB shell I can find the file with exactly the same path which is used in my code. I have already added

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

in my code, but it did not help at all.

Third-party apps do not have access to your app's portion of internal storage . Use something like FileProvider to make this content available to other apps .

Also:

  • Replace all occurrences of getApplicationContext() with this in your code shown above. Only use getApplicationContext() when you know exactly why you are using getApplicationContext() .

  • Get rid of the ContextWrapper , as you do not need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM