我尝试在我的应用程序确实完成业务流程时在状态栏中显示通知。我尝试创建通知。它执行但在状态栏中看不到。也无法获取错误详细信息。下面是尝试。但是两者都不起作用。
private fun showNotification(title: String?, body: String?) {
val intent = Intent(requireContext(), MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(requireContext(), 0, intent,
PendingIntent.FLAG_ONE_SHOT)
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(requireContext())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
val notificationManager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
}
// --------------------------------------------- -------------------------------------------------- -------
private fun sendNotification(remoteMessage: String) {
val intent = Intent(requireContext(), MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(requireContext(), 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(requireContext())
.setContentText(remoteMessage)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
val notificationManager = requireContext().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
}
答案 0 :(得分:1)
在Android 8(API级别26)中,所有通知都必须分配给一个频道。这对我有用:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getContext(), CHANNEL_ID)
.setSmallIcon(R.drawable.emo_no_paint_120)
.setContentTitle("title")
.setContentText("content")
.setColor(Color.parseColor("#009add"))
.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(
NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(0, mBuilder.build());
您应该添加AppCompat库
implementation 'com.android.support:support-compat:27.1.0'
检查此链接
https://developer.android.com/training/notify-user/channels.html