如何保持android应用程序始终处于登录状态



现在我正在尝试创建一个Android应用程序,假设它将是一些"X"概念。所以我创建了一个登录屏幕。我想做的是,如果我在手机上登录了该应用程序,那么每当我尝试访问该应用程序时,它都应该始终登录。

例如我们的Facebook、g-mail和雅虎等。在我们的手机中

该怎么办?

使用共享首选项实现自动登录功能。当用户登录到您的应用程序时,将登录状态存储到sharedPreference中,并在用户注销时清除sharedPreferences。

每次用户进入应用程序时都要检查。如果共享首选项中的用户状态为true,则无需再次登录,否则直接登录到登录页面。

为了实现这一点,首先创建一个类,在这个类中,您需要在sharedpreference中编写关于get和set值的所有函数。请看下面的代码。

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, "");
}
}

现在,在主活动(用户登录时将重定向的"活动")中,首先检查

if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0)
{
// call Login Activity
}
else
{
// Stay at the current activity.
}

在登录活动中,如果用户登录成功,则使用setUserName()函数设置UserName。

您可以在SaveSharedPreference.java中添加以下注销操作:

public static void clearUserName(Context ctx) 
{
Editor editor = getSharedPreferences(ctx).edit();
editor.clear(); //clear all stored data
editor.commit();
}

无论何时。。。所以这看起来像是一种自动登录的方法。应用程序启动,用户提供授权信息后就不必再次登录。有几种方法可以实现这一点。例如,Facebook API提供了在不使用表单元素的情况下登录的机制。因此,您基本上必须构建一个视图,用户可以在其中提供一次授权信息,将其存储在SharedPreferences中,并在下次自动登录。即使没有这种基于API的登录,并且您必须使用提供的登录表单,您有时可以模拟POST请求进行登录。这取决于该表单的实际服务器端实现。但请记住:这是一个安全问题。因此,永远不要以明文格式存储授权凭据。不要依赖于通过应用程序中定义的密钥来加密它,因为这个密钥可能是通过反向工程APK检测到的。相反,使用许多关于设备的集体信息和用户必须输入或由应用程序随机生成和存储的密钥。

我很惊讶没有回答提到AccountManager。这是找出你的用户是否真的是他/她声称的人的官方和正确的方法。为了使用它,你必须通过在你的清单文件中添加这个来获得许可:

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

然后你可以使用这个获得一系列帐户(如果你想让用户使用他/她的谷歌帐户):

AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccountsByType("com.google");

此处提供完整参考:AccountManager

我只是想发布另一个我觉得最简单的解决方案:

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();
}

现在让我们假设我在另一个活动中有一个注销按钮:

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);
}

使用SharedPreferences是在Android中保存和检索键值对数据的一种方法,也是在整个应用程序中保持会话的一种方式。

要使用SharedPreferences,您需要采取以下步骤:

  1. 通过向构造函数传递两个参数(String和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
  1. 使用编辑器界面及其方法修改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
  1. 检索数据

可以通过调用getString()(For string)方法从保存的首选项中检索数据。请记住,此方法应在"共享首选项"上调用,而不是在"编辑器"上调用。

// 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
  1. 最后,像在注销的情况下一样清除/删除数据

如果您想从共享首选项中删除,可以调用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

请按照下面的链接下载一个简单明了的示例:http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/

我希望我没有因为分享这个链接而违反平台的规则和规定。

//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);
}
}

最后,您必须在活动类的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);
}

我希望它能有所帮助。

登录后按返回键时调用moveTaskToBack(true);

由此,您的应用程序将处于后台状态。希望能帮助

Chirag RavalLINTUismXamarin.Android端口的答案:

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();
}
}

因此,如果您使用的是Firebase Auth,则不需要SharedPreference,而是可以使用

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){

startActivity(new Intent(LoginActivity.this, DashActivity.class)));
finish();

}

**如果用户登录一次**,将调用此方法

最新更新