I had recommended that you could use the method onDestroy
, which is called when the system needs memory or when the Finish() method is called. But this might not work in some cases. So, the best thing to do is: you don’t need to wipe the data when the user leaves the app, but when they log in.
For this, we make a SplashActivity
or a class Application
. You can choose any one.
Splahactivity
We will not use any layout in our Splashactivity because it is not necessary. We don’t want the user to waste much time on it, it will be something fast, we will only show the app icon and ready.
<style name="AppTheme.Splash" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowBackground">@mipmap/ic_launcher</item>
</style>
In this style tag, focus on the attribute windowBackground, because he is the one who will position the icon of our app on Splashscreen. You can exchange for a Drawable as well, if you want to make a custom image or leave without any background image.
Don’t forget to define this class on Manifest like the Entrypoint of the application.
public class SplashActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle cycle) {
super.onCreate(cycle);
clearData();
startActivity(new Intent(this, MainActivity.class));
finish();
}
private void clearData() {
SharedPreferences pref = getSharedPreferences("info",MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.commit();
}
}
<activity
android:name="br.com.exemplo.SplashActivity" <!-- muda para o endereço correto -->
android:theme="@style/AppTheme.Splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Application
You will only need to create a class you inherit from Application and then clear the data.
public class MyApp extends Application {
@Override
public void onCreate() {
clearData();
startActivity(new Intent(this, MainActivity.class));
finish();
}
private void clearData() {
SharedPreferences pref = getSharedPreferences("info",MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.commit();
}
}
Don’t forget to point out in the Manifest in the Application tag the name for your Myapp class.
<Application
.....
android:name=".package.MyApp" />
As it was said, in the onDestroy method it gets kind of bad to put because it is not always called.
Try to put your logout logic into ondestroy? If it doesn’t work here is the answer that suggests you create a service to notify when your tasks are destroyed: https://stackoverflow.com/questions/41744933/android-ondestroy-isnt-called-when-i-close-the-app-from-the-recent-apps-button
– Antonio S. Junior