简体   繁体   English

如何维护整个应用程序中的会话,直到用户在android中注销?

[英]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. 我是android的新手,所以请给我很好的解释或webside参考或任何其他用于会话维护的内容。
Thank you. 谢谢。

you can use the Application class in you activity. 您可以在活动中使用Application类。 By extending the Application class you can maintain the state in android throughout the application. 通过扩展Application类,您可以在整个应用程序中维护android中的状态。 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. 只是您需要像这样将类名添加到manifest.xml中。

<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. 您可以使用来自任何活动或服务的静态getter和setter访问应用程序变量。 :

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

Hope you get your answer by this sample. 希望您通过此示例得到答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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