How to get notified when the application is closed in Android

前端 未结 1 507
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 23:03

I want to show up a Notification when my app is removed from the recent apps list.

I\'ve tried putting code for that in onStop() and

相关标签:
1条回答
  • 2020-12-08 23:50

    This answer is outdated and most likely will not work on devices with API level 26+ because of the background service limitations introduced in Oreo.

    Original answer:

    When you swipe an app out of Recents, its task get killed instantly. No lifecycle methods will be called.

    To get notified when this happens, you could start a sticky Service and override its onTaskRemoved() method.

    From the documentation of onTaskRemoved():

    This is called if the service is currently running and the user has removed a task that comes from the service's application.

    For example:

    public class StickyService extends Service {
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            return START_STICKY;
        }
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public void onTaskRemoved(Intent rootIntent) {
            Log.d(getClass().getName(), "App just got removed from Recents!");
        }
    }
    

    Registering it in AndroidManifest.xml:

    <service android:name=".StickyService" />
    

    And starting it (e.g. in onCreate()):

    Intent stickyService = new Intent(this, StickyService.class);
    startService(stickyService);
    
    0 讨论(0)
提交回复
热议问题