How to tell which app was selected by Intent.createChooser?

前端 未结 5 906
囚心锁ツ
囚心锁ツ 2020-11-29 05:26

Code:

Intent launchIntent = new Intent(Intent.ACTION_MAIN);
launchIntent.addCategory(Intent.CATEGORY_HOME);
Intent chooser = Intent.createChooser(launchInten         


        
5条回答
  •  猫巷女王i
    2020-11-29 05:29

    This should work for early versions of Android.

    Use intent PICKER instead of CHOOSER. The difference is that picker won't start the target intent automatically, but rather, it returns to onActivityResult() the target intent with the selected app's component name attached. Then you start the target intent in the callback as a 2nd step.

    A little bit of code should explain,

    // In MyActivity class
    static final int REQUEST_CODE_MY_PICK = 1;
    
    // Getting ready to start intent. Note: call startActivityForResult()
    ... launchIntent = the target intent you want to start;
    Intent intentPick = new Intent();
    intentPick.setAction(Intent.ACTION_PICK_ACTIVITY);
    intentPick.putExtra(Intent.EXTRA_TITLE, "Launch using");
    intentPick.putExtra(Intent.EXTRA_INTENT, launchIntent);
    this.startActivityForResult(intentPick, REQUEST_CODE_MY_PICK);
    // You have just started a picker activity, 
    // let's see what user will pick in the following callback
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == REQUEST_CODE_MY_PICK) {
             String appName = data.getComponent().flattenToShortString();
             // Now you know the app being picked.
             // data is a copy of your launchIntent with this important extra info added.
    
             // Don't forget to start it!
             startActivity(data);
        }
    }
    

提交回复
热议问题