通知服务中的android内存泄漏 [英] android memory leak in notification service

查看:27
本文介绍了通知服务中的android内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务,它创建一个通知,然后定期用某些信息更新它.大约 12 分钟左右后,手机崩溃并重新启动,我相信这是由以下代码中的内存泄漏引起的,与我更新通知的方式有关,有人可以检查/建议我是否是这种情况以及我是什么我做错了.

I have a service which creates a notification and then updates it with certain information periodically. After about 12 mins or so the phone crashes and reboots, I believe it is caused by a memory leak in the following code to do with how I am updating the notification, could someone please check/advise me if this is the case and what I am doing wrong.

onCreate:

mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

创建通知:

private void createNotification() {
  Intent contentIntent = new Intent(this,MainScreen.class);
  contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
  PendingIntent appIntent =PendingIntent.getActivity(this,0, contentIntent, 0);

  contentView = new RemoteViews(getPackageName(), R.layout.notification);
  contentView.setImageViewResource(R.id.image, R.drawable.icon);
  contentView.setTextViewText(R.id.text, "");

  notification = new Notification();
  notification.when=System.currentTimeMillis();
  notification.contentView = contentView;
  notification.contentIntent = appIntent;
}

更新通知:

private void updateNotification(String text){
  contentView.setTextViewText(R.id.text, text);
  mNotificationManager.notify(0, notification);
}

提前致谢.

推荐答案

我偶然发现了同样的问题.看起来如果您不在服务中缓存"远程视图和通知,而是在更新"例程中从头开始重新创建它们,则此问题就会消失.是的,我知道它效率不高,但至少手机不会因内存不足错误而重启.

I stumbled upon the same problem. Looks like that if you don't "cache" the RemoteView and Notification in the service, but re-create them from scratch in the "update" routine this problem disappears. Yes, I know it is not efficient, but at least the phone does not reboot from out of memory errors.

这篇关于通知服务中的android内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆