I have to clear the data from SharedPreference
when the app is cleared from recent list.
Is there any way for that ?
I have to clear the data from SharedPreference
when the app is cleared from recent list.
Is there any way for that ?
Which activity is called when app removed from recent list in android?
The above link tells you how to enter a callback method on removing app from recent list. You can then update your shared variable in that function.
I don't think so,when the app is cleared from the background the onDestroy() method does not get called most of the times. Hence the app does not get any callback method to do so. If you want to do that then why don't you use some static variable or objects (if that is possible) in application class,depending on the requirement. They will get reinitialized each time the application launches, may be if that can help you.
When an app is cleared from the recent list, the onDestroy() method will be called. So clear your SharedPreference
values when the onDestroy() method will be called.
@Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences.Editor editor = getSharedPreferences("APP", MODE_PRIVATE).edit();
editor.putString("YOUR_DATA_KEY", "").apply(); //data nullified
}
See the lifecycle of an activity in android below:
You could do that using a Service.
Create a Sticky Service:
and override the onTaskRemoved
function to clear your Shared Preferences.
public class CheckAppRemovedService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
//YOUR CODE TO CLEAR SHARED PREFS.
}
}
Start the service when you start your activity.
Intent intent = new Intent(MyActivity.this, CheckAppRemovedService.class);
startService(intent);
As already said, there is no guarantee that you will receive a callback when you app is killed no matter what callback you try to use. However, I'm still wondering why you are using the SharedPreferences
if you do not want that data to be persistent, it's beside the point of this class. That being said, you should handle the data like any other data inside your app.
If you are required to use the SharedPreferences
for some reason, then the proper way to clear it is when you start the application, not when you kill it. This way, you won't have any problems.