笔记
针对整个应用程序的监听 与Activity 的数量无关
Lifecycle.Event.ON_CREATE 只会被调用一次 Lifecycle.Event.ON_DESTROY 永远不会被调用
具体代码
package com.cbhx.myapplicationobserver;
import android.util.Log;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
/***
*
* 创建人:xuqing
* 创建时间:2022-4-15
*
*/
public class ApplicationObserver implements LifecycleObserver {
private static final String TAG = "ApplicationObserver";
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate(){
Log.e(TAG, "onCreate: " );
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart(){
Log.e(TAG, "onStart: " );
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume(){
Log.e(TAG, "onResume: " );
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause(){
Log.e(TAG, "onPause: " );
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop(){
Log.e(TAG, "onStop: " );
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy(){
Log.e(TAG, "onDestroy: " );
}
}
在application 里面添加 myapplicationobserver
package com.cbhx.myapplicationobserver;
import android.app.Application;
import androidx.lifecycle.ProcessLifecycleOwner;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(new ApplicationObserver());
}
}
通过 ProcessLifecycleOwner 来管理我们的生命周期的监听 代码变的更加简洁 也比较方便管理 希望文章对各位同学有用
网友评论