2012-04-01 28 views
0

我在ViewPager上有5个片段(它们全部在内存中,onPause()等包含Activity在屏幕上时不会调用)。自定义BroadcastReceiver将不会收到广播

无论如何,我需要更新一个片段(GroupsListFragment)取决于另一个(TimetableListFragment)发生了什么。我为此使用了LocalBroadcastManager和BroadcastReceiver。

现在进入相关部分。 注册的广播意图(严重略):

public class GroupsListFragment extends Fragment { 
     @Override 
     public void onResume() { 
      super.onResume(); 
      mBroadcastManager = LocalBroadcastManager.getInstance(getActivity()); 
      mBroadCastReceiver = new UpdateGroupsReceiver(this); 
      IntentFilter iFilter = new IntentFilter(UpdateGroupsReceiver.UPDATE_TIMETABLE_ACTION); 
      Log.d("GroupsListFragment", "Registering for receiver with intentfilter:[action=" + iFilter.getAction(0) + "]"); 
      mBroadcastManager.registerReceiver(mBroadCastReceiver, iFilter); 
     } 
} 

发送广播(再次严重略):

public class TimetableListFragment extends Fragment { 
    public void updateStatus() { 
     Intent intent = new Intent(UpdateGroupsReceiver.UPDATE_TIMETABLE_ACTION); 
     mBroadcastManager.sendBroadcast(intent); 
     Log.d(TAG, "Sending broadcast with intent:[action=" + intent.getAction() + "]"); 
    } 
} 

的问题是,我UpdateGroupsReceiver从来没有收到它(onReceive()是从来没有发射) 。

任何有关可能是罪魁祸首的建议?

+0

updategroupsreciever是什么样子的?编辑:NVM,可能不相关......但我假设你的日志语句签出? – JRaymond 2012-04-01 18:03:35

+0

你在做什么onPause()为GroupsListFragment? B/C你说GroupListFragment可能暂停在这一点上。此外,它有**有史以来**现在在屏幕上出现? – JRaymond 2012-04-01 18:14:18

+0

我假设,把this.registerReceiver(BroadCastReceiver,IntentFilter);在onCreate()方法中尝试 – Selva 2012-08-08 07:09:54

回答

0

我使用这个代码,运作良好

@Override 
public void onResume() { 
    super.onResume(); 
    if (myReceiver == null) { 
     myReceiver = new UpdateGroupsReceiver(this); 
     IntentFilter filter = new IntentFilter(
       UpdateGroupsReceiver.UPDATE_TIMETABLE_ACTION); 
     registerReceiver(myReceiver, filter); 
    } 
} 

public void updateStatus() { 
    Intent intent = new Intent(); 
    intent.setAction(UpdateGroupsReceiver.UPDATE_TIMETABLE_ACTION); 
    sendBroadcast(intent); 
} 

一个运行过程中出现小例子testapp可以在https://github.com/k3b/EzTimeTracker/BroadCastTest下找到。