Search code examples
androidtimeoutsharedpreferences

Android Sharedpreferences Timelimit


In my android application I am using shared preference to remember some inputs so that whenver application get started user don't need to type the input every time.. now I need to logout the sharedpreference if the time of using the app is more than 24 hours.. Like in gmail something our login details will be remembered for 24 hours or something and after tha it will be automatically logout...What change I need to do for that.. I am giving my code below..

SharedPreference for remembering

if (spl1.equals("English")  ) 
            {SharedPreferences setting = this.getSharedPreferences(PREFS_NAME,0);
                    SharedPreferences.Editor editors = setting.edit();
                    editors.putString("lo", "lo");

                    editors.putString("fn", firstName);
                    editors.putString("mn",middleName);
                    editors.putString("ln",lastName);

                    editors.putString("dt",dates);
                    editors.putString("mt",months);
                    editors.putString("yrs",years);
                    //Passing exp no, heart no, lifepath number
                    editors.putLong("name11", sum11);
                    editors.putLong("name12", sum12);
                    editors.putLong("name10", sum10);

                    editors.commit();



                    Intent t = new Intent(FullExplanationEntry.this, TabLayoutActivityh.class);
}

logout

*

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
            if (item.getItemId() == R.id.button04) {
                    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.remove("lo");
                    editor.commit();
                    finish();
            }
            return super.onOptionsItemSelected(item);

}

Solution

  • What you can do is , store the last login time in sharedprefence using :-

    editors.putLong("lastlogin", new Date().getTime());
    

    and when users starts the app next time, get the lastlogin time and check whether its older than 24hrs , if yes then clear the data using :-

    Deleting shared preferences