Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple activities competing one intent

I got an interview question.....

How to specify which Activity to be launched from an implicit intent, when there are multiple activities competing to execute the intent, without requiring user intervention.

My answer to this question is to use proper intent-filter within every activity, but it just sounds wrong..

Thanks in advance!

like image 907
Sherman_Meow Avatar asked Mar 23 '23 16:03

Sherman_Meow


1 Answers

When creating an Intent you can pass explicit component name. i.e. class name. Only that component will now receive the intent.

example:

Intent myIntent = new Intent(getApplicationContext(),RequiredActivity.class);
startActivity(myIntent);

If you don't specify the exact component, Android will smartly let user choose one of the components that handles the intent.

example:

    Intent myIntent = new Intent(Intent.ACTION_VIEW);
    startActivity(myIntent);

If you want to go through all the components that handle the intent, yourself instead of letting android show choices to user, you can do that too:

example:

    Intent myIntent = new Intent(Intent.ACTION_VIEW);

    List<ResolveInfo> infoList = getPackageManager().queryIntentActivities(myIntent, 0);

    for (ResolveInfo ri : infoList){
        ActivityInfo ai = ri.activityInfo;
        String packageName = ai.packageName;
        String componentName = ai.name;

       // you can pick up appropriate activity to start 
       // if(isAGoodMatch(packageName,componentName)){
       //     myIntent.setComponent(new ComponentName(packageName,componentName));
       //     startActivity(myIntent);
       //     break;
       // }

    }

I got six Activity matches for above code:

enter image description here

like image 156
S.D. Avatar answered Apr 01 '23 05:04

S.D.