After updating lifecycle
library to 2.4.0 Android studio marked all Lifecycle events as deprecated.
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun create() {
tts = TextToSpeech(context, this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun stopTTS() {
tts?.stop()
}
Is there any equivalent replacement such as DefaultLifecycleObserver
?
CodePudding user response:
It's deprecated because they now expect you to use Java 8 and implement the interface DefaultLifecycleObserver. Since Java 8 allows interfaces to have default implementations, they defined DefaultLifecycleObserver with empty implementations of all the methods so you only need to override the ones you use.
The old way of marking functions with @OnLifecycleEvent
was a crutch for pre-Java 8 projects. This was the only way to allow a class to selectively choose which lifecycle events it cared about. The alternative would have been to force those classes to override all the lifecycle interface methods, even if leaving them empty.
In your case, change your class to implement DefaultLifecycleObserver and change your functions to override the applicable functions of DefaultLifecycleObserver. If your project isn't using Java 8 yet, you need to update your Gradle build files. Put these in the android
block in your module's build.gradle
:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}