Nick
Nick

Reputation: 3435

android restart app from main activity

My Android app comprises several activities: M (main or root), A, B, C... Below is a possible activity navigation graph:

enter image description here

When my root activity M is being initialized, I cache some parameters (like screen dimensions) as static variables in special class MyUtils to use them later in other activities.

The Kaboom happens when I press Home button in activity say C and then launch a dozen applications. When I return back to my application, it appears that everything has been destroyed. C.onCreate method is being called, but cached parameters appears to be reset.

I would like to start from M, not from C after Android has devastated my application after a long pause. How can I achieve this?

I thought of something like this:

// to be put into all my activities but M:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (MyUtils.GetScreenWidth() == -1)
    {
        // seems like Android killed my app
        finish();
        return;
    }
    // Normal initialization.
    // Use MyUtils.GetScreenWidth() to align my ui elements.
}

...but I'm not sure that it's the best way. What would you suggest?

Upvotes: 1

Views: 979

Answers (3)

Chris Stratton
Chris Stratton

Reputation: 40357

You probably don't want to do things this way unless you require the user to interact with the front-door activity (for example, to authenticate the user again).

If you do want to force them to come back in through that front door activity, you can use an Intent to launch it when you detect that you have started up in a new process with one of the other activities. You will probably want to spend some time reading through the documentation for the Intent flags to select the ones which apply for this usage.

Upvotes: 2

sam
sam

Reputation: 3511

It's not a really smart mean but you could store these information in some other place like a database or simply a file then retrieve it when needed.

Upvotes: 0

John Leehey
John Leehey

Reputation: 22240

To be honest, I would do the same or something similar to what you're doing. A possibly better idea is to have a static MyUtils.initialize() method, perhaps taking in an application context parameter, that is called at each onCreate() of each Activity that uses MyUtils.

Either that, or store the values each in a SharedPreference.

Upvotes: 2

Related Questions