问题描述
我正在开发一个类似聊天的应用程序模块,它需要频繁轮询(每 3 秒一次)以从服务器获取新消息。目前我正在通过使用前台服务来管理一个单独的线程来进行轮询。
由于这是一项前台服务,因此需要通知,我通过创建低优先级/重要性来设置通知,以便通知仅在状态栏中显示为图标。
protected void createNotificationChannel() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,title,notificationmanager.IMPORTANCE_DEFAULT);
channel.setDescription(title);
channel.setShowBadge(true);
channel.enableVibration(true);
channel.setSound(null,null);
notificationmanager notificationmanager = (notificationmanager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if(notificationmanager != null) {
notificationmanager.createNotificationChannel(channel);
}
}
}
// showNotification is true if the Notification "peek" should be displayed,and
// false to just display the notification in the status bar
public NotificationCompat.Builder buildNotification(boolean showNotification) {
List<Message> messageList = getMessageList();
Message oldest = messageList.size() > 0 ? messageList.get(0) : null;
Message newest = messageList.size() > 0 ? messageList.get(messageList.size() - 1) : null;
// Create the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext(),channelId)
// Set notification data and appearance
.setSmallIcon(smallIcon)
.setColor(ContextCompat.getColor(getContext(),R.color.moxie_primary_color))
// Set notification options
.setPriority(showNotification ? NotificationCompat.PRIORITY_HIGH : NotificationCompat.PRIORITY_MIN)
.setDefaults(showNotification ? NotificationCompat.DEFAULT_VIBRATE : 0)
.setDefaults(0)
.setonlyAlertOnce(false);
// If this is a stacking notification,set up the appropriate notification style
NotificationCompat.MessagingStyle style = new NotificationCompat.MessagingStyle(new Person.Builder().setName("Me").build());
for (Message message : getMessages()) {
style.addMessage(
message.message,message.when,new Person.Builder().setName(message.sender).build()
);
}
builder.setStyle(style);
return builder;
}
当 Activity 处于前台并且通知在状态栏中无声可见且不显示窥视时,这可以正常工作,这很合适,因为消息实际上是在聊天 Activity 本身中实时显示的。
当我将活动移到后台时出现问题。那时我希望向用户显示通知查看,以便他们可以看到(并响应)传入的消息。到目前为止,我还没有找到真正实现这一目标的方法。在 showNotification
设置为 true 的情况下重新发布由上述代码创建的通知,这会更改优先级和默认值似乎并没有实际工作。
有什么方法可以使用前台服务通知并有条件地显示或隐藏通知查看?
对于频繁的后台轮询,是否有比前台服务更好的选择(我之前根据操作系统使用过 Timer
或 JobService
,但由于 Android 10 导致轮询延迟过长而放弃了使用)和复杂的过程)?这样我只能在活动在后台发布通知并且它的优先级/重要性永远不需要改变。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)