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?
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:
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.
来源:https://stackoverflow.com/questions/20943636/ondestroy-not-getting-called-while-the-activity-is-getting-killed-by-the-user