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

前端 未结 3 1634
攒了一身酷
攒了一身酷 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:48

    This is a really good question!

    I think one can safely rule out the possibility of the Service probing for the current configuration to decide what activity to target with the PendingIntent.

    I'd agree that it would be preferable to keep UI decisions at the UI layer, but having the service make the decision would certainly be an expedient choice. You might use a static method on a UI layer class to keep the decision code technically outside of the service (e.g., a static createArticlePendingIntent() method on NewsReaderActivity that the service uses to build its Notification).

    So, how does one decide what activity to launch from a notification, if the activity to launch depends on screen configuration?

    Use a getActivity() PendingIntent for NewsReaderActivity in your Notification, with enough extras that NewsReaderActivity knows that it is in this "show the article" scenario. Before it calls setContentView(), have it determine if ArticleActivity is the right answer. If so, NewsReaderActivity calls startActivity() to launch ArticleActivity, then calls finish() to get rid of itself (or not, if you want BACK from the article to go to NewsReaderActivity).

    Or, use a getActivity() PendingIntent for ICanHazArticleActivity in your Notification. ICanHazArticleActivity has Theme.NoDisplay, so it will not have a UI. It makes the decision of whether to launch NewsReaderActivity or ArticleActivity, calls startActivity() on the right answer, and then calls finish(). The advantage over the previous solution is that there is no brief flash of NewsReaderActivity if the end destination is ArticleActivity.

    Or, use the createArticlePendingIntent() option I mentioned in the first paragraph of my answer.

    There may be other options as well, but those are what come to mind.

提交回复
热议问题