Android中部分业务会需要监听前后台切换 , 而一般前后台监听有两种方案 :
Application
中注册registerActivityLifecycleCallbacks
, 在回调的生命周期onPause
、onResume
进行匹配 , 延时700ms
检测是否有Activity在前台ProcessLifeCyclerOwner
来监听整个进程的生命周期使用ProcessLifeCyclerOwner主要注意以下几点 (官网截取) :
ON_CREATE
一次 , 永远不会调用ON_DESTROY
START
/Resume
状态后 , 才会回调ON_START
、ON_RESUME
PAUSE
/STOP
状态后 , 才会回调ON_PAUSE
、ON_STOP
, 此处还有个700ms
延迟检测700ms
足够让Activity销毁 , 或者执行Configuration ChangeProcessLifeCyclerOwner
Application.registerActivityLifeCycleCallbacks
注册Activity的回调 : ReportFragment.injectIfNeededIn
将ReportFragment注册到Activity中监听Fragment的生命周期ReportFramgnet.setProcessListener
来注册监听器 , 监听ReportFragment的Start/Resume事件Activity.registerActivityLifecycleCallbacks
注册Activity的生命周期监听implementation "androidx.lifecycle:lifecycle-process:2.2.0"
ON_RESUME与ON_PAUSE
即可 , 或者START/STOP
也可以 , 因为在进程生命周期内 , 不会重复回调public class ProcessObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onAppForeground(){
Log.e("ProcessLifeCycler","onAppForeground called");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onAppBackground(){
Log.e("ProcessLifeCycler","onAppBackground called");
}
}
ProcessLifecycleOwner.get().getLifecycle().addObserver(new ProcessObserver());
lifecycler-process.aar
中 , 会在AndroidManifest.xml中注册一个ContentProvider
, 在Provider中进行初始化.public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}
...
}
ProcessLifecycleOwner.init()
中 , 主要是调用attach
函数进行回调注册void attach(Context context) {
mHandler = new Handler();
// 回调on Create
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
Application app = (Application) context.getApplicationContext();
app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@Override
public void onActivityPreCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
activity.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@Override
public void onActivityPostStarted(@NonNull Activity activity) {
activityStarted();
}
@Override
public void onActivityPostResumed(@NonNull Activity activity) {
activityResumed();
}
});
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// 在SDK版本29之前 , 会使用ReportFragement注册 , 生命周期回调
if (Build.VERSION.SDK_INT < 29) {
ReportFragment.get(activity).setProcessListener(mInitializationListener);
}
}
@Override
public void onActivityPaused(Activity activity) {
// 回调Activity Pause状态
activityPaused();
}
@Override
public void onActivityStopped(Activity activity) {
// 回调Activity Stop状态
activityStopped();
}
});
}
void activityStarted() {
mStartedCounter++;
if (mStartedCounter == 1 && mStopSent) {
// 如果StartCount为1 , 发送ON START消息
// mPauseSent是代表是否已经发送了Pause事件
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
mStopSent = false;
}
}
void activityResumed() {
mResumedCounter++;
if (mResumedCounter == 1) {
// 如果resume count为1 , 发送ON START消息
if (mPauseSent) {
// 回调Resume消息 , 如果发送过pause消息
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
mPauseSent = false;
} else {
mHandler.removeCallbacks(mDelayedPauseRunnable);
}
}
}
void activityPaused() {
mResumedCounter--;
if (mResumedCounter == 0) {
// 700毫秒后发送pause等事件
mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);
}
}
void activityStopped() {
mStartedCounter--;
dispatchStopIfNeeded();
}
void dispatchPauseIfNeeded() {
if (mResumedCounter == 0) {
mPauseSent = true;
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
}
}
void dispatchStopIfNeeded() {
if (mStartedCounter == 0 && mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
mStopSent = true;
}
}
public class ProcessLifecycleOwner implements LifecycleOwner {
void attach(Context context) {
mHandler = new Handler();
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
Application app = (Application) context.getApplicationContext();
// 在Application中注册Activitylifecallback
app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@Override
public void onActivityPreCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
// 在ActivityPreCreated中注册ActivityLifeCycle的回调
// 是为了要更准确的拿到Activity的Start/resume
activity.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@Override
public void onActivityPostStarted(@NonNull Activity activity) {
activityStarted();
}
@Override
public void onActivityPostResumed(@NonNull Activity activity) {
activityResumed();
}
});
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// 只有在29版本前 , 才使用ReportFragment , 在29版本后 , 使用在onActivityPreCreate中注册的ActivityPostStarted/ActivityPostResume回调
if (Build.VERSION.SDK_INT < 29) {
ReportFragment.get(activity).setProcessListener(mInitializationListener);
}
}
@Override
public void onActivityPaused(Activity activity) {
activityPaused();
}
@Override
public void onActivityStopped(Activity activity) {
activityStopped();
}
});
}
}
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// 在29之上 , 通过注册ActivityLifecycle来获取生命周期
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}
// 在API 29之前,为了保持与旧版本ProcessLifecycleOwner的兼容性 ,
// 更新生命周期运行时可能不会更新 , 所以需要加上ReportFragment来
// 监听对应的生命周期
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
// 通过ProcessListener分发start状态
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
dispatchResume(mProcessListener);
dispatch(Lifecycle.Event.ON_RESUME);
}
@Override
public void onPause() {
super.onPause();
dispatch(Lifecycle.Event.ON_PAUSE);
}
@Override
public void onStop() {
super.onStop();
dispatch(Lifecycle.Event.ON_STOP);
}
@Override
public void onDestroy() {
super.onDestroy();
dispatch(Lifecycle.Event.ON_DESTROY);
mProcessListener = null;
}
private void dispatch(@NonNull Lifecycle.Event event) {
if (Build.VERSION.SDK_INT < 29) {
// 只有在29以下版本才会分发
dispatch(getActivity(), event);
}
}
}
// 在ProcessLifecyclerOwner中注册的回调 , 在onStart、onResume的时候调用
ActivityInitializationListener mInitializationListener =
new ActivityInitializationListener() {
@Override
public void onCreate() {
}
@Override
public void onStart() {
activityStarted();
}
@Override
public void onResume() {
activityResumed();
}
};