![](/img/trans.png)
[英]How to stop android from restoring state when the app process is killed?
[英]Android - restoring state when process has been killed
我在Android中进行了带有片段的活动,如果我最小化应用程序,并且一段时间后系统终止了该进程,则稍后运行我的应用程序时会崩溃,因为它试图从第二个活动(包含片段的活动)中恢复,即使该进程已被终止,也不是启动程序活动。 它崩溃的原因是,在片段中某些视图使用了Singleton类中的变量,并且当进程被杀死时,所有这些变量都变为空。 因此,我尝试检查承载此类片段的父活动
public class SecondActivity extends FragmentActivity {
FragmentTabsAdapter tabsAdapter;
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Crash", "Second Activity");
if (Commons.INST.someVariableFromTheSingleton == null) {
Intent i = new Intent(this, SplashScreen.class);
// Splash screen is the launcher activity
startActivity(i);
} else {
setContentView(R.layout.activity_second);
tabsAdapter = new FragmentTabsAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(tabsAdapter);
}
}
}
问题是,即使我明确声明要启动启动器活动,当它尝试还原活动时,它仍将继续使用第二个活动生命周期方法。...一旦启动了意图,如何停止它?
考虑将Singled的Application类与SharedPreferences一起使用。 从android文档中
您可以使用SharedPreferences保存任何原始数据:布尔值,浮点数,整数,长型和字符串。 这些数据将在用户会话之间保持不变(即使您的应用程序被终止)。
尝试在startActivity(i)之后调用finish()
SecondActivity活动在AndroidManifest.xml中是否具有意图过滤器MAIN,如下所示
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
如果确实尝试删除此过滤器。
在onCreate()
您想这样做:
Intent i = new Intent(this, SplashScreen.class);
// Splash screen is the launcher activity
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
return;
仅当SplashScreen
仍位于活动堆栈的根目录(即:尚未完成)时,此选项才有效。 如果当前正在启动下一个Activity时在SplashScreen
调用finish()
,则需要将其删除,以便始终将SplashScreen
作为Activity堆栈的根。 为了防止用户按BACK返回到SplashScreen
您应该在SplashScreen
启动下一个Activity时在SplashScreen
设置一个布尔标志,而在SplashScreen.onResume()
则应检查此布尔标志,如果该标志是,请调用finish()
设置(然后将“退出”您的应用程序)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.