Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if an Activity exists on the current device?

Is there a way to check and see if an Activity exists on your device? If I have a youtube video link I want to specify it open in the YouTube PlayerActivity. However, I don't want to crash if for some reason they don't have it.

Is there a way to check and see if the activity exists? I don't think I can catch the runtime exception since startActivity() doesn't throw it.

like image 936
stormin986 Avatar asked May 20 '10 23:05

stormin986


People also ask

How do you know if activity is visible?

In your finish() method, you want to use isActivityVisible() to check if the activity is visible or not. There you can also check if the user has selected an option or not. Continue when both conditions are met.

How can I get current activity?

This example demonstrates How to get current activity name in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How can I tell if activity has stopped?

Check to see whether this activity is in the process of finishing, either because you called finish() on it or someone else has requested that it finished. This is often used in onPause() to determine whether the activity is simply pausing or completely finishing.

How do I get running activities on Android?

There's an easy way of getting a list of running tasks from the ActivityManager service. You can request a maximum number of tasks running on the phone, and by default, the currently active task is returned first. Once you have that you can get a ComponentName object by requesting the topActivity from your list.


2 Answers

You could create an Intent object with necessary component info and then check if the intent is callable or not.I stumbled upon this snippet here on SO, don't have the link to the actual thread.

private boolean isCallable(Intent intent) {
        List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 
            PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
}
like image 193
Samuh Avatar answered Oct 12 '22 04:10

Samuh


This is the simplest way to do this:

boolean activityExists = intent.resolveActivityInfo(getPackageManager(), 0) != null;

It is also the one recommended by Google:

To first verify that an app exists to receive the intent, call resolveActivity() on your Intent object. If the result is non-null, there is at least one app that can handle the intent and it's safe to call startActivity(). If the result is null, you should not use the intent and, if possible, you should disable the feature that invokes the intent.

like image 24
Malcolm Avatar answered Oct 12 '22 02:10

Malcolm