Cannot make startActivity() with Chooser asking ju

2019-02-13 06:51发布

When you do startActivity() with chooser, Android would list all apps entitled to handle your Intent along with options to set this assignment permanent or once-time (on ICS its "Always" and "Just once" action button, on 2.x it's checkbox). However for this code:

public class Redirector {
    public static void showActivityWithChooser( Context context, int chooserLabelTitleId, Intent intent ) {
      try {
        context.startActivity( Intent.createChooser( intent, 
                     context.getResources().getString( chooserLabelTitleId )) );
      } catch( Exception e ) {
        e.printStackTrace();
      }
    }

    public static void viewInExternalApplication( Context context, String url ) {
      Intent intent = new Intent(   Intent.ACTION_VIEW );
      intent.setData( Uri.parse( url ) );
      intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET );
      showActivityWithChooser( context, R.string.open_chooser_title, intent );
    }
}

I see no "Always|Just once" buttons and cannot make my selection permanent (I got apps listed only and can fire any by tapping it). What elementary I overlooked that made Android unable to make user choice persistent?

See the pics: left dialog is what I'd like to see, but right is what I get now (different number of applications in both dialogs is irrelevant):

enter image description here

1条回答
乱世女痞
2楼-- · 2019-02-13 07:12

For a record - it was over-interpretation type of bug (of mine). The chooser I was using is exactly what can be seen on the image on the right side. And it was showing up all the time because... I was calling it all the time. I incorrectly assumed that chooser offers "Always|Just once" functionality and would not show up if user tapped "Always" (and will show up if s/he used "Just once"). But it is wrong. Chooser will always show up because that's its role - to let user choose. The "Always|Just once" functionality is different thing - it is feature of the Android framework for startActivity()and startActivityForResult() calls, and will show up automatically when needed - if there's more than one app (or precisely, more than one matching intent-filter) that can handle certain Intent. It will not show up if you got just one (or user previously tapped "Always"). You, as developer do not need to care.

So to fix this, I just changed my viewInExternalApplication() code to make it just call startActivity():

try {
  context.startActivity( intent );
} catch (.... )

and let the framework do the rest.

查看更多
登录 后发表回答