如何使Activitly正确观察Lifecycle事件

Che*_*eng 11 android

目前,我需要执行一些操作

  • 应用程序启动.
  • 申请退出.
  • 但不是在活动娱乐,配置改变,......

因此,到目前为止,以下代码片段对我很有帮助.我从CommonWare中学到了这样的技巧 - https://commonsware.com/AndroidArch/previews/other-lifecycle-ownershttps://proandroiddev.com/react-to-app-foreground-and-background-events-with-processlifecycleowner -96278e5816fa

WeNoteApplication.java

public class WeNoteApplication extends Application {

    public static class AppLifecycleObserver implements DefaultLifecycleObserver {
        @Override
        public void onResume(LifecycleOwner owner) {
            // Do something when the application launched.
            // But not during activity recreation, configuration change, ...
        }

        @Override
        public void onPause(LifecycleOwner owner) {
            // Do something when the application quit.
            // But not during activity recreation, configuration change, ...
        }
    }

    private static final AppLifecycleObserver appLifecycleObserver = new AppLifecycleObserver();

    @Override
    public void onCreate() {
        super.onCreate();

        initLifecycleObserver();
    }

    private void initLifecycleObserver() {
        Lifecycle lifecycle = ProcessLifecycleOwner.get().getLifecycle();
        lifecycle.removeObserver(appLifecycleObserver);
        lifecycle.addObserver(appLifecycleObserver);
    }
}   
Run Code Online (Sandbox Code Playgroud)

但是,我还需要执行一些操作,使用Activity,Fragment,...例如,呈现出DialogFragment.

对于我的入口点Activity,这是我尝试过的.

public class MainActivity extends AppCompatActivity implements DefaultLifecycleObserver {

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

        ProcessLifecycleOwner.get().getLifecycle().removeObserver(this);
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);

        setContentView(R.layout.activity_main);
    }

    @Override
    public void onResume(LifecycleOwner owner) {
        android.util.Log.i("CHEOK", "onResume LifecycleOwner called");
    }

    @Override
    public void onPause(LifecycleOwner owner) {
        android.util.Log.i("CHEOK", "onPause LifecycleOwner called");
    }

    @Override
    public void onCreate(LifecycleOwner owner) {
        android.util.Log.i("CHEOK", "onCreate LifecycleOwner called");
    }
}
Run Code Online (Sandbox Code Playgroud)

由于以下观察结果,它无法按预期工作

应用程序启动时

onCreate LifecycleOwner called
onResume LifecycleOwner called
onResume LifecycleOwner called    <-- Why onResume of LifecycleOwner is called twice??
Run Code Online (Sandbox Code Playgroud)

当我旋转设备时

onCreate LifecycleOwner called
onResume LifecycleOwner called    <-- Why onCreate and onResume of LifecyclOwner is called during configuration change?
Run Code Online (Sandbox Code Playgroud)

再试一次LiveData

我试图使用LiveData以便AppLifecycleObserver与之通信Activity.但是,在配置更改期间,onResumeLiveData会将处理重新创建Activity为新的生命周期所有者.因此,它将再次触发它.

public class WeNoteApplication extends Application {

    public MutableLiveData<LifecycleOwner> onResumeLiveData = new MutableLiveData<>();

    public class AppLifecycleObserver implements DefaultLifecycleObserver {
        @Override
        public void onResume(LifecycleOwner owner) {
            // This will only be called during app launch, not configuration change.
            android.util.Log.i("CHEOK", "onResume callback happen in application");
            onResumeLiveData.setValue(owner);
            ...


public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        WeNoteApplication.instance().onResumeLiveData.observe(this, new Observer<LifecycleOwner>() {
            @Override
            public void onChanged(@Nullable LifecycleOwner lifecycleOwner) {
                // This will only be called during app launch
                // This will also be called during configuration change.
                android.util.Log.i("CHEOK", "onResume callback happen in activity");
            }
        });
Run Code Online (Sandbox Code Playgroud)

所以,我有些困惑.Activitly(或Fragment)观察Lifecycle事件的正确方法是什么?意思是,在配置更改,活动重新创建期间,不应触发那些回调事件函数,...

Ale*_*lex 2

我在谷歌“todo app”项目中找到了它。您可以使用 SingleLiveEvent 代替 MutableLiveData。我希望它对你有帮助。

public class SingleLiveEvent<T> extends MutableLiveData<T> {

    private static final String TAG = "SingleLiveEvent";

    private final AtomicBoolean mPending = new AtomicBoolean(false);

    @MainThread
    public void observe(LifecycleOwner owner, final Observer<T> observer) {

        if (hasActiveObservers()) {
            Log.w(TAG, "Multiple observers registered but only one will be notified of changes.");
        }

        // Observe the internal MutableLiveData
        super.observe(owner, new Observer<T>() {
            @Override
            public void onChanged(@Nullable T t) {
                if (mPending.compareAndSet(true, false)) {
                    observer.onChanged(t);
                }
            }
        });
    }

    @MainThread
    public void setValue(@Nullable T t) {
        mPending.set(true);
        super.setValue(t);
    }

    /**
     * Used for cases where T is Void, to make calls cleaner.
     */
    @MainThread
    public void call() {
        setValue(null);
    }
}
Run Code Online (Sandbox Code Playgroud)