2

The app I am developing should know if the user/android* has cleared cache or clear data , so that I logout the user. How to do this? How to find out if user has cleared cache?

    • Can the android OS clear the cache of an app by itself (without human intervention)?
Samttha Biby
  • 73
  • 11
  • 3
    When, a user clears data, he will be logged out. This is because, all the database, preferences you saved would be deleted and application would seem like a fresh install. As for cache, android can delete cache. Usually, cache should contain data which does not impact the usability of application but rather is used to speed up slow tasks, like instead of downloading an image from network again and again, you can store the image in cache. It wont matter to user, if image was from cache or network. – Kartik Sharma Feb 02 '17 at 05:30

1 Answers1

3

Use SharedPreference to store value in Application cache

SharedPreference prefs = getSharedPreferences("UserInfo", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.commit();

when App started Retrieve data from SharedPreference

 SharedPreference prefs = getSharedPreferences("UserInfo", 0);
 String username = prefs.getString("username","");
 String password = prefs.getString("password","");

if cache is cleared SharedPreference also cleared.so you have to make a condition like if username and password empty means not enter Application.

sasikumar
  • 12,540
  • 3
  • 28
  • 48
  • Got it. But if there in activity X, then go to settings and clearing cache and then coming back to the activityX where they left, should I check for preferences in each activity to log them out? If yes, should I check prefs in each activity or fragment? Wjhich is the best place to do ? – Samttha Biby Feb 02 '17 at 05:54
  • you can check SharedPreference any where in Application with application context , But Before you do this create your SharedPreference in separate class by passing only context. – Chetan Joshi Feb 02 '17 at 05:59
  • Best one is you create extend application class with getter and setter methods .when app is login set status as true .then check all the activity and fragment check it true or not when its oncreate... or use service for checking session. – sasikumar Feb 02 '17 at 05:59
  • @ChetanJoshi If I can check preferences any where in Application, why should I create my SharedPreference in separate class by passing only context? – Samttha Biby Feb 02 '17 at 06:05
  • Because we have to right each time same code in all activities like above code ,So its just for avoiding code redundancy , – Chetan Joshi Feb 02 '17 at 06:20