我有一项每毫秒更新一次通知的服务(秒表)。
它最初运行良好,问题是,应用最终变慢了,秒表更新看起来真的很慢。我已将此问题确定为我正在重置通知的内容 View 。如果我注释掉该代码,计时器将无限期地正常运行。如果我保留该行,计时器和应用程序会在大约 1-2 分钟后显着变慢。
创建通知的代码:
notificationContent.setImageViewResource(R.id.image, R.drawable.ic_main);
notificationContent.setTextViewText(R.id.exerciseName, _currentExercise.getTitle());
notificationContent.setTextViewText(R.id.setNumber, "Set " + _currentSet + "/" + _currentExercise.getSets());
notificationContent.setTextViewText(R.id.timeElapsed, getFormattedElapsedTime());
notificationContent.setOnClickPendingIntent(R.id.notifButton, setComplete);
mBuilder.setSmallIcon(icon); //for some reason I need this for my view to show up
mBuilder.setContentIntent(contentIntent);
notification = mBuilder.build();
notification.bigContentView = notificationContent;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_NO_CLEAR;
//attach notification and ensure service continues to run in foreground after activity is destroyed
startForeground(NOTIFICATION_ID, notification);
更新通知的代码(每毫秒调用一次):
notificationContent.setTextViewText(R.id.exerciseName, _currentExercise.getTitle());
notificationContent.setTextViewText(R.id.setNumber, getString(R.string.sets_prefix, _currentSet, _currentExercise.getSets()));
notificationContent.setTextViewText(R.id.timeElapsed, getFormattedElapsedTime());
notification = mBuilder.build();
notification.bigContentView = notificationContent;
mNotificationManager.notify(NOTIFICATION_ID,notification);
这一行:notification.bigContentView = notificationContent;
导致速度变慢。如果我删除它,该应用程序将无限期地平稳运行。如果我把它留在里面,我的应用程序就会变慢。而且加类时间也变慢了。就像它在一分钟后开始减速一样,到了 5 分钟,它的速度慢得令人难以忍受。我不知道为什么更新通知的 View 会导致这种情况。任何帮助将不胜感激。
最佳答案
我似乎通过每次更新通知时创建一个新的远程 View 来解决它。
RemoteViews newNotifContent = new RemoteViews(getPackageName(), R.layout.custom_notification);
newNotifContent.setTextViewText(R.id.exerciseName, _currentExercise.getTitle());
newNotifContent.setTextViewText(R.id.setNumber, getString(R.string.sets_prefix, _currentSet, _currentExercise.getSets()));
newNotifContent.setTextViewText(R.id.timeElapsed, getFormattedElapsedTime());
Notification notif = mBuilder.build();
notif.bigContentView = newNotifContent;
mNotificationManager.notify(NOTIFICATION_ID,notif);
现在没有延迟,但我真的不知道为什么每毫秒创建一个新的 remoteviews 对象就能修复它。如果有人知道,请随时补充
关于java - 更新通知时设置 ContentView 最终会卡住应用程序? (安卓),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30293704/