user2863638 user2863638 - 4 months ago 6
Android Question

Why can't I find activity from app that is on device?

I have the application that I want to open from another. It's an app I've developed before but android seems to be unable to find it:

Intent intent = new Intent("org.example.android.ExampleActivity");
PackageManager packageManager =getActivity().getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
boolean isIntentSafe = activities.size() > 0;


isIntentSafe
is always false and I've copied this code directly from android docs.

Answer

When you do this:

Intent   intent = new Intent("org.example.android.ExampleActivity");
PackageManager packageManager =getActivity().getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);

You are asking the PackageManager to find an Activity that has an Intent filter that looks like this:

        <intent-filter>
            <action android:name="org.example.android.ExampleActivity"/>
        </intent-filter>

This is probably not what you intended and is the reason that it returns an empty list.

When you create an Intent using the constructor that takes a single argument, that argument is interpreted as an ACTION, not a class name.

If you are looking for a specific Activity, you should use explicit Intent resolution like this:

Intent   intent = new Intent();
intent.setClassName ("org.example.android", "org.example.android.ExampleActivity");
PackageManager packageManager =getActivity().getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);

In this case, you create an empty Intent and then set the class name using an explicit package name and class name.

Comments