syntagma
syntagma

Reputation: 24294

Open any type of file of Android without declaring MIME type explicitly

I am using this method to open launch an Intent to open a file on Android (I've described my problems in the comments):

public static void openFile(Context context, String fileName) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // intent.setType(FileHelper.getMimeType(file)); // this doesn't work for PDF files
        // opens Intent but then the chosen application doesn't open the file
        intent.setType("application/pdf");  // this works correctly for PDF files
        intent.setData(Uri.parse("file://" + getPath(context) + fileName));
        context.startActivity(intent);
    }

I would like to have a single method that would open any kind of file, without having to explicitly specify the MIME type, is that possible?

Upvotes: 2

Views: 1081

Answers (1)

berserk
berserk

Reputation: 2728

Mime type is needed to open the file i.e. we have to set Data and Type. You can use this function to open any file:

public void openFile(Context ctx,String filepath)   
{   
Uri ttt = Uri.parse("file://" + filepath);
Intent intent = new Intent(Intent.ACTION_VIEW);
String arr[] = filepath.split("\\.");
MimeTypeMap myMime = MimeTypeMap.getSingleton();
String mimeType = myMime.getMimeTypeFromExtension(arr[arr.length - 1]);
intent.setDataAndType(ttt, mimeType);
ctx.startActivity(intent);
}

However, there will be problem in files without extension.

Upvotes: 3

Related Questions