문제

I have an activity with two tabs. Clicking on two tabs will change the the fragments below the tabs. While that activity is in front I give out a notification, After that I minimize the app and kill that activity(not force stopping).

My problem is that am not getting call back in onDestroy while the activity is been killed by the user. Now if I click the notification the app will force close and thats because the activity for pending intent is been missing. Why am not getting the call back in onDestroy?

도움이 되었습니까?

해결책 3

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top