Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the ActivityNotFoundException?

In my app , I need to use startActivity to see the content of the file , or use the default application to open the certain file , but sometimes the android system may not install the application which is needed .

My question is how to handle this exception . I want a toast , not FC..

Any Advice? THX

like image 777
xuyao Avatar asked Dec 06 '11 11:12

xuyao


2 Answers

Just simply add that activity in your manifest file..

like,

<activity android:name=".ActivityName"
                  android:label="@string/app_name">
        </activity>

EDIT:

Now to catch the ActivityNOtFoundException put your code in,

try {

  // Your startActivity code wich throws exception  
} catch (ActivityNotFoundException activityNotFound) {

    // Now, You can catch the exception here and do what you want
}

Note: Be careful when you catch this ActivityNotFound Exception but you can't modified manifest file to run time, means once you encountered the exception and if you want to add that this activity tag at runtime then you can't.

like image 111
user370305 Avatar answered Sep 25 '22 18:09

user370305


Android 11 update:

If you target SDK version 30 or above, you shouldn't use resolveActivity anymore due to new package visibility rules. You'd better simply use try/catch solution mentioned in the accepted answer instead. For more information refer to the CommonsWare's answer

Old answer: (deprecated)

You can use resolveActivity method

    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }else {
        Toast.makeText(this,"No suitable app found!",Toast.LENGTH_SHORT).show();
    }
like image 34
Ehsan Heidari Avatar answered Sep 23 '22 18:09

Ehsan Heidari