假设某人正在使用我的应用程序,并且他们处于危急状态,前提是他们正在输入一些数据。同时说电话响了,所以他们接听电话,迫使我的应用程序进入后台。电话结束后,如果他们点击我的应用程序的图标,我希望它将他们带回他们离开的活动。我该怎么做?
修改
我忘了澄清(道歉)的一件事是用户离开的活动不主要活动。我需要在通常不是主要入口点的活动中重新打开应用程序。
答案 0 :(得分:2)
您需要覆盖onSaveInstanceState(Bundle savedInstanceState)并将要保留的状态值保存到Bundle参数,如下所示:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("booleanValue", true);
savedInstanceState.putString("stringValue", "Your String data");
// etc.
}
Bundle是一种在(“名称 - 值对”)映射中存储值的方法,它将被传递到onCreate和onRestoreInstanceState,在那里你可以像这样提取值:
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean booleanValue = savedInstanceState.getBoolean("booleanValue");
String stringValue = savedInstanceState.getString("stringValue");
}
您通常使用此技术存储应用程序的实例值(选择,未保存的文本等)。
现在,您可以使用这些值填充字段。
请检查:http://developer.android.com/training/basics/activity-lifecycle/recreating.html
答案 1 :(得分:-1)
要防止系统启动另一个活动实例,您应该为活动添加launchMode="singleTop"
。
的AndroidManifest.xml
<activity
....
....
android:launchMode="singleTop" />
这将做什么:
当用户尝试启动您的应用时(例如,在通话后),系统会检查您的启动器活动是否已在运行&amp;&amp;在堆栈的顶部。如果是,则不会创建新实例,并且您的活动将恢复。堆栈顶部条件很重要。根据您的要求,您可能希望选择singleTask
启动模式。
此处有更多信息:Link