0

This method is in Mainactivity.class. I want this method to be called when application destroys

   @Override
    protected void onDestroy() {

        if (singleQuestion.size() > 0) {
            LastQuestionService.answerLastQuestion(context, singleQuestion.get(0));
        }

        super.onDestroy();

        MyLog.e(TAG, "onDestroy");
}
Zhi Kai
  • 1,549
  • 1
  • 13
  • 31

3 Answers3

0

It automatically calls when an activity is destroyed. For example when you press back button, the activity will be destroyed and onDestroy() method will be called. But what if you press, Home or Menu butoon, then onDestory() method will not be called, rather onPause() method will be called. So to check that, override OnUserLeaveHint(), it will be called in that case.

Tanay Mondal
  • 147
  • 2
  • 9
  • if the user press HOME button and then clear Applications running in background, the application will destroy. – Dhanraj Naik Oct 12 '16 at 06:56
  • i want to start service on application destroy and not on activity destroy as onDestroy() method is not always called from activity – Dhanraj Naik Oct 12 '16 at 06:57
  • When your user force kill the application like what you mentioned, i don't think your app will be notified as there will be no callbacks due to the entire process being killed. – Zhi Kai Oct 12 '16 at 07:00
  • It do call onDestroy() method when i kill application but the method is not always called (i checked this by putting Log in onDestroy method) . – Dhanraj Naik Oct 12 '16 at 07:03
  • okay, in that case, ill start a service when the app starts. Make a singleton approach for the application context. Run a timer task in that service & check if that appContext is null or not. If it is null means the app is destroyed, start the service you wanted & stop that timertask service. – Tanay Mondal Oct 12 '16 at 07:08
0

Perhaps you could try putting it within finish() instead. It will eventually call onPause() > onStop() follow by onDestroy(). Using finish() kills the activity and releases the memory, so you could effectively say that your application is killed since I supposed you will press the back button to close the app.

Note that finish() may not necessary call onDestroy() due to multiple reasons. Read this up for more info Android: Will finish() ALWAYS call onDestroy()?

Community
  • 1
  • 1
Zhi Kai
  • 1,549
  • 1
  • 13
  • 31
0

Imo, the problem is about both energy consuming issue and context values. Possible solutions:

  1. May be singleQuestion.size() > 0 is false? :)
  2. Use either getApplicationContext() or getBaseContext() instead of context.
  3. Call broadcast event into WakefulBroadcastReceiver url which launches your own service
  4. Use startForeground notification inside your Service to prevent your process to be killed. url
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194