Есть ли способ изменить поведение Android Foreground Notification? Важность / всплывающее окно / звук - PullRequest
0 голосов
/ 23 мая 2019

Я создал службу переднего плана, которая запускается при запуске MainActivity, и мне нужно изменить поведение уведомления на лету.Повторное создание NotificationChannel не помогло.

Приложение должно проверять наличие новых сообщений каждый раз X.Когда приложение запускается, так как мы используем foregroundservice, мы должны показать уведомление.Этот запуск не должен иметь всплывающих уведомлений со звуком (это может быть достигнуто путем установки значения LOW, но это не является приемлемым решением в этом случае).После запуска службы переднего плана необходимо проверить наличие новых сообщений.Если есть, должно появиться уведомление и звук тоже, текст должен быть обновлен до (у вас есть новые сообщения).Если нет новых сообщений, он должен спокойно сидеть в области уведомлений с текстом (без новых сообщений).Если значение установлено на LOW, звук / всплывающее окно не будет.Мы действительно не хотим использовать 2 уведомления.

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    //Create Notification Channel
    createChannel(applicationContext)

    //Start Foreground
    startForeground(NOTIFICATION_ID, createNotification(applicationContext, applicationContext.getString(R.string.notification_message_empty)))

    timer.scheduleAtFixedRate(
        object : java.util.TimerTask() {

            override fun run() {
                updateNotification()
            }

        }, (1000 * REPEATING_CYCLE_SECONDS).toLong(), (1000 * REPEATING_CYCLE_SECONDS).toLong()
    )

    return Service.START_STICKY
}

private fun createChannel(context: Context) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        notificationManager.deleteNotificationChannel(CHANNEL_ID)

        val importance = NotificationManager.IMPORTANCE_HIGH

        val notificationChannel = NotificationChannel(CHANNEL_ID, InnosmartLerakodas.applicationContext().getString(R.string.app_name), importance)

        notificationChannel.enableVibration(true)
        notificationChannel.setShowBadge(true)
        notificationChannel.enableLights(true)
        notificationChannel.lightColor = ContextCompat.getColor(applicationContext, R.color.colorAccent)
        notificationChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
        notificationManager.createNotificationChannel(notificationChannel)
    }

}

private fun createNotification(context: Context, message: String): Notification {

    val notifyIntent = Intent(context, MainActivity::class.java)
    notifyIntent.flags = Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT

    val title = applicationContext.getString(R.string.notification_title)

    notifyIntent.putExtra("title", title)
    notifyIntent.putExtra("message", message)
    notifyIntent.putExtra("notification", true)

    val pendingIntent = PendingIntent.getActivity(context, System.currentTimeMillis().toInt(), notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT)

    lateinit var mNotification: Notification

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        mNotification = Notification.Builder(context, CHANNEL_ID)
            // Set the intent that will fire when the user taps the notification
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.drawable.ic_notification)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setStyle(
                Notification.BigTextStyle()
                    .bigText(message)
            )
            .setContentText(message).build()
    } else {

        mNotification = Notification.Builder(context)
            // Set the intent that will fire when the user taps the notification
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.drawable.ic_notification)
            .setAutoCancel(true)
            .setPriority(Notification.PRIORITY_HIGH)
            .setContentTitle(title)
            .setStyle(
                Notification.BigTextStyle()
                    .bigText(message)
            )
            .setContentText(message).build()

    }

    return mNotification
}

private fun updateNotification() {
    val text = getCurrentTime()

    val notification = createNotification(applicationContext, text)

    val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    mNotificationManager.notify(NOTIFICATION_ID, notification)
}

Ожидаемый результат: при первом запуске уведомление не появляется и не издает звука.Просто отображается в списке уведомлений, с текстом «нет новых сообщений».Через X раз, если появятся какие-либо новые сообщения, приложение должно отобразить уведомление со звуком, но без создания второго уведомления в списке уведомлений.После нажатия на него, он открывает MainActivity и должен вернуться обратно к «без новых сообщений» без всплывающего сообщения и без звука.

Фактические результаты: либо все уведомления всплывают и имеют звук, либо их нет.

...