public static boolean openFileAttachment ( final Context context , final String sourcePath , final String selectedFilePath , final String mimeTypeString ) { if ( ( Environment . MEDIA_MOUNTED . equals ( Environment . getExternalStorageState ( ) ) || ! Environment . isExternalStorageRemovable ( ) ) && hasPermission ( context , Manifest . permission . WRITE_EXTERNAL_STORAGE ) ) { File selectedFile = new File ( selectedFilePath ) ; String selectedFileName = null ; if ( selectedFile . exists ( ) ) { selectedFileName = selectedFile . getName ( ) ; final Intent intent = new Intent ( ) ; intent . setAction ( android . content . Intent . ACTION_VIEW ) ; /* Attachments were downloaded into app private data dir. In order for external app to open * the attachments, the file need to be copied to a download folder that is accessible to public * The folder will be sdcard/Downloads/apptentive-received/<file name> */ File downloadFolder = Environment . getExternalStoragePublicDirectory ( Environment . DIRECTORY_DOWNLOADS ) ; File apptentiveSubFolder = new File ( downloadFolder , "apptentive-received" ) ; if ( ! apptentiveSubFolder . exists ( ) ) { apptentiveSubFolder . mkdir ( ) ; } File tmpfile = new File ( apptentiveSubFolder , selectedFileName ) ; String tmpFilePath = tmpfile . getPath ( ) ; // If destination file already exists, overwrite it; otherwise, delete all existing files in the same folder first. if ( ! tmpfile . exists ( ) ) { String [ ] children = apptentiveSubFolder . list ( ) ; if ( children != null ) { for ( int i = 0 ; i < children . length ; i ++ ) { new File ( apptentiveSubFolder , children [ i ] ) . delete ( ) ; } } } if ( copyFile ( selectedFilePath , tmpFilePath ) == 0 ) { return false ; } intent . setDataAndType ( Uri . fromFile ( tmpfile ) , mimeTypeString ) ; try { context . startActivity ( intent ) ; return true ; } catch ( ActivityNotFoundException e ) { ApptentiveLog . e ( e , "Activity not found to open attachment: " ) ; logException ( e ) ; } } } else { Intent browserIntent = new Intent ( Intent . ACTION_VIEW , Uri . parse ( sourcePath ) ) ; if ( Util . canLaunchIntent ( context , browserIntent ) ) { context . startActivity ( browserIntent ) ; } } return false ; }
This function launchs the default app to view the selected file based on mime type