user1865027
user1865027

Reputation: 3647

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. there are a few static vars being initialized in 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.

my launchMode for both activities are singleTop. not sure if that matters but I've tried singleTop, singleInstance and standard none of them work. 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.

Thanks!

Upvotes: 0

Views: 84

Answers (3)

Hello World
Hello World

Reputation: 2774

If static variables doesn't work, you can try using getter() and setter() methods for variables.

Upvotes: 0

kevz
kevz

Reputation: 2737

  • I hope those static variables are of primitive datatypes.
  • Even if the Application is in background Android system kills the process after some time.
  • So you can do is pass those primitive variables through Intent to 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.

Pass variable to ActivityB instead of static variable.

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

Now in ActivityB get the passed variable values-

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

Upvotes: 0

Ankit Singh
Ankit Singh

Reputation: 149

the problem may be because when your application is in background the android o.s must have cleaned the memory to free resources for other application

Upvotes: 0

Related Questions