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

如何在Android Studio中实现启动页动态切换:重启后打开指定Activity

实现方案

步骤1:记录跳转状态

在MainActivity的按钮点击事件里,跳转至AutoActivity的同时,用SharedPreferences保存用户已进入过AutoActivity的标记:

button.setOnClickListener(v -> {
    // 保存状态标记
    SharedPreferences sp = getSharedPreferences("app_config", MODE_PRIVATE);
    sp.edit().putBoolean("has_enter_auto", true).apply();
    // 跳转页面
    startActivity(new Intent(MainActivity.this, AutoActivity.class));
});

步骤2:修改MainActivity启动逻辑

在MainActivity的onCreate方法中,先读取标记,若用户已进入过AutoActivity,直接跳转并关闭当前页面:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    SharedPreferences sp = getSharedPreferences("app_config", MODE_PRIVATE);
    boolean hasEnterAuto = sp.getBoolean("has_enter_auto", false);
    
    if (hasEnterAuto) {
        startActivity(new Intent(this, AutoActivity.class));
        finish(); // 避免返回栈残留MainActivity
        return;
    }
    
    // 正常加载MainActivity布局与初始化
    setContentView(R.layout.activity_main);
    // 其他初始化代码...
}

步骤3:可选的重置逻辑

如果需要让用户能回到MainActivity,可在AutoActivity中添加清除标记的功能:

resetBtn.setOnClickListener(v -> {
    SharedPreferences sp = getSharedPreferences("app_config", MODE_PRIVATE);
    sp.edit().putBoolean("has_enter_auto", false).apply();
    startActivity(new Intent(AutoActivity.this, MainActivity.class));
    finish();
});

进阶优化方案(可选)

如果想让启动流程更清晰,可新增一个SplashActivity作为唯一启动页,在其中判断标记后跳转:

// SplashActivity的onCreate逻辑
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
    
    SharedPreferences sp = getSharedPreferences("app_config", MODE_PRIVATE);
    boolean hasEnterAuto = sp.getBoolean("has_enter_auto", false);
    
    Intent targetIntent = hasEnterAuto 
        ? new Intent(this, AutoActivity.class) 
        : new Intent(this, MainActivity.class);
    
    startActivity(targetIntent);
    finish();
}

然后在Manifest中修改启动页配置:

<activity
    android:name=".SplashActivity"
    android:theme="@style/Theme.App.Splash">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name=".MainActivity"/>
<activity android:name=".AutoActivity"/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 14:02:20