سؤال

I have an Activity A start Activity B in my App. When my App is stopped and the memory of the android system is low, my App will be cleared from the back stack. When I launch my App again, an exception occur during instantiate Activity B. So I want to make sure Activity B is finished when the memory is low, thus the exception will not occur. I have tried putting finish() in onMemoryLow(), but it didn't work. What else can I do?

هل كانت مفيدة؟

المحلول

Android just kills your process if it is in the background. When the user returns to the app, Android recreates the process and recreates the Activity that was on the top of the activity stack. You need to program your activities so that they can run like this (ie: being recreated after a restart). If you can't do this you can try the following:

Create a class with static variable like this:

public class Globals {
    public static boolean initialized;
}

The variable Globals.initialized will have the value false when the process is created (or recreated).

Now, in your ActivityA, when you set up the data that ActivityB relies on, you can set the initialized flag, like this:

Globals.initialized = true;

In ActivityB.onCreate(), check the value of initialized and if it isn't set, just call finish() which will take the user back to ActivityA, like this:

if (!Globals.initialized) {
    finish(); // Process was recreated while ActivityB was on top of the stack,
              //  so finish now
    return;
}

نصائح أخرى

This might not answer your entire question But still it will be helpful.

First thing what you have to note is that, onLowMemory() will be called when your entire Android system is running low on memory. This has nothing to do with your app or activity. So overriding the method will not ensure your Activity will get finished.

Maybe if your Activity is in memory of the Andorid system(i.e Before onDestroy() is called) and if you have overridden the onLowMemory(), then it will help you. But other than that there is no possibility to do it. Else you have to check the required condition before you enter the Activity.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top