如何保持android应用程序始终处于登录状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12744337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to keep android applications always be logged in state?
提问by Rohith
Right now I am trying to create one Android application, assume it is going to be some "X" concept okay. So I am creating one login screen. What I want to do is at once if I logged in that application on my mobile, it should always be logged in whenever I try to access that application.
现在我正在尝试创建一个 Android 应用程序,假设它将是一些“X”概念。所以我正在创建一个登录屏幕。我想要做的是,如果我在我的手机上登录该应用程序,那么每当我尝试访问该应用程序时,它都应该始终登录。
For example our Facebook, g-mail and yahoo etc.. in our mobile phones
例如我们手机中的 Facebook、g-mail 和 yahoo 等
What to do for that?
为此该怎么办?
回答by Chirag
Use Shared Preference for auto login functionality. When users log in to your application, store the login status into sharedPreference and clear sharedPreference when users log out.
使用共享首选项实现自动登录功能。当用户登录您的应用程序时,将登录状态存储到 sharedPreference 并在用户注销时清除 sharedPreference。
Check every time when the user enters into the application if user status from shared Preference is true then no need to log in again otherwise direct to the login page.
每次用户进入应用程序时检查,如果来自共享首选项的用户状态为真,则无需再次登录,否则直接进入登录页面。
To achieve this first create a class, in this class you need to write all the function regarding the get and set value in the sharedpreference. Please look at this below Code.
为了实现这一点,首先创建一个类,在这个类中,您需要在 sharedpreference 中编写有关获取和设置值的所有函数。请看下面的代码。
public class SaveSharedPreference
{
static final String PREF_USER_NAME= "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
public static String getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
}
Now in the main activity (The "Activity" where users will be redirected when logged in) first check
现在在主要活动中(登录时将重定向用户的“活动”)首先检查
if(SaveSharedPreference.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.
在登录活动中,如果用户登录成功,则使用 setUserName() 函数设置用户名。
回答by LINTUism
You may add the following for logout operation in your SaveSharedPreference.java :
您可以在 SaveSharedPreference.java 中为注销操作添加以下内容:
public static void clearUserName(Context ctx)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.clear(); //clear all stored data
editor.commit();
}
回答by Peter
Always and whenever ... so this seems like an automated login approach. The application starts, the user doesn't have to login again once he has provided his authorization information. There are several ways to achieve this. The Facebook API e.g. provides mechanism for login without the use of a form element. So you would basically have to construct a view in which the user can provide his authorization information once, store them in SharedPreferences and login automatically the next time. Even if there is no such API - based login and you have to use a login - form provided, you sometimes could simulate the POST - request for logging in. This depends on the actual server - side implementation of that form. But remember: This is an security issue. So never store authorization credentials in clear text format. Don't rely on crypting it by a defined key in your application as this key maybe detected by reverse engineering your APK. Instead use many collective informations about the device and a key the user has to enter or is randomly generated and stored by the app.
总是和任何时候......所以这似乎是一种自动登录方法。应用程序启动后,用户在提供授权信息后无需再次登录。有几种方法可以实现这一点。例如,Facebook API 提供了无需使用表单元素的登录机制。因此,您基本上必须构建一个视图,用户可以在其中提供一次授权信息,将它们存储在 SharedPreferences 中,并在下次自动登录。即使没有这种基于 API 的登录并且您必须使用提供的登录表单,您有时也可以模拟 POST 请求登录。这取决于该表单的实际服务器端实现。但请记住:这是一个安全问题。所以永远不要以明文格式存储授权凭证。大学教师' 不要依赖于通过应用程序中定义的密钥对其进行加密,因为该密钥可能会通过对您的 APK 进行逆向工程来检测到。而是使用有关设备的许多集体信息以及用户必须输入或由应用程序随机生成和存储的密钥。
回答by Edwinfad
Using SharedPreferences is a way to save and retrieve key-value pair data in Android and also to keep the session throughout the entire application.
使用 SharedPreferences 是一种在 Android 中保存和检索键值对数据以及在整个应用程序中保持会话的方法。
To work with SharedPreferences you need to take the following steps:
要使用 SharedPreferences,您需要执行以下步骤:
- Initialization of the share SharedPreferences interface by passing two arguments to the constructor (String and integer)
- 通过向构造函数(字符串和整数)传递两个参数来初始化共享 SharedPreferences 接口
// Sharedpref file name
private static final String PREF_NAME = "PreName";
// Shared pref mode
int PRIVATE_MODE = 0;
//Initialising the SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
- Using Editor interface and its methods to modify the SharedPreferences values and for storing data for future retrieval
- 使用 Editor 接口及其方法来修改 SharedPreferences 值并存储数据以备将来检索
//Initialising the Editor
Editor editor = pref.edit();
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
- Retrieving Data
- 检索数据
Data can be retrieved from saved preferences by calling getString() (For string) method. Remember this method should be called on Shared Preferences and not on Editor.
可以通过调用 getString()(对于字符串)方法从保存的首选项中检索数据。请记住,此方法应在共享首选项上调用,而不是在编辑器上调用。
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
- Finally, clearing / deleting data like in the case of logout
- 最后,像注销一样清除/删除数据
If you want to delete from shared preferences you can call remove(“key_name”) to delete that particular value. If you want to delete all the data, call clear()
如果您想从共享首选项中删除,您可以调用 remove(“key_name”) 来删除该特定值。如果要删除所有数据,请调用 clear()
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
Following will clear all the data from shared preferences
editor.clear();
editor.commit(); // commit changes
Please follow the link below to download a simple and straightforward example: http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
请按照以下链接下载一个简单明了的示例:http: //www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
I hope I haven't gone against the rules and regulations of the platform for sharing this link.
我希望我没有违反分享这个链接的平台的规则和规定。
//This is my SharedPreferences Class
import java.util.HashMap;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class SessionManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
// Constructor
@SuppressLint("CommitPrefEdits")
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
*/
public void createLoginSession(String name, String email) {
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, name);
// Storing email in pref
editor.putString(KEY_EMAIL, email);
// commit changes
editor.commit();
}
/**
* Check login method wil check user login status If false it will redirect
* user to login page Else won't do anything
*/
public void checkLogin() {
// Check login status
if (!this.isLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
*/
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
checkLogin();
}
/**
* Quick check for login
**/
// Get Login State
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
}
Finally, you will have to create an instance of this SessionManager class in the onCreate method of your activity class and then call the createLoginSession for the session that will be used throughout the entire session
最后,您必须在活动类的 onCreate 方法中创建此 SessionManager 类的实例,然后为将在整个会话中使用的会话调用 createLoginSession
// Session Manager Class
SessionManager session;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Session Manager
session = new SessionManager(getApplicationContext());
session.createLoginSession("Username", intentValue);
}
I hope it helps.
我希望它有帮助。
回答by Daniel Wu
I am surprised no answer mentions AccountManager. It is the official and correct way to find out if your user is really who he/she claimed to be. In order to use it, you have to get permission by adding this in your manifest file :
我很惊讶没有答案提到AccountManager。这是确定您的用户是否真的是他/她声称的身份的官方且正确的方法。为了使用它,您必须通过在清单文件中添加以下内容来获得许可:
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Then you get an array of Accounts using this (in case you want user to use his/her Google account) :
然后你使用这个获得一系列帐户(如果你希望用户使用他/她的 Google 帐户):
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccountsByType("com.google");
Full reference here : AccountManager
完整参考:AccountManager
回答by Deepak Swami
after login when you press back call moveTaskToBack(true);
登录后按回电话 moveTaskToBack(true);
from this your application will be in background state. hope help
从此您的应用程序将处于后台状态。希望帮助
回答by Mehdi Dehghani
Xamarin.Android
port of Chirag Raval's and LINTUism's answers:
Xamarin.Android
Chirag Raval和LINTUism的答案的端口:
public class SharedPreference
{
static ISharedPreferences get(Context ctx)
{
return PreferenceManager.GetDefaultSharedPreferences(ctx);
}
public static void SetUsername(Context ctx, string username)
{
var editor = get(ctx).Edit();
editor.PutString("USERNAME", username);
editor.Commit();
}
public static string GetUsername(Context ctx)
{
return get(ctx).GetString("USERNAME", "");
}
public static void Clear(Context ctx)
{
var editor = get(ctx).Edit();
editor.Clear();
editor.Commit();
}
}
回答by Syed Sadman
Just wanted to post another solution that I found the easiest for me:
只是想发布另一个我发现对我来说最简单的解决方案:
SharedPreferences sharedpreferences;
int autoSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//"autoLogin" is a unique string to identify the instance of this shared preference
sharedpreferences = getSharedPreferences("autoLogin", Context.MODE_PRIVATE);
int j = sharedpreferences.getInt("key", 0);
//Default is 0 so autologin is disabled
if(j > 0){
Intent activity = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(activity);
}
}
public void loginBtn(View view){
//Once you click login, it will add 1 to shredPreference which will allow autologin in onCreate
autoSave = 1;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("key", autoSave);
editor.apply();
}
Now let's suppose I have a sign out button in another activity:
现在让我们假设我在另一个活动中有一个退出按钮:
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//Get that instance saved in the previous activity
sharedPreferences = getSharedPreferences("autoLogin", Context.MODE_PRIVATE);
}
@Override
public void signOut(View view) {
//Resetting value to 0 so autologin is disabled
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("key", 0);
editor.apply();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
回答by Naresh J
Firstly after successful login, save username/email and password in SharedPreferences
.
首先登录成功后,将用户名/邮箱和密码保存在SharedPreferences
.
Whenever application will start, execute code which will retrieve the username and password from sharedPrefernces and then these two values can be passed as a parameter to a method which will authenticate the user.
每当应用程序启动时,执行将从 sharedPrefernces 检索用户名和密码的代码,然后这两个值可以作为参数传递给将验证用户的方法。