setSmallIcon () и setLargeIcon () не работают в уведомлении Android - PullRequest
0 голосов
/ 30 мая 2019

Я отправляю уведомление из консоли Firebase. Я могу легко получить данные уведомления, и уведомление также появляется, но я пытаюсь изменить маленький значок и большой значок уведомления.

Я использую оба метода, но ни один из них не работает. Я также попытался сделать маленькую иконку с помощью опции Vector через res>New>Vector>Clip Art. Не появляется ни маленький значок, ни большой значок, и уведомление также нельзя развернуть.

MessagingService.kt

class MessagingService(): FirebaseMessagingService() {

  override fun onMessageReceived(p0: RemoteMessage ? ) {
    super.onMessageReceived(p0)
    showNotification(p0!!.notification!!.title!!, p0!!.notification!!.body!!)
  }

  fun showNotification(title: String, body: String) {
    val icon = BitmapFactory.decodeResource(resources,
      R.drawable.iphn)
    NotificationCompat.Builder(this, "MyNotifications")
      .setLargeIcon(icon)
      .setSmallIcon(R.drawable.ic_notif)
      .setContentTitle(title)
      .setContentText(body)
      .setStyle(NotificationCompat.BigPictureStyle()
        .bigPicture(icon)
        .bigLargeIcon(null))
      .build()

  }
}

ic_notif - это чертеж, который я создал, используя Vector

Ответы [ 3 ]

1 голос
/ 30 мая 2019

Вы можете попробовать использовать ic_notif.png вместо вектора.

Кроме этого, в последней версии Android рекомендуется использовать channelId.Вы можете добавить этот блок, чтобы добавить channelId

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channelId = "yourChannelId"
        val channel = NotificationChannel(channelId, "your channel Name" ,
                NotificationManager.IMPORTANCE_DEFAULT)
        mNotificationManager.createNotificationChannel(channel)
        mBuilder.setChannelId(channelId)
    }
0 голосов
/ 30 мая 2019

Вот рабочий пример:

вызов sendNotification(yourResponse) внутри onMessageReceived(remoteMessage: RemoteMessage?), таким образом вы можете установить большой значок статически или динамически.

private fun sendNotification(response: NotifyResponse) {
        var bmp: Bitmap? = null
        try {
//loading the image from server 


//            if (!TextUtils.isEmpty(response.image)) {
//                val futureTarget = GlideApp.with(this).asBitmap().load(response.image).submit()
//                try {
//                    bmp = futureTarget.get()
//                    GlideApp.with(this).clear(futureTarget)
//
//                } catch (e: ExecutionException) {
//                    e.printStackTrace()
//                } catch (e: InterruptedException) {
//                    e.printStackTrace()
//                }
//
//            }

            val uniqueInt = (System.currentTimeMillis() and 0xfffffff).toInt()
            val pendingIntent = PendingIntent.getActivity(this, uniqueInt, getIntent(response.type), PendingIntent.FLAG_ONE_SHOT)

            val channelId = BuildConfig.FLAVOR
            val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
            val notificationBuilder = NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(notificationIcon)
                    .setContentTitle(response.title)
                    .setContentText(response.message)
                    .setAutoCancel(true)
                    .setSound(soundUri)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
            if (bmp != null) {
                notificationBuilder.setLargeIcon(bmp)
                notificationBuilder.setStyle(NotificationCompat.BigPictureStyle().bigPicture(bmp).bigLargeIcon(null))
            }
            notificationBuilder.setContentIntent(pendingIntent)


            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager


            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = NotificationChannel(BuildConfig.FLAVOR,
                        "Channel human readable title",
                        NotificationManager.IMPORTANCE_DEFAULT)
                notificationManager.createNotificationChannel(channel)
            }

            notificationManager.notify(0, notificationBuilder.build())
        } catch (o: Exception) {
            o.printStackTrace()
        }

    }
0 голосов
/ 30 мая 2019
private var mBuilder: NotificationCompat.Builder? = null  
val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val intent = Intent(activity, MainActivity::class.java)
val pi = PendingIntent.getActivity(activity, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)


  if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {            
     val icon = BitmapFactory.decodeResource(resources, shapemyapp.admin.R.drawable.iphn)                                    
     val importance = NotificationManager.IMPORTANCE_DEFAULT
     val notificationChannel = NotificationChannel("ID", "Name", importance)
     mNotificationManager.createNotificationChannel(notificationChannel)
     mBuilder = NotificationCompat.Builder(this, "MyNotifications")
          .setLargeIcon(icon)
          .setSmallIcon(R.drawable.ic_notifications_active_black_24dp)
          .setContentTitle(title)
          .setContentText(body)              
          .build()
  } else {
        mBuilder = NotificationCompat.Builder(activity) 
           .setSmallIcon(R.drawable.ic_notifications_active_black_24dp)
  }                                         
    mBuilder!!.setContentIntent(pi)
    mNotificationManager.notify(NotificationID.id, mBuilder!!.build())
...