gpt4 book ai didi

java - Android IntentReceiver 泄漏

转载 作者:行者123 更新时间:2023-11-30 09:19:29 27 4
gpt4 key购买 nike

在我的 Android 应用程序中,我有一个 Activity MainActivity,它有一个 Fragment MainFragment,它启动一个 IntentService,然后转换到 Activity SelectPlayersActivity(它有一个 Fragment SelectPlayersFragment)。当任一 Activity 位于前台时,IntentService 可能会完成。所以我必须在它们的两个 fragment 中注册 BroadcastReceivers。我通过在名为“NewGameServiceReceiver”的两个 fragment 中创建扩展 BroadcastReceiver 的子类来做到这一点。在这两个 fragment 中,我按如下方式注册了 BroadcastReiceiver:

private void registerBroadcastReceivers() {
IntentFilter newGameFilter = new IntentFilter(BroadcastReceivers.NEW_GAME_BROADCAST_RECEIVER.getName());
newGameServiceReceiver = new NewGameServiceReceiver();
getActivity().registerReceiver(newGameServiceReceiver, newGameFilter);

}

这是在两个 fragment 的 onStart() 方法中触发的:

@Override
public void onStart() {
super.onStart();
registerBroadcastReceivers();
}

我注销的两个 fragment 如下:

@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 的正确方法吗?请注意,我在两个 fragment 中为 IntentFilters 提供了相同的构造函数参数 (BroadcastReceivers.NEW_GAME_BROADCAST_RECEIVER.getName())。这是必要的,因为我不知道哪个 Fragment 会收到服务的 Intent。

如有任何意见/帮助,我们将不胜感激。

最佳答案

尝试先取消注册接收器,然后调用 super.onPause()

@Override
public void onPause() {
getActivity().unregisterReceiver(newGameServiceReceiver);
super.onPause();

}

希望这对您有所帮助。

关于java - Android IntentReceiver 泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17960289/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com