how to delete sharedpreference after 60minutes
Asked Answered
S

2

6

I want to store login data but I want that data to be deleted after 60 minutes. What is the proper way to do this?

The app can be closed, stopped, opened in these 60 minutes. I don't want to use an internal database.

Here is my code for accessing SharedPreferences

sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Username, usernameTxt);
editor.putString(Password, passwordTxt);
Spivey answered 10/12, 2015 at 23:35 Comment(0)
A
7

I think the easiest and most direct way to do this is keeping expired date:

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("Username", usernameTxt);
editor.putString("Password", passwordTxt);
editor.putLong("ExpiredDate", System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(60));
editor.apply();

And then check it

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.getLong("ExpiredDate", -1) > System.currentTimeMillis()) {
    // read email and password
} else {
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.clear();
    editor.apply();
}

But, @CommonsWare is right and keeping the information just in your process is more correct.

Autocephalous answered 11/12, 2015 at 1:8 Comment(0)
A
0

Personally, I would not implement it that way. Keep the information just in your process, so that the data goes away when your process does.

That being said, you are welcome to use JobScheduler or AlarmManager to schedule work to be done in the future, regardless of the state of your app at that time.

Antediluvian answered 10/12, 2015 at 23:37 Comment(2)
i checked these two options and I have to say my API limit is 16, and these two are 19 and greater. can't use themSpivey
19 and greater? What? AlarmManager was added in API level 1, the very first version of Android, ever. developer.android.com/reference/android/app/AlarmManager.htmlWintergreen

© 2022 - 2024 — McMap. All rights reserved.