Skip to content Skip to sidebar Skip to footer

Why Would An Android Open File Intent Hang While Opening An Image?

My Problem: When openFile() intent attempts StartActivityForResult, the application hangs with a blank screen and circular cursor. The file(s) are stored to app. What I have done:

Solution 1:

I was able to resolve my issue combined with S-Sh's second suggestion of considering the use of FileProvider. I had to perform some refinements and ended up with the following to work. I also provided links to the sources in which I used.

Context of the solution:

As a note to future readers as to the context of this solution within my Android app, the code below is launched by clicking a "clickable" TableRow in a TableLayout. The TableLayout lists each filename and file ID as a TableRow. Once a row is clicked, the onClick method of the selected TableRow the filename is acquired and the File class and FileProvider are used and filename passed to create an Uri. This Uri is then passed to an openFile(Uri uri) method I created encapsulating (so-to-speak) the Intent used to open the file.

Code

Adding of the FileProvider to the AndroidManifest.xml' within the` tag:

<provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="com.mistywillow.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
    <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
</provider>

Creating within res directory the file_paths.xml and xml directory (res/xml/):

<?xml version="1.0" encoding="utf-8"?>
   <paths xmlns:android="http://schemas.android.com/apk/res/android">
      <files-path name="myFiles" path="." />
   </paths>

The onClick capturing the filename and preparing the Uri to be passed to the openFile():

    row.setOnClickListener(v -> {

        TableRowtablerow= (TableRow) v;
        TextViewsample= (TextView) tablerow.getChildAt(1);
        Stringresult= sample.getText().toString();

        FilefilePaths=newFile(getFilesDir().toString());
        FilenewFile=newFile(filePaths, result);
        UricontentUri= getUriForFile(getApplicationContext(), "com.mydomain.fileprovider", newFile);
        openFile(contentUri);

    });

The openFile(Uri uri) method containing the Intent to open a file:

privatevoidopenFile(Uri uri){
    Intentintent=newIntent(Intent.ACTION_VIEW);
    intent.setData(uri);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivityForResult(intent, 2);
}

Links referenced:

https://developer.android.com/reference/androidx/core/content/FileProvider

FileProvider - IllegalArgumentException: Failed to find configured root

Solution 2:

Try use origin Uri itself:

 intent.setDataAndType(uri, "image/jpeg");

Post a Comment for "Why Would An Android Open File Intent Hang While Opening An Image?"