在我的 MainActivity 类中,我有一个启动新 Activity 并终止当前 Activity 的方法:
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
finish();
在新 Activity 中,如果我按下后退按钮,应用程序会按预期最小化/关闭,但是当我重新打开应用程序时,它没有出现在 NewActivity 中,而是返回到 MainActivity!
为什么会这样?
最佳答案
因为当它重新开始时,也就是说,即使在您结束任务之后,它也会启动“Main/Launcher”Activity
。您在 AndroidManifest
中指定它。
<activity android:name=".MainActivity"
...>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
默认情况下,按下后退按钮会结束当前的 Activity
,如果当前任务中不存在其他 Activity
,则已知该任务已经结束。
对此的解决方案是在 SharedPreferences
中保存一些标志或状态,或者以某种方式保留它以再次读取它以将流定向到 NewActivity
。
在您的 MainActivity
中,执行如下操作:
@Override
protected void onCreate(Bundle savedInstanceState) {
if(shouldStartNewActivity()) {
Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
finish();
} else {
super.onCreate(savedInstanceState);
}
}
private boolean shouldStartNewActivity() {
//Your logic to check if NewActivity should be started directly
}
关于android - 重新进入应用程序,它从头开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36563157/