我有一项服务可以创建通知,然后定期更新某些信息。电话崩溃并重新启动大约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);
}
提前致谢。
答案 0 :(得分:9)
答案 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);
}
在方法getBigContentView
和getCompactContentView
中,我返回一个更新布局的新RemoteViews
。