在Android中使用SharedPreferences来保存7天登录状态

LoginManager类包含setLoginStatus和isLoggedIn方法,用于设置和检查用户登录状态。setLoginStatus保存用户名和上次登录时间,isLoggedIn判断如果7天内登录过则认为用户在线。
摘要由CSDN通过智能技术生成

先上代码

import android.content.Context;  
import android.content.SharedPreferences;  
import java.util.Date;  
  
public class LoginManager {  
    private static final String PREF_NAME = "login_status";  
    private static final String KEY_USERNAME = "username";  
    private static final String KEY_LAST_ LoginTime = "last_login_time";  
  
    public static void setLoginStatus(Context context, String username, long lastLoginTime) {  
        SharedPreferences.Editor editor = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE).edit();  
        editor.putString(KEY_USERNAME, username);  
        editor.putLong(KEY_LAST_LOGIN_TIME, lastLoginTime);  
        editor.apply();  
    }  
  
    public static boolean isLoggedIn(Context context) {  
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);  
        long lastLoginTime = prefs.getLong(KEY_LAST_LOGIN_TIME, 0);  
        if (new Date().getTime() - lastLoginTime < 7 * 24 * 60 * 60 * 1000) {  
            return true; // 7天内登录过,仍然视为登录状态  
        } else {  
            return false;  
        }  
    }  
}

在上面的示例代码中,我们定义了一个名为LoginManager的类,其中包括两个方法:setLoginStatus()和isLoggedIn()。setLoginStatus()方法用于设置登录状态,包括用户名和上一次登录时间。isLoggedIn()方法用于判断用户是否处于登录状态,如果上一次登录时间距今不足7天,则认为用户仍然处于登录状态。

在setLoginStatus()方法中,我们首先获取SharedPreferences对象,并使用edit()方法创建一个编辑器。然后,我们使用putString()方法和putLong()方法分别保存用户名和上一次登录时间。最后,我们使用apply()方法将编辑操作应用到SharedPreferences对象中。

在isLoggedIn()方法中,我们首先获取SharedPreferences对象,并使用getLong()方法获取上一次登录时间。然后,我们计算出距离上一次登录时间是否不足7天,如果不足,则返回true,否则返回false。

在使用时,我们可以在用户登录成功后调用setLoginStatus()方法来设置登录状态,并在需要判断登录状态的地方调用isLoggedIn()方法来判断用户是否处于登录状态。例如:

String username = "user123";  
long lastLoginTime = new Date().getTime();  
LoginManager.setLoginStatus(context, username, lastLoginTime);  
  
if (LoginManager.isLoggedIn(context)) {  
    // 用户处于登录状态,可以继续使用应用  
} else {  
    // 用户不处于登录状态,需要重新登录或者进行其他处理  
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值