简体   繁体   English

静态var被杀死但活动进入前台

[英]android - static var is killed but activity is brought to foreground

let's say I have 2 activities A and B. I go to B from A then hit the Home button. 假设我有2个活动A和B。我从A转到B,然后按“主页”按钮。 there are a few static vars being initialized in A. 有一些静态变量在A中初始化。

after a few hours or days or until activity is being killed, I launch the app again from the Recent button. 几个小时或几天之后,或者直到活动被终止,我从“最近”按钮再次启动该应用程序。 activity B becomes the new entry point of this app, but static vars are no longer holding any value and has no chance of getting initialized unless I redirect back to A. 活动B成为该应用程序的新入口点,但是静态var不再拥有任何值,除非我重定向回A,否则它没有初始化的机会。

my launchMode for both activities are singleTop . launchMode两个活动是singleTop not sure if that matters but I've tried singleTop , singleInstance and standard none of them work. 不知道这是否重要,但是我尝试了singleTopsingleInstancestandard都不起作用。 I guess my expected behavior would be the entry point is always A or any other activities if is not being killed and of course static vars are still holding value. 我想我的预期行为是入口点始终是A或任何其他活动(如果未被杀死),当然静态var仍然保持价值。

Thanks! 谢谢!

问题可能是因为当您的应用程序在后台运行时,Android操作系统必须清除内存才能为其他应用程序释放资源

  • I hope those static variables are of primitive datatypes. 我希望这些static变量属于原始数据类型。
  • Even if the Application is in background Android system kills the process after some time. 即使该应用程序在后台运行,Android系统也会在一段时间后终止该进程。
  • So you can do is pass those primitive variables through Intent to ActivityB . 因此,您可以做的是将这些原始变量通过Intent传递给ActivityB
  • Now if the Application is killed from background and brought it to Foreground same intent is used to launch the ActivityB and you can still get the passed variables. 现在,如果该应用程序从后台被杀死并将其带到前台,则使用相同的意图来启动ActivityB ,您仍然可以获取传递的变量。

Pass variable to ActivityB instead of static variable. 将变量传递给ActivityB而不是静态变量。

Intent intent = new Intent();
intent.putExtras("Id", 1);
intent.putExtras("Name", "kevz");
startActivity(intent, ActivityB.class);

Now in ActivityB get the passed variable values- 现在在ActivityB获取传递的变量值-

int Id = getIntent().getIntExtra("Id", -1); // -1 is default value.
String Name = getIntent().getStringExtra("Name", "unknown"); // unknown is default value

如果静态变量不起作用,则可以尝试对变量使用getter()setter()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM