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?
Use
Intent intent = new Intent(SyncActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
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.
精彩评论