2

I would like to know how i can execute a piece of code when the app closes. My objective is to send a cancel call to the notification so the notification is destroid when the app closes.

Luis
  • 668
  • 1
  • 6
  • 16

2 Answers2

2

Use the Activity onDestroy() method

@Override
public void onDestroy() {
    Log.d("SampleApp", "destroy");
    super.onDestroy();
}
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • Only if the app is killed via TakeManager otherwise is called. – Pedro Lobito Oct 12 '15 at 14:29
  • my app is a music player, in which sometimes the user may close it in the taskmanager – Luis Oct 12 '15 at 14:29
  • You've no way to control that, this means that you cannot execute any code if the user closes the app via TaskManager. – Pedro Lobito Oct 12 '15 at 14:30
  • then thank you for the clarification about the matter – Luis Oct 12 '15 at 14:34
  • I'd be cautious with calling code inside onDestroy(). It's not just the user via the task manager that can kill the app - the OS can kill the app if it runs low on memory. In that case onDestroy() will also not be called. Check out this answer here: http://stackoverflow.com/questions/22210241/how-to-remove-all-notifications-when-an-android-app-activity-or-service-is-kil – vkislicins Oct 12 '15 at 15:00
  • @vkislicins i have found out how to do what i wanted but thank you either way :D – Luis Oct 12 '15 at 21:43
0

I found what i was looking for here , even though the process is not well documented, its a solution .

It basicly consists of creating a service that will execute an action when the the app is killed in the taskmanager.

Used this as an helper to know how to create a service and then used

@Override
public void onTaskRemoved(Intent rootIntent) {
    MainActivity.notification.onCancel();
    stopSelf();
    super.onTaskRemoved(rootIntent);
}

to kill the notification and stop the service when the app was closed in the task manager

Community
  • 1
  • 1
Luis
  • 668
  • 1
  • 6
  • 16