2013-04-03 72 views
4

我使用Notifications接口来更新片段,每当数据发生变化时。Android:何时注册和取消注册通知?

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(); 
    } 

请解释为什么你会建议使用一个或其他我mplementation ..或另一个!

+0

为什么不注册和在你的应用类注销? –

回答

1

我会坚持情景2.尽管onPause()onResume()对于片段的顺序是线性的,但对于活动也是如此。

fragment_lifecycle

由于片段暂停和恢复被称为每当活动的是,每当活动是活动的广播将被接收。但是,该活动在调用失败之前不会调用onStop()。在这种情况下,片段仍然会处理广播,而它所包含的活动处于非活动状态,这对我来说听起来不是一个好主意。

2

没有一个普遍的回答这个问题。 onResume/onPause可能会在大多数情况下给出预期的行为,但您可能会遇到您想要更早或更晚执行此操作的情况。

然而,在不同的笔记上,风格和功能上有两点 - 分别称为super.onResume作为方法中的第一件事物(super.onStop作为最后一件事物)。这样你的循环完全嵌套在“超级”循环中,并且避免了怪异的错误和边缘情况。此外,它不是一个伟大的想法,总是叫notifyDataSetChangedonResume。实际上,这可能是一个相当浪费的想法。