Sherman_Meow
Sherman_Meow

Reputation: 247

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!

Upvotes: 4

Views: 1633

Answers (1)

s.d
s.d

Reputation: 29436

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

Upvotes: 8

Related Questions