如何在Splash Screen后打开Dashboard Screen?已登录未登出时直接跳转
嘿,我来帮你一步步搞定这两个启动屏跳转的问题~
一、先实现启动屏后直接打开仪表盘
你的现有代码里,启动屏结束后默认跳转到登录页面,要改成跳仪表盘很简单,只需要把Intent里的目标Activity换成你的仪表盘对应的类就行。假设你的仪表盘Activity叫DashboardAct,修改后的核心代码片段如下:
handler.postDelayed(new Runnable() { @Override public void run() { progress.setVisibility(View.GONE); // 把原来的CustomerLoginAct替换成你的仪表盘Activity类 Intent obj = new Intent(ActSplashScreen.this, DashboardAct.class); startActivity(obj); // 记得加上finish(),避免用户按返回键回到启动屏 finish(); } }, 5000);
二、根据登录状态自动跳转(已登录直接进仪表盘,未登录进登录页)
要实现这个逻辑,我们需要先在用户登录成功时保存登录状态(用Android自带的SharedPreferences轻量存储最合适),然后在启动屏里读取这个状态,再决定跳转方向。
步骤1:用户登录成功时保存登录状态
在你的登录页面(比如CustomerLoginAct)里,当验证账号密码通过后,添加这段代码记录登录状态:
// 获取SharedPreferences实例,"UserPrefs"是自定义的存储文件名 SharedPreferences sp = getSharedPreferences("UserPrefs", MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); // 存入登录标记,true表示已登录 editor.putBoolean("isLoggedIn", true); // 提交保存 editor.apply();
步骤2:启动屏里读取状态并判断跳转
修改你的ActSplashScreen代码,在延迟任务里先检查登录状态,再决定跳转到哪个页面:
public class ActSplashScreen extends AppCompatActivity { ProgressBar progress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_act_splash_screen); progress = (ProgressBar) findViewById(R.id.progress); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { progress.setVisibility(View.GONE); // 读取登录状态,默认值设为false(未登录) SharedPreferences sp = getSharedPreferences("UserPrefs", MODE_PRIVATE); boolean isLoggedIn = sp.getBoolean("isLoggedIn", false); Intent intent; if (isLoggedIn) { // 已登录状态,直接跳仪表盘 intent = new Intent(ActSplashScreen.this, DashboardAct.class); } else { // 未登录状态,跳登录页 intent = new Intent(ActSplashScreen.this, CustomerLoginAct.class); } startActivity(intent); finish(); // 关闭启动屏,避免返回 } }, 5000); } }
步骤3:用户登出时清除登录状态
别忘了在用户点击登出按钮时,把登录状态重置为false,这样下次启动App会回到登录页:
SharedPreferences sp = getSharedPreferences("UserPrefs", MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putBoolean("isLoggedIn", false); editor.apply(); // 跳转到登录页 Intent intent = new Intent(this, CustomerLoginAct.class); startActivity(intent); finish();
这样就完美实现你想要的逻辑啦~
内容的提问来源于stack exchange,提问作者Pratiksha Patil
相关产品推荐
相关产品推荐

