I use the application interconnected with the service, in the onDestroy method of the application the launch of the service with notification is set.

 @Override public void onDestroy() { if (mediaPlayer.isPlaying()) { Intent i = new Intent(this, MyService.class); i.setAction(Constants.SERVICE.SERVICE_IN_BACKGROUND); startService(i); } super.onDestroy(); } 

That is, if the user minimizes the application, the service starts with a notification, if it expands again, then the notification is closed.

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (notificationManager != null) { notificationManager.cancel(NOTIFICATION_ID); } } 

Faced a problem when an application is minimized, if you clear it from background applications, the notification service lives on, but since it was associated with the application, its functions in the notification do not work. Is there any method that works when an application is completely destroyed? So that I destroy the service with the notification. For example, if I minimized the application and cleared it from the background processes so that the service was also destroyed?

    2 answers 2

    I decided:

    In the manifest file where the service added:

     android:stopWithTask="false" 

     <service android:name=".MyService" android:enabled="true" android:exported="false" android:stopWithTask="false" /> 

    In the service itself created method:

     @Override public void onTaskRemoved(Intent rootIntent) { stopSelf(); } 

      stopService("имя сервиса") tried?

      • Within the normal lifecycle methods, I can call or destroy it, the question is how to destroy in that case or the application is closed in background processes. - McDaggen
      • Refresh my memory, but if the application is called onDestroy in the background? I remember it was called when the activity is killed and if on the background, then onStop - elik
      • If you minimize the application, it enters the states from onPause, onStop, onDestroy. I also thought, I thought if I collapse the onStop and if I completely destroy onDestroy, but no. I have already solved the problem. - McDaggen
      • According to Google documentation, guaranteed to be called only onPause when minimized. And the onStop and onDestroy may not be called at all under certain conditions. - mit