Android:何时注册和取消注册通知?

时间:2013-04-03 09:04:36

标签: android-fragments android-lifecycle android-adapter

每当数据发生变化时,我都会使用Notifications接口来更新片段。

public interface Notifications {

    void register(ID id, Listener listener);
    void unregister(ID id, Listener listener);
    <T> void post(ID id, T value);

    interface Listener<T> {
        void onEvent(ID id, T value);
    }

    enum ID {
        CustomersUpdated,
        ProductsUpdated
    }

}

关于Android Lifecycle,注册和取消注册通知的最佳点是什么?

Android Lifecycle

以下是一些情景:

场景1:

public class ProductsListFragment extends BaseFragment 
    implements Notifications.Listener {

    @Override
    public void onStart() {
        mAdapter.notifyDataChanged();
        register(Notifications.ID.ProductsUpdated, this)
        super.onStart();
    }

    @Override
    public void onStop() {
        unregister(Notifications.ID.ProductsUpdated, this)
        super.onStop();
    }

    @Override
    public void onEvent(Notifications.ID id, Object value) {
        mAdapter.notifyDataChanged();
    }

场景2:

public class ProductsListFragment extends BaseFragment
    implements Notifications.Listener {

    @Override
    public void onResume() {
        mAdapter.notifyDataChanged();
        register(Notifications.ID.ProductsUpdated, this)
        super.onResume();
    }

    @Override
    public void onPause() {
        unregister(Notifications.ID.ProductsUpdated, this)
        super.onPause();
    }

    @Override
    public void onEvent(Notifications.ID id, Object value) {
        mAdapter.notifyDataChanged();
    }

请解释为什么您建议使用其中一个或另一个实现..

2 个答案:

答案 0 :(得分:2)

这个问题没有普遍的答案。 onResume / onPause可能会在大多数情况下提供预期的行为,但是您可能会遇到想要在之前或之后执行此操作的情况。

另外,在风格和功能上有两点 - 调用super.onResume作为方法中的第一件事(和super.onStop作为最后一件事)。这样你的循环完全嵌套在“超级”循环中,你可以避免奇怪的错误和边缘情况。此外,始终在notifyDataSetChanged中呼叫onResume并不是一个好主意。事实上,这可能是一个非常浪费的想法。

答案 1 :(得分:1)

我会坚持使用场景2.尽管onPause()onResume()对于片段是线性的,但对于Activities来说却不是这样。

fragment_lifecycle

由于片段的暂停和恢复仅在活动时被调用,因此只要活动处于活动状态,就会收到广播。但是,在活动失去可见性之前,活动不会调用onStop()。在这种情况下,片段仍将处理广播,而其中包含的活动是不活动的,这对我来说听起来不是一个好主意。

相关问题