7

I need some help in application exit handling. My application has multiple Activity say : - EntryAct, Act1, Act2 .... Act10.

When user presses home key on any of these Activities, I need to do some flag setting.

Handling home key in every application Activity is not possible! Can someone tell how this can be achieved?

Can't change anything in OnPause,OnStop or OnDestory of all activities Act1... Act10. :-(

Black
  • 89
  • 1
  • 2
  • 5

3 Answers3

7

your issue can be solved if you use a custom Application class. say like

public class MyApp extends android.app.Application
{
}

and inside this put your code that you want to be called anywhere in your app.

Now only you require to get the application object in your Activity like this

MyApp app = (MyApp) getApplication();
app.setUpBeforeClosingApp();

and you can put this inside every onDestroy() of Activity and from here code handling before closing actions can be achieved.

Akram
  • 7,548
  • 8
  • 45
  • 72
y ramesh rao
  • 2,954
  • 4
  • 25
  • 39
  • Why not just create a singleton and put the setUpBeforeClosingApp function in there? Since this function is custom, what power does the Application object give in addition to a custom singleton? – Subby Apr 02 '14 at 14:18
  • Keep in mind that OnDestroy is not guaranteed to fire – Bamerza Oct 24 '15 at 20:25
1

Do it in the onPause() method which is called as soon as the activity is no more in the foreground.

WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
1

First of all it is possible to detect the home key event in an indirect way as shown in my post about killing an application when the home key is pressed: How to close Android application?

Also it is possible to determine if an activity is the root activity in its onDestroy() method and then have it call a helper class to perform final processing if it is the root activity. Better yet would be to create a custom activity that all of your activities inherit from, place the final processing logic in the onDestroy() method of the custom activity and then have all subclasses call super.onDestroy() in their onDestroy() method. This is similar to what is done in the aforementioned post: How to close Android application? as well as posts about creating setting screens when the menu button is pressed as well as handling the search button and return button.

I hope this helps.

Community
  • 1
  • 1
Danny Remington - OMS
  • 5,244
  • 4
  • 32
  • 21