Domanda

Struggled with an appropriate title on this one. I've encountered and odd/baffling situation which only came to light as I sometimes initialize fields.

In this case, I had a boolean which I initialized to false (I know, redundant... but...)

the app runs fine and prior to exit my boolean is set to true. I watch the log cat to see that onDestroy() has been called.

I then restart the app.

My boolean, whose value I now log in onCreate(), is true.

WTF?

I noted that the activity started with a new PID. And yet, it is bypassing field initializations. Mind you, I have some which are not redundant. So what is going on here?

I then force stopped the app from the settings menu on the device. Restarting the app now shows all as expected, boolean = false.

So is onDestroy() not a reliable/real termination? I don't recall ever reading anything like that.

This is not my app but is an example of the situation:

public class MyActivity extends Activity {
/**
 * Called when the activity is first created.
 */
private static boolean b = false;
private static int i = 1;
private static final String TAG = "junk app";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Log.i(TAG, "==================================================================");
    if(b) Log.i(TAG,"boolean is true");
    if(!b) Log.i(TAG,"boolean is false");
    Log.i(TAG,"The value of i is"+i);
    i++;
    b=!b;

    foo();
}
public void foo() {
    finish();
}

@Override
public void onResume() {
    Log.i(TAG,"onResume");
    super.onResume();
}

@Override
public void onStop() {
    Log.i(TAG,"onStop");
    super.onStop();
}
@Override
public void onDestroy() {
    Log.i(TAG,"onDestroy");
    super.onDestroy();
}

}

Run this app on a device and watch your logcat. onDestroy() is called. Now start the app again from its icon. i is incremented and b becomes !b.

IDK but my (naive) expectation is that if an app is destroyed, if it is restarted it starts fresh and all initializations, etc are done again.

È stato utile?

Soluzione

Statics are statics -- they are global to the process. So their value will last for the lifetime of the process, which is usually much longer than an individual activity instance.

Source: https://groups.google.com/forum/#!topic/android-developers/PZXbCXliRbo

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top