Q:

Android intent filer for opening pdf files

I added my pdf viewer app to "Complete action using" list for pdf files. But if I run a file on the list, the app just shut down.
I made intent filter in onCreate method and manifest file, but I couldn't figure out how to fix this error.
PdfActivity.java
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pdf); //xml file for pdf view page

    Intent intent = getIntent();

    if(intent != null) {
        if(Intent.ACTION_VIEW.equals(intent.getAction())) {
            startActivity(intent);
        }
    }

    init();
}

AndroidManifest.xml
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity
        android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name=".PdfActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.BROWSABLE" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:scheme="content" />
            <data android:scheme="file" />
            <data android:mimeType="application/pdf" />
        </intent-filter>
    </activity>

</application>

Please help me in this problem.

A:

Try this
  //Method to generate a MIME Type
  private static String getMimeType(String url) {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return type;
}

 //Method to generate File URI
 private static Uri getFileUri(String filePath) {
    Uri fileUri = null;
    File file = new File(filePath);
    try {
        if (Build.VERSION.SDK_INT >= 24) {
            Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
            m.invoke(null);
        }
        fileUri = Uri.fromFile(file);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fileUri;
}

 //Intent
 Intent intent = new Intent(Intent.ACTION_VIEW);
 intent.setDataAndType(getFileUri(file_path), getMimeType(file_path));
 startActivity(intent);

