Android Activity Handling (Resume/Restart) - android

I hope you can help me understanding the Android Lifecycle and how I can manage navigation between several kinds if activities. Suppose the following scenario:
Activity A "MainMenu" is started: User clicks on a menuentry
Activity B is started and UI is loaded with content from local database
user interacts with Activity B
user presses Backbutton and returns to Activity A
user presses again the same menuentry for returning to activity B
At the moment: The activity is loaded from scratch
Whished: The previous instance of Activity B with all its UI entries and User interactions should resume
I thought of saving all activities in a static manager. If a activity is started, the manager looks if it has already been started previously. If so, resume the previous activity else startActivity(ActivityA). Is that a good way of handling those navigations? How can I directly resume via code an instance of an activity?
Or is there another way to do this in a better way?
Thanks in advance!
greetings,
faiko

Your not going to be able to "cache" an activity once its off the stack. Activities are very quick to start, Im guessing its your database stuff that is slowing you down. That you could do something about.
In theory, if you knew the user was going to click on entries multiple times going from A -> B, you might want to just load the DB stuff into memory in Activity A, and then send it via Parcel into B. Then when you go back to A, its still in memory, and it will be to go back to B instantly.
If you are unsure of whether this is true, try debugging it and stepping through. You will see the activity is launched fairly quickly, but you need to identify which operations are lagging. From your description above it is probably your database calls, but it could be other things like network calls, or other long standing calls

The life cycle of android activities makes it not possible to start a new intent but keep the old state.
You should save the state of the activity by saving the fields and restore it to this state when needed.

You cannot resume an instance of an activity in the scenario that you have posted. Because due to the android lifecycle, when you press the back button on activity B that activity is destroyed, with all its states and information.
One option to get the information to persist is to extend the Application class and save the information into some variables inside the application class. Although alot of what you do even then can be garbage collected if the system needs the memory. I dont believe there is any good way to have that information persist through the activities even using Jameo's solution, if activity A is killed then if you return to Activity A from activity B then that activity is reloaded and the database access has to happen again.

Related

Save data into Android SQLite Database when app is killed

I am troubled by the following issue in my Android Application (Java).
I have 3 activities, let's assume A, B and C.
The Activity A has two buttons : New Game and Resume Last Game.
The New Game button leads to Activity B, where the user enters some data, and from Activity B we go to Activity C.
The Resume Last Game button can directly lead to Activity C by reading the appropriate data from the database, if Activity C was killed in the middle of the game.
My problem is that I don't know to handle the code in Activity C, when the whole app is killed by swiping, so exactly at that moment I can populate my database.
As far as I've tried, onDestroy() method is not called at that moment.
Any ideas?
Thanks in advance!
You have to use the activities life cycle, and I do recommend you to do handle it at the onDestroy() method. You can check the next link for more info.
https://developer.android.com/guide/components/activities/activity-lifecycle

Android : Back Button and activity lifecycle

I'm having a hard time managing a back button in my app. If I'm not mistaken, the back button default function should return the user to their previous activity. But when I'm changing from one activity to another I call finish() in the listener. Because of the killed previous activity, pressing back button causes the app to exit.
Is there any way to preserve the previous activity and kill it only after the current activity has changed?
BTW, I know how to override the back button. But if I have a lot of activities, is it efficient to write an override for every activity that doesn't have previous acvitity already killed? I'm developing an RPG and I'm pretty sure there will be a lot of activities.
You're setting yourself up for a really bad time. You want to use as few activities as possible. In a game you really don't want to manage all of that data going back and forward between * amount of activities.
You need models to manage the game data, and your view activity can receive this data from a view controller. You don't want to kill you main view activity and you don't want to keep a bunch of activities in memory. Read a few chapters from this book. Good luck!
http://danielrparente.files.wordpress.com/2013/01/rpg_design_patterns_9_26_05.pdf

onBackPressed - avoid destroying activity

I have two activities - activity A starts activity B. Then activity B loads some stuff from database, and visualizes the data. It takes some time (5-10sec) to fully initialize all the stuff in B.
My problem is that if I press back button in B, it destroys B activity (calls onDestroy) and returns to activity A. I still want to return to activity A, but without destroying B, because if I launch B again, I have to wait again before it does all the stuff (which is annoying). Is this possible somehow?
Thanks for your help!
You can use Fragments, but what you really want to do is cache the information. Otherwise you'll reload on device rotation anyways (unless you use Fragments and setRetainInstance to true, but this can cause other headaches).
I would use a CursorLoader on Activity B's onCreate. onLoadFinished you cache the result and setup your UI. On subsequent loads the results are cached and you forego the loader. What's more, using the CursorLoader will alert you if the underlying database results change.
I think you do not see the problem from the right point of view.
I'd say that you can't prevent B to be destroyed if Android wants to (because it's up to it to handle the activities).
However, you have the choice to move all the long initialisation in a third class which can be persisted all the time. So you should make this init phase independant from your B activity.
I think that putting all this in an attribute of your Application class would be a good idea.
Maybe you can use AndroidFragments
Use SharedPreferences to store key-value pairs then use getSharedPreferences() to retrieve them.
When you press back button Activity b is destroyed. It is how android works. I would not try to override the default functionality
Once you get data from data base you can cache then some where and load it.
http://developer.android.com/guide/topics/data/data-storage.html. Check the topic under Saving cache files.

Pausing/Resuming Activity outside of an activity

I have 2 activities. Main Activity A & Activity B
I do not want Activity A to destroy. I am starting Activity B in a new task.
public static void startActivity(Class<?> startClass) {
Intent intent = new Intent(Constants.getActivity(), startClass);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Constants.getActivity().startActivity(intent);
}`
Constants.getActivity() returns the Context on current activity
startClass is the either activity "A" or activity "B"
Thing is they create/destroy the activities and they leak. Am I doing it wrong? How can I start activity "B" from activity "A" and vice versa keep them both in background when I dont need them.
First of all, what are you trying to do? You should always separate things you want to do in the background from your UI. Think of your Activities are simply a container to show the UI, everything else can be stored and restored from persistent storage or savedinstance bundles.
It is very crucial that you understand the difference between Activity lifecycle and Service lifecycle here.
I'm going to refer to my answer from another question here:
Your app will be in the background, onResume and onPause will both be called, provided that the OS have enough memory to keep the new app and all the old apps.
If you have a long running process that you need while the user not looking at it, use a service.
If you need the user to return the app in the same state, you need to do the work in onResume and onPause to save the state information and initialize your UI again when the user comes back. If you are really worried that it can get killed (well, it shouldn't lose the bundle I think), you can store them in SharePreferences for your app.
If you want to know when the app returns from that specific share intent, use startActivityForResult
You cannot keep an activity "alive" as you said. When an activity is paused, Android system is always able to claim its memory and unload it, at any time.
But if you want to switch from A to B, then maybe A and B can be different views inside a single activity. Maybe you'll want to have a look at http://developer.android.com/reference/android/widget/ViewFlipper.html
When you use tasks, cleanup is very important. You need to cleanup all tasks in the activity. readthis
If the activity does not have a lot of crazy initialization, just use finish and onCreates. Else be aware that onResume will be called often as you switch between activity's. Cleanup will be crucial here. If you dont cleanup, its possible one of your activities (with dead object reference from the other cleaned up activity) may come back up from the activity stack and throw exceptions. Its very difficult to debug this kinda exception.

does object die navigating between activities?

I have an application that navigates to the same activity but each time the activity loads with different parameters. In my application it's a parsed data content retrieved from url. First thing I want to ask: When I push the backbutton of my device I get my earlier activity without being recreated. Is the objects in this activities alive and can I reference them?
Second question is if my first question doesn't make sense, what do you advice me to do?
If you look at the Activity life cycle, you'll notice that as long as your phone has enough memory, your first activity is kept in memory, and with it any member with the data it contains.
But if your phone needs to have some memory, it can kill any activity kept in background (any activity but the one being shown to the user), which means that you'll loose any data that was in your first activity.
To know which happened, keep in mind that the onResume() method will always be called when your activity is brought to foreground (either on creation, or when you navigate back to it), but onCreate() will be called only when your application is created from scratch (meaning you don't have any saved data).
You should use the bundle mechanism to save data when your activity is paused, and load it when you come back to it. Read the paragraph about Saving Activity state in Android doc to see how to use this.
You are not guaranteed that in memory data will be around once you leave an Activity. Read through this part of the dev guide thoroughly to understand the lifecycle of an Activity: http://developer.android.com/guide/topics/fundamentals/activities.html
If you need to persist information, you should override the onPause, onStop, and/or onDestroy methods of your Activity. You can then save your state using SharedPreferences, the SQLite database, or even a flat file.
In the manifest file add the following to the activity:
android:launchMode="singleTop"
In your example what is happening is when you navigate back to the activity using the back button you are bringing up the activity from the stack. When you navigate to the activity inside of the app what is happening is a NEW activity is being created, while the original is still on the stack. The singleTop launch mode will pop the activity out of the stack if it is there when you navigate to it in the app, and only create a new activity if it is not on the stack.
Without singleTop each time you launch the activity in the app it will create a new instance and you will find there are times you have to hit the back button on the same activity more than once due to multiple instances.

Categories

Resources