在我的Android应用程序中,我有一个Activity MainActivity,它有一个Fragment MainFragment,它启动一个IntentService,然后转换到Activity SelectPlayersActivity(它有一个Fragment SelectPlayersFragment)。当任一活动位于前台时,IntentService可能会完成。所以我必须在他们的片段中注册BroadcastReceivers。我这样做是通过创建在名为“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())
。这是必要的,因为我不知道哪个片段会收到服务的意图。
感谢任何评论/帮助。
答案 0 :(得分:2)
首先尝试取消注册接收器,然后调用super.onPause()
@Override
public void onPause() {
getActivity().unregisterReceiver(newGameServiceReceiver);
super.onPause();
}
希望这有帮助。