Android finish Activity and start another one

别等时光非礼了梦想. 提交于 2019-12-18 04:30:33

问题


I'm curious about one thing. How can I finish my current activity and start another one.

Example :

MainActivity
    --(starts)--> LoginActivity
        --(if success, starts)--> SyncActivity
            --(if success start)--> MainActivity (with updated data).

So I want when SyncActivity starts MainActivity after succesfull sync and if I press back button not to return to SyncActivity or any other activity opened before SynActivity.

I've tried with this code :

Intent intent = new Intent(Synchronization.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
this.finish();

but it's not working properly. Any ideas how to get the things to work properly?


回答1:


Use

Intent intent = new Intent(SyncActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);



回答2:


Judging from your OP, I'm not sure if you absolutely must initialize your mainActivity twice..

Android is designed so that an app is never really closed by the user. Concentrate on overriding the android lifecycle methods such as OnResume and OnPause to save UI data, etc.

Hence, you don't need to explicitly finish() the main activity (and really shouldn't). To receive login or sync data from the previous activities, just override the OnActivityResult() method. However, to do this you must start the activity using startActivityForResult(intent). So for each activity you should do this:

Main activity:

static public int LOGIN_RETURN_CODE = 1;

to start login:

Intent intent = new Intent(MainActivity.this, LogInActivity.class);
startActivityForResult(intent, LOGIN_RETURN_CODE);

to recieve login info:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
      case LOGIN_RETURN_CODE:
        //do something with bundle attached
    }
}

Login activity:

static public int SYNC_RETURN_CODE = 2;

to start sync:

Intent intent = new Intent(LogInActivity.this, SyncActivity.class);
startActivityForResult(intent,SYNC_RETURN_CODE);

to recieve info and return to Main:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
          case MainActivity.SYNC_RETURN_CODE:
            Intent intent = new Intent(...);
            intent.setResult(RESULT_OK);
            finish();
        }
    }

This might not all compile, but hopefully you get the idea.



来源:https://stackoverflow.com/questions/7599955/android-finish-activity-and-start-another-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!