Is there a way to define something like a "session" for an android app?
I have an application that launches multiple activities and the user the app going from activity to activity etc.
Of course may switch to another app, take a phone call, stop using the app because he is busy so the app is in the background etc.
Is there an easy and meaningful way to define something like a single session across all these different cases? So that we can tell when a new session starts and possibly store some data for each session?
Mobile apps run on the device (client-side) while Session variables are stored in the server. So the notion of Session variables in the context of mobile doesn't exist. Everytime the device calls the server, it is a different Web Request. So all of the session variables stored before will be lost.
Session help you when want to store user data outside your application, so that when the next time user use your application, you can easily get back his details and perform accordingly. This can be done in many ways. But the most easiest and nicest way of doing this is through Shared Preferences.
SessionManager works with Android MediaRouter on managing session lifecycle. The current session always uses the current selected route (which corresponds to MediaRouter. getSelectedRoute() ). SessionManager listens to route changes from MediaRouter via MediaRouter. addCallback(MediaRouteSelector, MediaRouter.
getUserName(MainActivity. this). length() == 0) { // call Login Activity } else { // Stay at the current activity. } In Login activity if user login successful then set UserName using setUserName() function.
You can use SharedPreferences for that..
SharedPreferences wmbPreference1,wmbPreference2;
SharedPreferences.Editor editor;
//wmbPreference1 for Shared Prefs that lasts forever
wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(this);
//wmbPreference2 for Shared Prefs that lasts only just once each time program is running
wmbPreference2 =getApplicationContext().getSharedPreferences("MYKEY",Activity.MODE_PRIVATE);
To save values
SharedPreferences.Editor editor = wmbPreference1.edit();
editor.putString("MYKEY", "12345");
editor.commit();
You can retrieve the values like
String Phonenumber = wmbPreference1.getString("MYKEY", "");
where MYKEY is the keyname by which you can identify the value..
Unfortunately its up to the developer to define what a 'session' is in Android. Since your activity can be backgrounded for a phone call for a minute and then return to foreground - is that part of the same session or two sessions? How about a gap of 20 minutes? You can store a timestamp but you are responsible for 'expiring' and implementing appropriate behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With