Saturday 5 November 2022

Android - Replace OnLifecycleEvent is deprecated with DefaultLifecycleObserver or LifecycleEventObserver

As of androidx.lifecycle version 2.4.0, OnLifecycleEvent is deprecated. Instead Use DefaultLifecycleObserver or LifecycleEventObserver is recommended to use instead. Many android applications that use OnLifecycleEvent such as when integrating Admob Open Ads will receive a warning.


For example, the following code will be warned by Android Studio OnLifecycleEvent is deprecated:


    /**
     * LifecycleObserver methods
     */
    @OnLifecycleEvent(ON_START)
    public void onStart() {
        showAdIfAvailable();
        Log.d(LOG_TAG, "onStart");
    }
To replace OnLifecycleEvent, follow these instructions:

First: In build.gradle, please include the LifecycleObserver libraries:


apply plugin: 'com.android.application'

dependencies {
   ...

   implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
   implementation "androidx.lifecycle:lifecycle-runtime:2.5.1"
   annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.2.0"
}

Then choose one of the following two alternatives:

Method 1: replace OnLifecycleEvent with DefaultLifecycleObserver


...
import androidx.lifecycle.DefaultLifecycleObserver;

public class MyApplication extends Application implements DefaultLifecycleObserver {
    @Override
    public void onCreate() {
        super.onCreate();
	// Register DefaultLifecycleObserver 
	ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    /*Replace for OnLifecycleEvent onStart Event */
    @Override
    public void onStart(@NonNull LifecycleOwner owner) {
	// Perform actions every time the app is reopened
    }
}

Method 2: replace OnLifecycleEvent with LifecycleEventObserver


public class MyApplication extends Application implements LifecycleObserver
{
  @Override
  public void onCreate() {
    super.onCreate();
    //...
    // Register LifecycleObserver
    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    //...
  }

  /*Replace for OnLifecycleEvent onStart Event */
  @OnLifecycleEvent(Event.ON_START)
  protected void onMoveToForeground() {
    // Perform actions every time the app is reopened (moves to foreground)
    // appOpenAdManager.showAdIfAvailable(currentActivity);
  }
}

Done !

If you have any difficulties, or have any questions, please leave a comment below the article. We will deal with them together. Thanks


0 nhận xét:

Post a Comment