发生本地通知但未出现在屏幕上
Local notification occurs but doesn't appear on the screen
虽然应用发送的通知是高优先级和分组的,但是当频繁发送通知时,过一段时间通知就开始不显示了。当我检查我的代码中的日志时,我可以看到本地通知已经发生。为什么频繁发送通知后没有显示通知?
fun getChatChannels(): MutableList<NotificationChannel> {
val chatChannels = mutableListOf<NotificationChannel>()
val chatChannel = NotificationChannel(
IM_CHANNEL_ID,
Application.getString(R.string.chat_channel_name),
NotificationManager.IMPORTANCE_HIGH
)
chatChannel.setShowBadge(false)
chatChannel.group = MESSAGE_GROUP_ID
chatChannels.add(chatChannel)
return chatChannels }
private fun getChannelList(): MutableList<NotificationChannel> {
val channelList = mutableListOf<NotificationChannel>()
channelList.addAll(getChatChannels())
return channelList
}
fun createGroupsAndChannels() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager =
Application.instance.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannelGroups(getGroupList())
notificationManager.createNotificationChannels(getChannelList())
}
Log.d(TAG, "Channels and groups created")
}
fun showChatNotification(destinationAddress: String, messageId: String, message: String) {
ThreadManager.createUITask {
val name = if (domainContact != null) {
"${domainContact.firstName} ${domainContact.lastName}"
} else {
destinationAddress
}
val notificationIntent = Intent(Application.instance, MainActivity::class.java)
notificationIntent.putExtra(
Application.getString(R.string.key_conversation_participant),
destinationAddress
)
notificationIntent.flags = Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
val pendingIntent = PendingIntent.getActivity(
Application.instance,
destinationAddress.hashCode(),
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val notificationId = UUID.randomUUID().hashCode()
val builder = NotificationCompat.Builder(Application.instance, IM_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification_message)
.setColor(ContextCompat.getColor(Application.instance, R.color.colorPrimary))
.setContentTitle(name)
.setContentText(message)
.setStyle(
NotificationCompat.BigTextStyle() // Expandable-Collapsible notification
.bigText(message)
)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(pendingIntent)
.setVisibility(VISIBILITY_PUBLIC)
.setAutoCancel(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
builder.addAction(getChatNotificationReplyAction(destinationAddress, notificationId, messageId))
}
chatNotifications.add(mapOf(destinationAddress to notificationId))
createNotifications(builder, notificationId)
Log.d(TAG, "Chat notification created")
}
private fun createNotifications(builder: NotificationCompat.Builder, notificationId: Int) {
with(NotificationManagerCompat.from(Application.instance)) {
notify(notificationId, builder.build())
}
}
如果 android os 等于或大于 Oreo,您是否创建了 NotificationChannel?
//////////////////////////////////////////////// //////////////
我在服务中创建一个通知,并在我想更新通知消息时启动通知服务。
我测试了每秒更新消息值,值会改变 50 次以上。
MyNotificationService.java
package com.urpackage.test;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import androidx.core.app.NotificationCompat;
public class MyNotificationService extends Service {
Context mContext;
Notification notification = null;
private final int notificationId=12321;
@Override
public void onCreate() {
super.onCreate();
mContext=this.getApplicationContext();
}
@Override
public void onDestroy() {
NotificationManager notificationManager = (NotificationManager)mContext.getSystemService(mContext.NOTIFICATION_SERVICE);;
notificationManager.cancel(notificationId);
builder =null;
super.onDestroy();
}
NotificationCompat.Builder builder =null ;
private void createNotification(String message) {
try {
NotificationManager notificationManager = (NotificationManager)mContext.getSystemService(mContext.NOTIFICATION_SERVICE);
if(builder==null)
{
String packageName=mContext.getClass().getPackage().getName();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClass(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_MUTABLE);
//Notification notification = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(
packageName,
"MyChannel",
NotificationManager.IMPORTANCE_DEFAULT);
//channelLove.setDescription("最重要的人");
//channelLove.enableLights(true);
//channelLove.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
builder = new NotificationCompat.Builder(getApplication(), packageName)
.setAutoCancel(false).setOngoing(true)
.setSmallIcon(R.drawable.ic_baseline_play_circle_filled_24).setTicker("MyChannelN")
.setContentTitle("MyChannelN")
//.setContentText(message).
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent);
} else {
builder = new NotificationCompat.Builder(getApplication(), packageName)
.setAutoCancel(false).setOngoing(true)
.setSmallIcon(R.drawable.ic_baseline_play_circle_filled_24).setTicker("MyChannelN")
.setContentTitle("MyChannelN")
//.setContentText(message).
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
}
}
// notificationId is a unique int for each notification that you must define
builder.setContentText(message);
notificationManager.notify(notificationId, builder.build());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle=null;
if(intent!=null)
bundle=intent.getExtras();
String message="Running";
if(bundle!=null)
message=bundle.getString("NotificationMessage","Running");
createNotification(message);
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
使用服务
Intent MyNotificationServiceIntent = new Intent(this, >MyNotificationService.class);
MyNotificationServiceIntent.putExtra("NotificationMessage", "your message");
startService(MyNotificationServiceIntent);
虽然应用发送的通知是高优先级和分组的,但是当频繁发送通知时,过一段时间通知就开始不显示了。当我检查我的代码中的日志时,我可以看到本地通知已经发生。为什么频繁发送通知后没有显示通知?
fun getChatChannels(): MutableList<NotificationChannel> {
val chatChannels = mutableListOf<NotificationChannel>()
val chatChannel = NotificationChannel(
IM_CHANNEL_ID,
Application.getString(R.string.chat_channel_name),
NotificationManager.IMPORTANCE_HIGH
)
chatChannel.setShowBadge(false)
chatChannel.group = MESSAGE_GROUP_ID
chatChannels.add(chatChannel)
return chatChannels }
private fun getChannelList(): MutableList<NotificationChannel> {
val channelList = mutableListOf<NotificationChannel>()
channelList.addAll(getChatChannels())
return channelList
}
fun createGroupsAndChannels() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager =
Application.instance.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannelGroups(getGroupList())
notificationManager.createNotificationChannels(getChannelList())
}
Log.d(TAG, "Channels and groups created")
}
fun showChatNotification(destinationAddress: String, messageId: String, message: String) {
ThreadManager.createUITask {
val name = if (domainContact != null) {
"${domainContact.firstName} ${domainContact.lastName}"
} else {
destinationAddress
}
val notificationIntent = Intent(Application.instance, MainActivity::class.java)
notificationIntent.putExtra(
Application.getString(R.string.key_conversation_participant),
destinationAddress
)
notificationIntent.flags = Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
val pendingIntent = PendingIntent.getActivity(
Application.instance,
destinationAddress.hashCode(),
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val notificationId = UUID.randomUUID().hashCode()
val builder = NotificationCompat.Builder(Application.instance, IM_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification_message)
.setColor(ContextCompat.getColor(Application.instance, R.color.colorPrimary))
.setContentTitle(name)
.setContentText(message)
.setStyle(
NotificationCompat.BigTextStyle() // Expandable-Collapsible notification
.bigText(message)
)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(pendingIntent)
.setVisibility(VISIBILITY_PUBLIC)
.setAutoCancel(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
builder.addAction(getChatNotificationReplyAction(destinationAddress, notificationId, messageId))
}
chatNotifications.add(mapOf(destinationAddress to notificationId))
createNotifications(builder, notificationId)
Log.d(TAG, "Chat notification created")
}
private fun createNotifications(builder: NotificationCompat.Builder, notificationId: Int) {
with(NotificationManagerCompat.from(Application.instance)) {
notify(notificationId, builder.build())
}
}
如果 android os 等于或大于 Oreo,您是否创建了 NotificationChannel?
//////////////////////////////////////////////// //////////////
我在服务中创建一个通知,并在我想更新通知消息时启动通知服务。
我测试了每秒更新消息值,值会改变 50 次以上。
MyNotificationService.java
package com.urpackage.test;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import androidx.core.app.NotificationCompat;
public class MyNotificationService extends Service {
Context mContext;
Notification notification = null;
private final int notificationId=12321;
@Override
public void onCreate() {
super.onCreate();
mContext=this.getApplicationContext();
}
@Override
public void onDestroy() {
NotificationManager notificationManager = (NotificationManager)mContext.getSystemService(mContext.NOTIFICATION_SERVICE);;
notificationManager.cancel(notificationId);
builder =null;
super.onDestroy();
}
NotificationCompat.Builder builder =null ;
private void createNotification(String message) {
try {
NotificationManager notificationManager = (NotificationManager)mContext.getSystemService(mContext.NOTIFICATION_SERVICE);
if(builder==null)
{
String packageName=mContext.getClass().getPackage().getName();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClass(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_MUTABLE);
//Notification notification = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(
packageName,
"MyChannel",
NotificationManager.IMPORTANCE_DEFAULT);
//channelLove.setDescription("最重要的人");
//channelLove.enableLights(true);
//channelLove.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
builder = new NotificationCompat.Builder(getApplication(), packageName)
.setAutoCancel(false).setOngoing(true)
.setSmallIcon(R.drawable.ic_baseline_play_circle_filled_24).setTicker("MyChannelN")
.setContentTitle("MyChannelN")
//.setContentText(message).
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent);
} else {
builder = new NotificationCompat.Builder(getApplication(), packageName)
.setAutoCancel(false).setOngoing(true)
.setSmallIcon(R.drawable.ic_baseline_play_circle_filled_24).setTicker("MyChannelN")
.setContentTitle("MyChannelN")
//.setContentText(message).
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
}
}
// notificationId is a unique int for each notification that you must define
builder.setContentText(message);
notificationManager.notify(notificationId, builder.build());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle=null;
if(intent!=null)
bundle=intent.getExtras();
String message="Running";
if(bundle!=null)
message=bundle.getString("NotificationMessage","Running");
createNotification(message);
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
使用服务
Intent MyNotificationServiceIntent = new Intent(this, >MyNotificationService.class); MyNotificationServiceIntent.putExtra("NotificationMessage", "your message"); startService(MyNotificationServiceIntent);