开发者

Close activity hierarchy in Android

How do I close a whole hierarchy of activities and show a new activity not present in the current task?

Context

Consider a FTP browser that resumes the previous session on launch. Each folder is displayed in its own activity. When I click on a folder, a new activity is started for the folder. If I press the back button, the app returns to the previous activity, which corresponds to the the parent folder.

I can logoff from the menu at any time. Logging off should bring me to the login activity (not present the current task when the app has resumed the session), and close all the other activities. How开发者_如何学运维 can I do this?

From what I've read, if the activity were in the current task I could use FLAG_ACTIVITY_CLEAR_TOP in the intent, but this is not my case.


One approach can be using startActivityForResult. So for example, your first activity is LoginActivity and subsequent activities are FolderActivity's. So the flow will be
1. LoginActivity (Launcher Activity)
2. Folder Activity (root as the Folder)
3. FolderActivity (clicked folder's contents)... and so on
so now use startAcitivityForResult for starting any new Folder Activity.

 public class LoginActivity extends Activity {
  onCreate() {
  }
  onLogin() {
    startActivityForResult(intent, 100 /*some request code*/); //start Folder Activity,
  }
  @override
  onActivityResult(int requestCode, int resultCode, Intent intent) {
    if(requestCode == 100 && resultCode == LOGOFF_ACTION) {
      //sign out and show the login screen
    }
}

public class FolderActivity extends Activity{ onCreate() { } onClickOnSomeFolder() { startActivityForResult(intent /*with folder details etc*/, 100); } @override onActivityResult(int requestCode, int resultCode, Intent intent) { if(requestCode == 100 && resultCode == LOGOFF_ACTION) { setResult(resultCode, intent); finish(); } else if(requestCode == 100 && resultCode == BACK_BUTTON) { /*No need to finish this activity*/ } } onBackButton(){ setResult(BACK_BUTTON, intent); finish(); } onLogOff(){ setResult(LOGOFF_ACTION, intent); finish(); } }

So now if user choose to sign off using menu then, activities will start finishing in the same order till it reaches the LoginActivity.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜