How to handle multiple activity task in android when press home?

195 views Asked by At

I have two activity in my app, A and B. They run in different task. which means A is the startup activity, B has singleTask launchMode and a different taskAffinity.

When I start B from A (A->B), a new task will be created. Here comes my question, when I press home button to push app to background and click the app launch icon to bring to foreground again, what I see is activity A. What should I do to see B when app go to foreground?

1

There are 1 answers

4
Stefan On

EDIT: It ain't pretty but it works. The singletask launchmode blocks the normal way that you get your current activity, so here's a workaround. The only disadvantage is that you would call startActvity again, possibly being visible.

Add this to your AndroidManifest.xml

    <application
    android:name=".DefaultApplication"   // add this line

Add this class to your package

public class DefaultApplication extends Application {

private int curAct;
@Override
public void onCreate() {
    super.onCreate();
    curAct = 0;
}

public int getCurAct() {
    return curAct;
}

public void setCurAct(int curAct) {
    this.curAct = curAct;
}
}

In the onCreate of B, post this line:

   ((DefaultApplication)this.getApplication()).setCurAct(2);

Add this method to A:

   public void onWindowFocusChanged(boolean hasfocus)
{
    if(hasfocus){
        int a = ((DefaultApplication) this.getApplication()).getCurAct();
        if(a == 2)
        {
            startActivity(new Intent(this, BActivity.class));
        }
    }
}

Something I forgot to add, you should add this method to B:

    @Override
public void onBackPressed() {
    super.onBackPressed();
    ((DefaultApplication)this.getApplication()).setCurAct(1);
}