Android开发:退出登录时如何清除SharedPreferences?
嘿,针对你的退出登录需求,我给你整理了两种实用的SharedPreferences清除方式,结合你的场景来适配:
方式一:精准移除单个登录相关键值对(推荐)
你登录时只存储了UID这个键,退出时可以只清除它,不会影响其他可能存在的偏好设置。把这段代码加到你的退出登录逻辑里:
// 获取SharedPreferences实例 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(DashBoard.this); SharedPreferences.Editor editor = prefs.edit(); // 移除指定的"UID"键值对 editor.remove("UID"); // 异步提交修改(apply()不会阻塞主线程,适合大多数场景) editor.apply(); // 执行退出跳转逻辑 Intent intent = new Intent(DashBoard.this, Login.class); startActivity(intent); finish();
方式二:清空所有SharedPreferences内容
如果你的SharedPreferences里还存了其他登录相关数据,需要一次性清空所有内容,可以用clear()方法:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(DashBoard.this); SharedPreferences.Editor editor = prefs.edit(); // 清空该文件下所有键值对 editor.clear(); editor.apply(); // 跳转回登录页,可选添加标记清理返回栈 Intent intent = new Intent(DashBoard.this, Login.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish();
小补充
apply()和commit()的区别:apply()是异步提交,不阻塞主线程;commit()是同步提交,会返回布尔值告知提交是否成功,按需选择即可。- 把这些代码放在退出按钮的点击回调或者菜单的选中逻辑里,就能完美实现退出时清除登录状态的效果。
内容的提问来源于stack exchange,提问作者Manish Ahire




