Fragments and Notifications: Target different Activities from Notification; depending on screen configuration

前端 未结 3 1516
攒了一身酷
攒了一身酷 2021-02-07 21:28

Question:

How to decide what Activity a Notification should launch if the target might depend on the configuration (screen size, orientation

3条回答
  •  情歌与酒
    2021-02-07 21:43

    The no-UI Activity approach mentioned in the accepted answer is what I decided on. I tried another option, but it did not work out. What I tried was this:

    1. In the Service, build an Intent stack with the Intent for NewsReaderActivity at the bottom of the stack and that for ArticleActivity at the top.
    2. Use PendingIntent.getActivities() and pass in the stack as created in Step1 to obtain PendingIntent representing the full stack.
    3. In ArticleActivity, we have the following code:

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          //...
          //...
          // If we are in two-pane layout mode, this activity is no longer necessary
          if (getResources().getBoolean(R.bool.has_two_panes)) {
              finish();
              return;
          }
      
          //...
          //...
      }
      

    So, you first target ArticleActivity - which does a sort of self-introspection to decide if it is useful in the current configuration. If not, it simply moves out of the way with finish(). Since the NewsReaderActivity is already present "before" ArticleActivity in the back-stack, this takes you to NewsReaderActivity.

    This seemed the perfect solution - except for one point which I had overlooked: PendingIntent.getActivities() only works with API 11 or above. There is a rough equivalent in the support library: TaskStackBuilder. One can go on adding Intents to the stack with addNextIntent(), and finally call getPendingIntent() to achieve something similar to PendingIntent.getActivities() (I assume).

    However, on pre-HC devices, this will result in only the top-most Activity from the stack being started in a new task (emphasis mine):

    On devices running Android 3.0 or newer, calls to the startActivities() method or sending the PendingIntent generated by getPendingIntent(int, int) will construct the synthetic back stack as prescribed. On devices running older versions of the platform, these same calls will invoke the topmost activity in the supplied stack, ignoring the rest of the synthetic stack and allowing the back key to navigate back to the previous task.

    So on pre-HC devices, pressing back from ArticleActivity will still take you back to the task that was running prior to ours. This is not what we want.

    I will probably share my project sometime soon. I was also concerned about starting fresh tasks even when I was doing intra-app notifications (for example, a "new news article" notification while I am reading an article). I'll hopefully post that as a separate question.

提交回复
热议问题