Lucas Arrefelt
Lucas Arrefelt

Reputation: 3929

Different behaviors on back key pressed

I've got four activities which the application cycles through. The first one fetches huge amount of data, so I don't wish to do that more than once. Thing is that if user presses back key on last activity, I want to return to the first one without reloading the activity. I'm currently thinking startActivityForResult methods and finish the two previous ones, but there may be a better solution?

Scenario:

enter image description here

Upvotes: 0

Views: 102

Answers (2)

Fuzzical Logic
Fuzzical Logic

Reputation: 13015

Hasslarn,

The first thing that you must understand is that you have very little choice as to whether an Activity will be reloaded or not. That is determined by the system (largely). With that said, there are a number of things you can do to limit the system's desire to kill the Activity. Additionally, you may use a number of tools at your disposal to limit the impact of such a possible closure

  1. Finish every child Activity as it becomes unimportant. This will free resources lowering the need to get rid of unused Activities (even temporarily).

  2. Find a simple, but clever way to limit loads.

Based on the information provided, your proposed solution is a viable way to accomplish both. However, I would ask "Is Activity B required to be active while Activity C is open?" If not, you may want to do the following:

  1. startActivityForResult(Activity B)

  2. When Activity B is done, send result back to Activity A and startActivityForResult(Activity C)

  3. Finally, when Activity C is done, you may startActivityForResult(Activity D) and back will work with no effort and you won't have to close the other activities.

Furthermore, if you press Back on Activity C, you can supply a cancelled result to Activity A forcing a restart of Activity B if you so desire. Depending on the required processing for Activity B, this may not be any hassle at all for your app.

Regardless of how you approach this, I recommend finding a way to cache this data such that onResume(), you may reload quickly if needed. This is because there is NO way to ensure that your original Activity will not be released to make way for the others.

Hope this helps,

FuzzicalLogic

Upvotes: 2

AndroGeek
AndroGeek

Reputation: 1300

Try using this:

    Intent a = new Intent(this,A.class);
    a.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(a);
    return true;

Activity A will get reordered to front, without creating a new instance. If you want to pass extras through intent , you can get the intent extras in onNewIntent(intent) in Activity A.

Upvotes: 1

Related Questions