SplashScreen之后如何启动MainActivity?

问题描述 投票:0回答:1

我想在 android 12 以下的设备上运行我的应用程序。该应用程序将有一个启动屏幕,该应用程序无法使用启动屏幕 api,因为它在 android 12 以下的设备中无法充分工作。如何在显示 SplashScreen 后正确启动 MainActivity ?

飞溅活动

@SuppressLint("CustomSplashScreen")
class SplashActivity: ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AudioAppTheme {
                SplashScreen()
            }
        }
    }
}

@Composable
private fun SplashScreen(){
    LaunchedEffect(key1 = true) {
        delay(2000)
        startActivity(Intent(this@SplashScreen,MainActivity::class.java))
    }
}

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">


    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@drawable/spotify"
        android:label="@string/app_name"
        android:roundIcon="@drawable/spotify"
        android:supportsRtl="true"
        android:theme="@style/Theme.AudioApp"
        tools:targetApi="31">
        <activity
            android:name=".ui.activities.SplashActivity"
            android:exported="true"
            android:theme="@style/Theme.MySplash">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ui.activities.MainActivity" android:exported="false"/>
    </application>

</manifest>

我阅读了多篇文章,但没有找到好的解决方案。

android kotlin android-activity android-jetpack-compose android-splashscreen
1个回答
0
投票

将上下文传递给可组合函数:您可以将上下文从 Activity 传递到可组合函数。

修改后的代码:

@SuppressLint("CustomSplashScreen")
class SplashActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AudioAppTheme {
                // Pass the context to SplashScreen
                SplashScreen(context = this)
            }
        }
    }
}

@Composable
private fun SplashScreen(context: Context) {
    LaunchedEffect(key1 = true) {
        delay(2000)
        // Use the passed context to start the MainActivity
        context.startActivity(Intent(context, MainActivity::class.java))
        // Optionally finish the SplashActivity if you don't want to keep it in the back stack
        if (context is Activity) {
            context.finish()
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.