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.
            Asked
            
        
        
            Active
            
        
            Viewed 125 times
        
    2 Answers
2
            
            
        Use the Activity onDestroy() method
@Override
public void onDestroy() {
    Log.d("SampleApp", "destroy");
    super.onDestroy();
}
        Pedro Lobito
        
- 94,083
 - 31
 - 258
 - 268
 
- 
                    
 - 
                    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
 - 
                    
 - 
                    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
- 
                    Does not work for API level >= 26, see https://stackoverflow.com/a/47110577/1000551 – Vadim Kotov Jan 11 '19 at 15:58