首页 > 解决方案 > Android - 状态栏通知未显示

问题描述

当我的应用程序根据业务完成流程时,我试图在状态栏中显示通知。我尝试创建通知。它执行但在状态栏中看不到。也无法获取错误详细信息。以下是尝试。但两者都没有奏效。

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())
    }

标签: androidkotlinnotificationsandroid-notifications

解决方案


在 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


推荐阅读