[英]Best way to handle activity state
I'm making an app that shows another activity when I correctly login however in the home screen when I pressed back and then returned to the app the login activity showed. 我正在制作一个应用程序,当我正确登录时该应用程序显示另一个活动,但是当我按下后又返回到登录活动显示的应用程序时,在主屏幕中显示了该活动。
I was able to avoid this overriding the onBackPressed this way: 我能够避免这种方式覆盖onBackPressed:
public void onBackPressed()
moveTaskToBack(true);
}
Is this the best way to do it? 这是最好的方法吗? Is there a more proper way to keep the state of the application when I exit it?
退出应用程序时,还有一种更合适的方法来保持应用程序的状态吗?
In your login activity after starting intent call finish() 在开始意图调用后的登录活动中finish()
finish destroy your activity and avoid to run it again automatically. 完成销毁您的活动,并避免自动再次运行。
Your issue is that you kept LoginActivity in stack. 您的问题是您将LoginActivity保留在堆栈中。 so when you press back it will kill MainActivity(after login) and since LoginAcitivity still there.
因此,当您按回时,它将杀死MainActivity(登录后),并且由于LoginAcitivity仍然存在。 it will be shown again.
它将再次显示。 best is to kill LoginAcitivty after starting new activity.
最好是在开始新活动后杀死LoginAcitivty。
call this in LoginActivity: 在LoginActivity中调用此命令:
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
finish();
As you question I understand, you want to clear the entire history stack and start a new activity. 如您所知,您想清除整个历史记录堆栈并开始新的活动。 For this, in API level 11 a new Intent Flag was added which is: Intent.FLAG_ACTIVITY_CLEAR_TASK
为此,在API级别11中添加了一个新的Intent标志,即: Intent.FLAG_ACTIVITY_CLEAR_TASK
Just to clarify, use this: 只是为了澄清,使用此:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
For API <=10 now one can use IntentCompat class for the same. 对于API <= 10,现在可以使用IntentCompat类。 One can use IntentCompat.FLAG_ACTIVITY_CLEAR_TASK flag to clear task.
可以使用IntentCompat.FLAG_ACTIVITY_CLEAR_TASK标志清除任务。 So you can support pre API level 11 as well.
因此,您也可以支持API之前的11级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.