如何启动应用程序启动时最后打开的activity?

How to start the activity that is last opened when launch an application?

我设计了一个包含多个活动的应用程序。任何时候返回堆栈中都只有一个 activity 实例。当我从名为 AcitivityOne 的 activity 退出应用程序时,下次如何使用 ActivityOne 启动应用程序?

快速的方法是,在您的 onCreate() 中将那些 flags 放在 setContentView() 之后:

if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { 
    finish(); 
    return; 
} 

您还可以创建一个 SharedPreferences,其中 Activity 最后被打开,如下所示:

将您的 onPause() 修改为:

@Override
protected void onPause() {
  super.onPause();
  SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE);
  Editor editor = prefs.edit();
  editor.putString("lastopened", getClass().getName());
  editor.commit();
}

然后在你的 onCreate() 中再次输入:

Class<?> LastOpened;

    try {
        SharedPreferences prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
        LastOpened= Class.forName(prefs.getString("lastoppened", MainActivity.class.getName()));
    } catch(ClassNotFoundException ex) {
        LastOpened= MainActivity.class;
    }

    startActivity(new Intent(this, LastOpened));

如果没有帮助,看看这个thread