onDestroy() not getting called while the activity is getting killed by the user?

心已入冬 提交于 2019-12-06 16:55:52

It is not sure to get callback in fragment's onDestroy(). When we kill the app Activity's onDestroy() will get the callback and the activity will be killed and fragment may not get callback.

buxik

I found solution of that:

  1. Create service:

    public class MyService extends Service {
    
        @Override
        public final int onStartCommand(Intent intent, int flags, int startId) {
            return START_STICKY;
        }
    
        @Override
        public final IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public void onTaskRemoved(Intent rootIntent) {
            Toast.makeText(getApplicationContext(), "APP KILLED", Toast.LENGTH_LONG).show(); // here your app is killed by user
    
            try {
                stopService(new Intent(this, this.getClass()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                super.onTaskRemoved(rootIntent);
            } else{}
        }
    }
    

and then start your service when app start:

startService(new Intent(this, MyService.class));

make sure you register service in your AndroidManifest.xml

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

onDestroy is guaranteed to be called when you explicitly call finish().

On the contrary, when you are minimizing your app by pressing Home key onDestroy may well not be called right now. If your app stays in the background for a long time then onDestroy will be called.

For debugging purposes you can enable Settings|Developer Options|Don't save Activities. This way onDestroy will be called immediately when your app goes to background.

As stated jn the documentation, onDestroy() can't be depended on, it will be called when the OS wants to kill the app, say in low memory conditions. Thus when the user hits the back button or home, onPause() or onStop() are called in place of it. Try implementing your callback in thr onPause() or onStop() method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!