How to get Activity Class from intent filter

2020-07-30 00:09发布

Suppose there is an application with package name com.example.

The application has an activity which has an intent filter android.intent.action.SEND

Now I want to programatically find the component class that supports the above intent filter.

This code filters all the classes that matches ACTION_SEND.

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);

But, I want to choose the activity only from the package that matches com.example.

2条回答
We Are One
2楼-- · 2020-07-30 00:35

This is how I achieved it. Get the list of all the packages that support the intent.

List<ResolveInfo> rInfo =  getActivity().getPackageManager().queryIntentActivities(createShareIntent(),0);
for(ResolveInfo r:rInfo){
    if(r.activityInfo.packageName.equals("com.example")){

        chosenName = new ComponentName( r.activityInfo.packageName,
                r.activityInfo.name);
        break;
    }
}

Intent choiceIntent = new Intent(createShareIntent());
choiceIntent.setComponent(chosenName);
startActivity(choiceIntent);

Create share intent

private Intent createShareIntent() {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.putExtra(Intent.EXTRA_TEXT,"Message");
    shareIntent.setType("text/plain");
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject...");
    return shareIntent;
}
查看更多
干净又极端
3楼-- · 2020-07-30 00:43

The PackageManager can be retrieved with Context.getPackageManager() and queryIntentActivities with the intent you are considering will return the ResolveInfo of Activities that can perform that intent.

ResolveInfo.activityInfo will give you the ActivityInfo which has packageName which is what you are looking to filter on.

Once you have selected the target you want, you can make the ComponentName for that activity using the package name and class and setComponent() on the desired intent to explicitly target the activity you want.

查看更多
登录 后发表回答