How to get Activity Class from intent filter

北战南征 提交于 2019-12-21 23:37:04

问题


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.


回答1:


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.




回答2:


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;
}


来源:https://stackoverflow.com/questions/18148420/how-to-get-activity-class-from-intent-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!