Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

android - How to know when my app has been killed?

I need to know when the user kills my app (Force stop). I've been reading the android lifecycle, which has the onStop() and onDestroy() functions, these are related to each activity the user ends on my app, but not when the user forces stop or kills my app.

Is there any way to know when the user kills the app?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have found one way to do this.....

  1. Make one service like this

    public class OnClearFromRecentService extends Service {
    
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.d("ClearFromRecentService", "Service Started");
            return START_NOT_STICKY;
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.d("ClearFromRecentService", "Service Destroyed");
        }
    
        @Override
        public void onTaskRemoved(Intent rootIntent) {
            Log.e("ClearFromRecentService", "END");
            //Code here
            stopSelf();
        }
    }
    
  2. Register this service in Manifest.xml like this

    <service android:name="com.example.OnClearFromRecentService" android:stopWithTask="false" />
    
  3. Then start this service on your splash activity

    startService(new Intent(getBaseContext(), OnClearFromRecentService.class));
    

And now whenever you will clear your app from android recent Then this method onTaskRemoved() will execute.

NOTE: In Android O+ this solution only works when the app is full-time in foreground. After more than 1 minute with the app in background, the OnClearFromRecentService (and all other Services running) will be automatically force-killed by the system so the onTaskRemoved() will not be executed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...