Wednesday, January 9, 2013

Logout and Exit from previous activity in android


Mostly of time, We facing a challenge in android when we creating session base application, in which we need to save login credentials through out application and after click on logout need to finish all previous activities those are using session values.
for save login credential in application used SharedPreferences, SQLite database or external file writing in SD card and more info see Android Storage guide
and in case of logout just remove all values from the SharedPreferences and redirect to login screen but when am click back from android mobile button, last activity restore. How prevent this,?
just add some code of lines in onRestart function in activity class at which you want to check session keys,
see below code of lines
@Override
 protected void onRestart() {
  // TODO Auto-generated method stub
  super.onRestart();
  SharedPreferences pref = context.getApplicationContext().getSharedPreferences("samplekey", Context.MODE_PRIVATE);
  if (pref.getString("<login key name>", "").length()==0) {
      finish();  
  }
 }
whenever you click back button from android mobile , every time onRestart method of previous activity/screen class called and checking about session,
if session not exist than it's finish the activity otherwise open that screen/activity

No comments:

Post a Comment