Pergunta

I have two apps, which I will refer to as app A and app B. App B is a single task app and normally, if you start this app from the Home screen and use the Back button, you will not be allowed to return to the Home screen. Now suppose app A needs to call app B using an Intent. If the user then uses the Back button in app B, I really do want them to return to app A. But since I am overriding the Back button, it is not possible to return to app A using the Back button.

How can I return to app A but make sure app B remains running if it was running when app A called it? If app B was not running when app A called it, app B should shutdown (get destroyed) when the Back button is pressed.

I am using Android 2.2

UPDATE:

I tried the following:

  @Override
  public void onBackPressed()
  {
    try
    {
      if (this.returnToClient)
        moveTaskToBack (true);

      this.returnToClient = false;
    }
    catch (Exception ex)
    {
    }
  }

I set returnToClient to true if the activity is launched by a calling app by checking some bundle data that gets passed in.

Now if I press the Back button, app B will move to the background and app A comes to the foreground. Looks good. Now if I press the Home button and then launch app B, app B just picks up where it left off. Also good. Now the bad part. If I do a long press on the Home button to bring up the history list and then tap on the icon for app B, the onNewIntent method gets called exactly the same with and with the same data being passed in as though app A had initiated the activity. So what I am guessing is that Android treats launching an app from the Home screen different than it does from the History list. Why? I have no idea. It seems that the history has to do with whoever launched the activity last and persists the bundle data as part of that history. That is weird and it results in unwanted behavior making app B look like it just got called from app A.

Foi útil?

Solução

Have AppA launch AppB using an Intent with an EXTRA that indicates that it was launched from AppA, something like this:

Intent intent = new Intent(this, AppB.class);
intent.putExtra("returnToAppA", "true");
startActivity(intent);

Then, when AppB traps the "back" key, it can check if it was launched from AppA and if so, it can return to appA like this:

Intent intent = new Intent(this, AppA.class); // Use the starting
                                              //  (root) Activity of AppA here
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

Setting FLAG_ACTIVITY_NEW_TASK will ensure that a new instance of AppA will not be created, but it will just return to the existing task containing AppA.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top