在我的 Android 应用程序中,我有一个 Activity MainActivity,它有一个 Fragment MainFragment,它启动一个 IntentService,然后转换到 Activity SelectPlayersActivity(它有一个 Fragment SelectPlayersFragment)。当任一 Activity 处于前台时,IntentService 可能会完成。所以我必须在它们的两个片段中注册广播接收器。我通过在两个名为“NewGameServiceReceiver”的片段中创建扩展 BroadcastReceiver 的子类来做到这一点。在这两个片段中,我按如下方式注册了 BroadcastReiceiver:
private void registerBroadcastReceivers() {
IntentFilter newGameFilter = new IntentFilter(BroadcastReceivers.NEW_GAME_BROADCAST_RECEIVER.getName());
newGameServiceReceiver = new NewGameServiceReceiver();
getActivity().registerReceiver(newGameServiceReceiver, newGameFilter);
}
这在两个片段的 onStart() 方法中触发:
@Override
public void onStart() {
super.onStart();
registerBroadcastReceivers();
}
我注销的两个片段如下:
@Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(newGameServiceReceiver);
}
但是,当我最终过渡到第三个 Activity 时,DDMS 会报告 NewGameServiceReceiver 上的内存泄漏。unregisterReceiver() 方法在应该调用的时候被调用。
07-31 00:01:30.017: E/ActivityThread(2002): Activity
ws.hamacher.cluebuddy.SelectPlayersActivity has leaked IntentReceiver
ws.hamacher.cluebuddy.SelectPlayersFragment$NewGameServiceReceiver@b3822ea0
that was originally registered here. Are you missing a call to
unregisterReceiver()? 07-31 00:01:30.017: E/ActivityThread(2002):
android.app.IntentReceiverLeaked: Activity
ws.hamacher.cluebuddy.SelectPlayersActivity has leaked IntentReceiver
ws.hamacher.cluebuddy.SelectPlayersFragment$NewGameServiceReceiver@b3822ea0
that was originally registered here. Are you missing a call to
unregisterReceiver()?
这是声明和处理的正确方法BroadcastReceviers
吗?请注意,我IntentFilters
在两个片段中都赋予了相同的构造函数参数(BroadcastReceivers.NEW_GAME_BROADCAST_RECEIVER.getName())
。这是必要的,因为我不知道哪个 Fragment 会收到服务的 Intent。
任何意见/帮助表示赞赏。