Vektor88
Vektor88

Reputation: 4920

Open unknown file type with specified application

I'm using this code to open a file with the specified app:

File file = new File("/path/to/file.ext");
    if(file.exists())
    {
        Uri path=Uri.fromFile(file);

        Intent intent=new Intent(Intent.ACTION_VIEW, path);
       // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setPackage("com.example.myapp");
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        String ext=file.getName().substring(file.getName().indexOf(".")+1);
        String type = mime.getMimeTypeFromExtension(ext);

        intent.setDataAndType(Uri.fromFile(file),type);


        try
        {
            startActivity(intent);
        }
        catch(ActivityNotFoundException e)
        {
            Toast.makeText(this, "No software found", Toast.LENGTH_SHORT).show();
        }

It works perfectly with .zip files, but doesn't work with unconventional file extensions, it throws AcivityNotFoundException. Is there a way to programmatically associate a file type to an app, or to force the app to open the given file?

Upvotes: 0

Views: 1310

Answers (2)

Robin
Robin

Reputation: 10368

The correct way to do it is:

List<ResolveInfo> resInfo = packageManager.queryIntentActivities(intent, flags);
if(resInfo !=null && resInfo.size()>0) {
    //Display the activity list that can handle this file format
} else {
    //Handle this file by your own code or display error message
}

If a file is apprently cannot be handled by any of the installed application in the system or even by your own programme - then you just display a error message. It is a exception handling.

If you are 100% sure that the app can open the file - open the app I'm prompted a file chooser and you can open that file with unknown extension - Well, that could be impossible if the target application just does not provide this interface to take the file input via a intent and you cannot hijack it. Or you might use sysdump tool or hierarchy viewer to see if the target application is using a separated activity to handle the file chosen from the file picker. If it does so, you may still not be able do send the file to it since the activity might not be exported. Try to de-compile the target app by apk-tool and java-decompiler to see if you have any luck.

Upvotes: 1

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

You got it wrong. If no app claims to be able to handle given file format then what app you'd like to force to do that? If you want to make your app handle any file format, make your Intent filter so generic that it will always match. If no app does so, trying to force anything will usually not end right.

Upvotes: 0

Related Questions