-1

I am working on exam application where user is taking exam. In case user completes 40% exam and moves app to back stack and then removes it from recent tab i want to save the total progress in that case. I tried doing it using ondestory activity but on destory is not called everytime the app is cleared. this is my code for on destroy.

@Override
protected void onDestroy() {
    super.onDestroy();
    Toast.makeText(getApplicationContext(),"On destroy called",Toast.LENGTH_LONG).show();
}

There is a fragment on which the questions are inflated and i tried calling ondestroyview there but it also didn't solved my problem.

 @Override
public void onDestroyView() {
    super.onDestroyView();
    Toast.makeText(getContext(),"On destroy view called",Toast.LENGTH_LONG).show();
}

How can i get the event when the app is removed from the recent tabs. I searched a lot but couldn't find anything.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Vipin NU
  • 301
  • 2
  • 16

2 Answers2

0

If you need event of application being removed from recent list, and do something before stopping service, you can use this:

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

So your service's method onTaskRemoved will be called. (Remember, it won't be called if you set stopWithTask to true).

public class MyService extends Service {

@Override
public void onStartService() {
    //your code
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    System.out.println("onTaskRemoved called");
    super.onTaskRemoved(rootIntent);
    //do something you want
    //stop service
    this.stopSelf();
}
}
Gaurav
  • 171
  • 1
  • 13
0

You need to override

onSaveInstanceState(Bundle savedInstanceState)

and

onRestoreInstanceState(Bundle savedInstanceState)

in-order to store and retrieve status values to/from a bundle.

Rakesh C
  • 41
  • 4
  • Will it work even after i remove app from back stack and open a new instance all over again. – Vipin NU Jun 26 '19 at 07:40
  • @VipinNU yes it will work. You should never try to store any status values in onDestroy() callback. Instead you can save data in onPause() by using Preferences and retrieve data in onResume() if you are saving it in preferences. – Rakesh C Jun 26 '19 at 07:58
  • I will call api and save the data on server when on destroy will be called. Then on page recreate i will fetch the data and show it to user. – Vipin NU Jun 26 '19 at 08:08