You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.7 KiB
62 lines
1.7 KiB
package net.micode.notes.tool;
|
|
|
|
import android.content.Context;
|
|
import android.content.SharedPreferences;
|
|
|
|
/**
|
|
* 用户管理工具类,用于管理用户登录状态
|
|
*/
|
|
public class UserManager {
|
|
|
|
private static final String PREF_NAME = "user_prefs";
|
|
private static final String KEY_IS_LOGGED_IN = "is_logged_in";
|
|
private static final String KEY_CURRENT_USER = "current_user";
|
|
|
|
private static UserManager instance;
|
|
private SharedPreferences sharedPreferences;
|
|
|
|
private UserManager(Context context) {
|
|
sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
|
|
}
|
|
|
|
public static synchronized UserManager getInstance(Context context) {
|
|
if (instance == null) {
|
|
instance = new UserManager(context.getApplicationContext());
|
|
}
|
|
return instance;
|
|
}
|
|
|
|
/**
|
|
* 保存登录状态
|
|
*/
|
|
public void saveLoginStatus(String username) {
|
|
sharedPreferences.edit()
|
|
.putBoolean(KEY_IS_LOGGED_IN, true)
|
|
.putString(KEY_CURRENT_USER, username)
|
|
.apply();
|
|
}
|
|
|
|
/**
|
|
* 检查是否已登录
|
|
*/
|
|
public boolean isLoggedIn() {
|
|
return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
|
|
}
|
|
|
|
/**
|
|
* 获取当前用户名
|
|
*/
|
|
public String getCurrentUsername() {
|
|
return sharedPreferences.getString(KEY_CURRENT_USER, "");
|
|
}
|
|
|
|
/**
|
|
* 退出登录,清除登录状态
|
|
*/
|
|
public void logout() {
|
|
sharedPreferences.edit()
|
|
.putBoolean(KEY_IS_LOGGED_IN, false)
|
|
.remove(KEY_CURRENT_USER)
|
|
.apply();
|
|
}
|
|
} |