You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android SharedPreferences 登录态持久化与登出跳转异常排查

问题核心错误点
  • 错误1:Authorisation页面初始化逻辑存在严重漏洞:一是is_logged的默认值设为true,首次安装App未登录就会直接跳转主页;二是在登录态判断逻辑的外部无差别执行editor.putBoolean("is_logged", false).apply(),只要页面没被立刻finish就会强制把登录状态改成未登录。
  • 错误2:Menu页退出逻辑完全不符合Android组件规则:直接new Authorisation()创建的Activity实例不受系统生命周期管理,没有绑定有效上下文,调用该实例的log_out()方法根本无法有效修改SharedPreferences里的登录标记,点击退出后登录态实际没有被清除。
  • 错误3:Menu页的菜单选中回调没有判断菜单项ID,点击任意菜单项都会触发跳转逻辑;同时跳转回Authorisation页时,因为SP里的is_logged还是true,Authorisation页初始化会立刻再次跳转回Menu页,表现为点击退出后停留在原页面没有反应。
  • 额外逻辑隐患:登录成功后存储用户名的key使用了变量NAME,没有使用固定字符串key,后续其他页面根本无法稳定读取到存储的用户名。
可直接运行的修复代码

1. 修正Authorisation页初始化逻辑

mSettings = getSharedPreferences("my_storage", Context.MODE_PRIVATE);
editor = mSettings.edit();

// 未登录状态默认值设为false,首次打开停留在登录页
if(mSettings.getBoolean("is_logged", false)){
    startActivity(new Intent(Authorisation.this, Menu.class));
    finish();
}
// 移除原代码中if块外的 editor.putBoolean("is_logged", false).apply(); 无效错误逻辑

2. 修正登录成功后的SP存储逻辑

Boolean checkuserpass = DB.checkusernamepassword(user, pass);
if(checkuserpass){
    Intent intent  = new Intent(getApplicationContext(), Menu.class);
    intent.putExtra("name", user);
    NAME = user;

    // 用固定key存用户名,不要用变量当key
    editor.putString("USER_NAME", user).apply();
    editor.putString("PASSWORD", pass).apply();
    editor.putBoolean("is_logged", true).apply();
    startActivity(intent);
    finish(); // 补充finish,避免登录页留在返回栈
}

3. 修正Menu页退出登录逻辑

@Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();
    // 先匹配退出菜单项的ID,替换成你menu文件中对应item的id
    if (id == R.id.menu_logout) {
        // 直接在当前页面获取SP修改登录态,禁止手动new Activity实例
        SharedPreferences sp = getSharedPreferences("my_storage", Context.MODE_PRIVATE);
        sp.edit().putBoolean("is_logged", false).apply();
        
        Intent intent = new Intent(Menu.this, Authorisation.class);
        startActivity(intent);
        finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
修复后逻辑链路

登录成功时SP标记is_logged=true,后续重启App会直接进Menu页;点击退出按钮时直接在当前Menu页把SP的is_logged改为false,跳转回Authorisation页时判断登录态为false就会停留在登录页,不会出现反复跳转的问题。

内容的提问来源于stack exchange,提问作者S S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 00:03:27