开发者

Start activity from widget & ignore back stack

开发者 https://www.devze.com 2023-04-10 10:48 出处:网络
Let\'s consider simple DB access application with two activities: A - list of entries from DB B - input form to enter new data to DB, with two buttons: Save / Cancel

Let's consider simple DB access application with two activities:

  • A - list of entries from DB
  • B - input form to enter new data to DB, with two buttons: Save / Cancel

Application starts with A (list开发者_Go百科) and from A user may go to B (input form).

To make entering new data more efficient I created a widget to jump directly to B (PendingIntent).

The observed behaviour of the application is like that:

  1. If the first action of the user is widget (empty back stack) => the application opens B and when user click Save or Cancel activity is finished and focus goes back to Android desktop.
  2. If main application was started before (A is on back stack) => B is still properly opened from widget however when user click Save or Cancel focus goes back to A

The behaviour described in 2 is OK when user starts B from A. However I would like to avoid it when B is started from widget.

Any hints ?


I have a situation where I need to do something similar. My quick fix was to add a "EXTRA_LAUNCHED_BY_WIDGET" Extra to the Intent launched by the widget. Then, in my Activity I treat that as a special case.

I needed to override the Back button behaviour, but you could just as easily use this case elsewhere, e.g. in other overridden Activity methods.

  @Override
  public void onBackPressed()
  {
    Bundle extras = getIntent().getExtras();

    boolean launchedFromWidget = false;

    if (extras.containsKey("EXTRA_LAUNCHED_BY_WIDGET"))
    {
      launchedFromWidget = extras.getBoolean("EXTRA_LAUNCHED_BY_WIDGET");
    }

    if (launchedFromWidget)
    {
      // Launched from widget, handle as special case
    }
    else
    {
      // Not launched from widget, handle as normal
    }    
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号