通知服务中的android内存泄漏

时间:2010-08-02 17:38:56

标签: android memory-leaks notifications notificationmanager

我有一项服务可以创建通知,然后定期更新某些信息。电话崩溃并重新启动大约12分钟后,我认为这是由于以下代码中的内存泄漏导致我如何更新通知,有人请检查/建议我是否是这种情况和我我做错了。

的onCreate:

mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

createNotification:

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;
}

updateNotification:

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

提前致谢。

2 个答案:

答案 0 :(得分:9)

我偶然发现了同样的问题。看起来如果你没有在服务中“缓存”RemoteView和Notification,但是在“更新”例程中从头开始重新创建它们,这个问题就会消失。是的,我知道它效率不高,但至少手机不会因内存不足而重启。

答案 1 :(得分:2)

我遇到了同样的问题。我的解决方案接近@haimg所说的那个,但我确实缓存了通知(只重新创建了RemoteView)。通过这样做,如果您正在查看通知,则通知不会再次闪烁。

示例:

public void createNotification(Context context){
    Notification.Builder builder = new Notification.Builder(context);

    // Set notification stuff...

    // Build the notification
    notification = builder.build();
}

public void updateNotification(){
    notification.bigContentView = getBigContentView();
    notification.contentView = getCompactContentView();

    mNM.notify(NOTIFICATION_ID, notification);
}

在方法getBigContentViewgetCompactContentView中,我返回一个更新布局的新RemoteViews