简体   繁体   中英

how to maintain session in whole app till the user log-out in android?

I'm developing a simple app in which I want to maintain a session in all the activities until the user logs out. I am new to android so please give me good explanations or webside references or any other stuff for session maintaining.
Thank you.

you can use the Application class in you activity. By extending the Application class you can maintain the state in android throughout the application. It means you can call those variables in the application in all the activity.

public class SampleApplication extends Application {

private static String username;
private static String password;

@Override
public void onCreate() {
super.onCreate();
username="";
password="";
}

public static String getUsername() {
return username;
}

   public static void setUsername(String username) {
   SampleApplication.username = username;
}

public static String getPassword() {
    return password;
}

public static void setPassword(String password) {
    SampleApplication.password = password;
}


}

by using this code you can set and get the username and password in any activity. And maintain the state of your username and password. Just you need to add the class name in the manifest.xml like this way.

<application 
android:name=".SampleApplication"
android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SampleApp"
          android:label="@string/app_name"
          >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

You can access you application variables with static getters and setters from any activity or service. :

SampleApplication.setUsername("");
String currentUserName=SampleApplication.getUsername();
SampleApplication.setPassword("");
String currentPassword=SampleApplication.getPassword();

Hope you get your answer by this sample.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM