代码未在应用程序的 onCreate 上执行 - Kotlin/Android

Joh*_*tto 2 android kotlin

您能帮我理解为什么我无法在应用程序的 onCreate 中运行SoundManager.initialize(this)行吗?

    class MyApplication : Application() {

override fun onCreate() {
    super.onCreate()
    SoundManager.initialize(this)
    }
}
Run Code Online (Sandbox Code Playgroud)

    class SoundManager {

var soundPool: SoundPool
var c3 = 0

init {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        soundPool = SoundPool.Builder().setMaxStreams(13).build()
    } else {
        soundPool = SoundPool(13, AudioManager.STREAM_MUSIC, 5)
    }
}

fun loadSound(context: Context) {
    c3 = soundPool.load(context, R.raw.c3, 1)
}

fun playSound() {
    soundPool.play(c3, 1.0f, 1.0f, 0, 0, 1.0f)
}

companion object {

    private var singleton: SoundManager? = null

    fun initialize(context: Context) {
        val soundManager = instance
        soundManager.loadSound(context)
    }

    val instance: SoundManager
        @Synchronized get() {
            if (singleton == null) {
                singleton = SoundManager()
            }
            return singleton as SoundManager
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我通过在第一个 Activity 的 onCreate 函数中调用 SoundManager.initialize(this) 找到了解决方法,但我很好奇为什么不能让它与应用程序的 onCreate 一起运行。

谢谢!

小智 5

     <application
        -------
        android:name=".MyApplication"
        ------
       >
Run Code Online (Sandbox Code Playgroud)

将其添加到您的清单文件中。