My ViewModel
class implements LifecycleObserver
.
When I call fragment.lifecycle.addObserver(this)
it produces exception.
Caused by: java.lang.IllegalArgumentException: The observer class has some methods that use newer APIs which are not available in the current OS version. Lifecycles cannot access even other methods so you should make sure that your observer classes only access framework classes that are available in your min API level OR use lifecycle:compiler annotation processor.
Strange, that firstly it was working fine, but not long ago this exception has appeared. I've found, that audioFocusRequest
is cause of this bug.
private val audioFocusRequest by lazy {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setOnAudioFocusChangeListener(this)
.build() else throw RuntimeException("Can't be done for Android API lower than 26")
}
Does anybody know how it can be fixed?
UPD
Tried to use annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
, but got compilation error:
(decided to paste screenshot, because whole logs are quite big)
UPD 2
At the end I've decided to delete audioFocusRequest
field and to use old deprecated method - requestAudioFocus(OnAudioFocusChangeListener l, int streamType, int durationHint)
instead of recommended requestAudioFocus(@NonNull AudioFocusRequest focusRequest)
It helped me to make code working again, so it can be solution. But I didn't find answer - why this problem had appeared. It strange because code used to be working before.
So problem has been solved but question still stays unanswered
You can implement LifecycleObserver in your Application Class: public class MyApplication extends MultiDexApplication implements LifecycleObserver @Override public void onCreate() { super.onCreate(); ProcessLifecycleOwner.get().getLifecycle().addObserver(this); }
//Also In Activities or Fragments You can also use them to reduce the complexity of code by creating different components which are implementing LifecycleObserver and then pass the lifecycle of activity to these components. This way you can split up the huge complexity to different components.
Then you can add an observer by calling the addObserver () method of the Lifecycle class and passing an instance of your observer, as shown in the following example:
In the example above, the myLifecycleOwner object implements the LifecycleOwner interface, which is explained in the following section. LifecycleOwner is a single method interface that denotes that the class has a Lifecycle. It has one method, getLifecycle () , which must be implemented by the class.
Try to use kapt "androidx.lifecycle:lifecycle-compiler:2.0.0"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With