James Dudley
James Dudley

Reputation: 957

Controlling the Application when the Power Button is pressed and returning to the App

I have app that works perfectly fine on my Phone (desire HD). When I press the power button and return to the app the data has not been reset.

A user has sent me a request that when they click the power button (dell streak) and return to the app the data that is being collected is reset.

I am already saving data away in an object if the back button is pressed

How do you go about finding out when the power is pressed to keep the data and what I need call when the user returns to the app

Thanks for your time

Upvotes: 2

Views: 2335

Answers (2)

Dori
Dori

Reputation: 18413

Most likely your activity is being killed whilst in the background. I imagine the Dell Streak is more prone to this as its an older device compared to the HD and probably has less RAM, im not sure how much any Dell customization takes up though (if any).

You probably dont want to be listening for the power button press specifically but rather hooking in the appropriate logic to the Activitys lifecycle methods, especially foccusing on the methods that are called when the activity is created and destroyed as opposed to paused and resumed.

What kind of data is being reset? Is this data being obtained remotly? There are a number of ways to combat this problem.

One is to preserve UI state when the Activity goes is destroyed, see onSaveInstanceState(Bundle)

See here regarding some more info regarding persiting data, which coveres Databases and Shared Prefs which are two alternatives to saving application state (or UI state in some circumstances ) to the onSaveInstanceState() method mentioned above. It really depends on what you are doing :)

Also, are there any remote data gathering operations being triggered in the lifecycle methods (like onCreate()) of this activity? There may be a better architecture for your app if so, say where the lifecycle method just triggers a conditional time-based refresh request thats wrapped in a Service (which is also less likely to be killed in the background) that will just update some model data (in mem or database backed) that the UI can be populated from, but has the advantage that its also persisted so that when your acitvity is killed it will be transparent to the user!

Hope this helps.

EDIT: i just thought, if you are saving state when the back button is pressed and using that saved state to reset the UI state when onResume or onStart is called, are you possibly just clearing the state completely if the activity was put into the background (but not killed) from any other action than pressing the back bytton, as your saved state object will be blank / null / contain default values? If so then the above approaches are still relavent

Upvotes: 3

Joe
Joe

Reputation: 2659

You will probably want to override your activity's onPause() and onResume() methods.

Upvotes: 0

Related Questions