androidwear-osambient

'AmbientLifecycleObserver' is abstract; cannot be instantiated


Google updated how ambient mode works in WearOS but I'm having trouble implementing the changes.

This is the change they made: https://android-review.googlesource.com/c/platform/frameworks/support/+/2534423

Rename AmbientLifecycleObserverInterface -> AmbientLifecycleObserver

The problem is I'm now getting this error message:

'AmbientLifecycleObserver' is abstract; cannot be instantiated

My code looks exactly like the sample code they provide:

https://android-review.googlesource.com/c/platform/frameworks/support/+/2534423/4/wear/wear-samples-ambient/src/main/java/androidx/wear/samples/ambient/MainActivity.kt

So I'm confused on what I'm doing wrong. This is the code for AmbientLifecycleObserver:

https://android-review.googlesource.com/c/platform/frameworks/support/+/2534423/4/wear/wear/src/main/java/androidx/wear/ambient/AmbientLifecycleObserver.kt

This is my code:

private AmbientLifecycleObserver mAmbientLifecycleObserver;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //getting error 'AmbientLifecycleObserver' is abstract; cannot be instantiated
    mAmbientLifecycleObserver = new AmbientLifecycleObserver(this, mAmbientCallback);
            
    getLifecycle().addObserver(mAmbientLifecycleObserver);
}



final AmbientLifecycleObserver.AmbientLifecycleCallback mAmbientCallback = new AmbientLifecycleObserver.AmbientLifecycleCallback() {

    @Override
    public void onEnterAmbient(@NonNull AmbientLifecycleObserver.AmbientDetails ambientDetails) {

    }

    @Override
    public void onUpdateAmbient() {

    }

    @Override
    public void onExitAmbient() {

    }
};

Solution

  • If you look at the actual change they made, the AmbientLifecycleObserver call that you see in their code is not a constructor - it is a top level function call (e.g., a static method) that just happens to return an instance of the interface AmbientLifecycleObserver.

    Because their code is in Kotlin, calling a top level function looks just like a constructor.

    In Java code though, you need to call that top level function using the same syntax as a static method, in this case on the automatically generated class that is created for each file, AmbientLifecycleObserverKt:

    mAmbientLifecycleObserver = AmbientLifecycleObserverKt.AmbientLifecycleObserver(
       this, mAmbientCallback);
    

    You can actually see the generated Java method name in the API signature file.