0

I read that when Android are low on memory, it will kill the activity that is on background.

When returning to application, Android will restore from the top most stack, so when the Activity called other killed Activity that has 'static', it could return null because it hasn't recovered yet.

Question is, how about static final variable ? My understanding is that since it's final, it won't be nulled by Android and keep it's value, even when Android killed the Activity holding it.

The use case is fyi :

Activity A :

private static final String EXTRA_KEY = "key"

void goToB(){
    Intent intent = new Intent(this, B.class);
    intent.putExtra(EXTRA_KEY,"value");
}

Activity B:

void getExtra(){
   getIntent.getExtras(A.EXTRA_KEY);
}

If I'm on Activity B, put the apps on background and Android kill the activities because of memory, is it possible for A.EXTRA_KEY to be null ?

Also is this the recommended way to use EXTRA_KEY as a constant ? Thank you

  • Running low on memory in Android is always a bad thing. Try reading through this article: https://developer.android.com/topic/performance/memory – Lukas Jan 08 '20 at 10:33
  • 1
    Constant expressions are (/may be) inlined by the compiler. So you're not actually using `intent.putExtra(EXTRA_KEY,"value");`, you're actually (/maybe) using `intent.putExtra("key","value");` – Andy Turner Jan 08 '20 at 10:37
  • There is a rumor going 'round that just won't die: That the JVM starts "nulling" references as it experiences memory pressure. This just isn't true. What is happening is, your app is restarting from scratch. Android will restore part of the Activity stack. If any references are null at this point, it's because your code failed to initialize them during the app's latest startup. No JVM can ever change a final reference, of any nature. And as Andy Turner mentioned, it might not even exist as a discrete reference; it may be inlined. – greeble31 Jan 08 '20 at 15:00
  • thanks if it's inlined or defined at compile time than it's probably safe – Wilson Lesley Jan 09 '20 at 03:41

1 Answers1

0

Static variables are tied to the class. And classes rarely get Garbage Collected here's a nice answer. Generally static variables are avoided in android due to the reference issues it can create.

Here's an alternative to keep constant values such as keys, urls etc

At your app gradle file

buildTypes {
    debug {
        buildConfigField "String", "EXTRA_KEY ", "\"key\""
    }
}

retreive it like that

BuildConfig.EXTRA_KEY 
  • 1
    That link you share are pretty useful thanks ! But since my EXTRA_KEY are not just one I think putting in BuildConfig will clutter it too much :( – Wilson Lesley Jan 09 '20 at 03:39
  • as long as you only storing the keys you can have a `public static` class with constant values(keys). This is safe – Stamatis Stiliats Jan 09 '20 at 08:43