开发者

How to clear stack history?

Consider am having an application containing activity A,B,C. A is launched from the launcher and B is launched from A. B has a button. My requirement is on clicking button on B the present history of the activity Stack A->B should clear and the history stack must contain only C. Is it possible to do ? If so plz a开发者_C百科dvise me...

Thanks in advance !


Although tedious, this can be done by launching using the Activity methods startActivityForResult(), setResult(), finish(), and onActivityResult().

In pseudo-code:

A: startActivityForResult(B)
B: startActivityForResult(C)
C: startActivity(D); setResult(CLEAR); finish()
D: ...
B: (onActivityResult) setResult(CLEAR); finish()
A: (onActivityResult) finish()

If you're willing to change your architecture a bit a more "natural" way to do this is to use FLAG_ACTIVITY_CLEAR_TOP for an easy way to go from A, B, C to just A.

A third way is to set A, B, and C to use noHistory, but then you would lose the ability to back out of C into B or A.


My "solution" is to override behaviour of Back button in activity C, so that it goes to phone launcher, not back the activity stack. This way, activities A and B remain on the back stack, but user has no way to navigate back to them. So the net result is same as if activity C was root activity.

/**
 * Override "Back" key on Android 1.6
 * Don't want user going back to Login or Register forms.
 */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        goHome();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}    

/**
 * Override "Back" key on Android 2.0 and later
 */
@Override
public void onBackPressed() {
    goHome();
}

private void goHome() {
    Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(startMain);    
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜