java - 更新通知时设置 ContentView 最终会卡住应用程序? (安卓)

标签 java android mobile service notifications

我有一项每毫秒更新一次通知的服务(秒表)。

它最初运行良好,问题是,应用最终变慢了,秒表更新看起来真的很慢。我已将此问题确定为我正在重置通知的内容 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/

相关文章:

java - Spring JMS 消息监听器容器

java - ScriptIntrinsicBlur 在 Galaxy S7 上的 API 24 上损坏了吗?

java - 在不同的 fragment 中实现两个 RecyclerViews,但在同一个 Activity 中

php - mobile.de 搜索 api 授权 fehler mit PHP curl

java - J2ME中如何绕过用户确认?

java - 如何将具有复合键的键值结构映射到 Java 中的 json 对象

java - TypeError : g. getResponseHeader 未定义

android - java.lang.ClassNotFoundException 启动时

Java Android 互联网访问 : WIFI or 3G

java - JDialog 关闭后 mouseReleased 从未调用