Нет звука в уведомлении в Kotlin Android 10 - PullRequest
0 голосов
/ 28 марта 2020

Я пытаюсь воспроизвести пользовательский звуковой файл как уведомление, но мобильный телефон воспроизводит только файл по умолчанию. (Kotlin) Я деинсталлировал и установил приложение. код должен быть в порядке. приложение представляет собой таймер, который отсчитывает до нуля. -> в нуле должен быть звук (необработанный файл), теперь мой код: сначала моя функция. затем BasicNotificationBuilder, затем PendingIntentWithStack, наконец, NotificationManager с createNotificationChannel. все что я нашел в Java. решение для Kotlin было бы идеально для запуска звукового файла. Спасибо

 fun showTimerExpired(context: Context) { 
        val startIntent = Intent(context, TimerNotificationActionReceiver::class.java)
        startIntent.action = Constants.ACTION_START
        val startPendingIntent = PendingIntent.getBroadcast(
            context, 0, startIntent, PendingIntent.FLAG_UPDATE_CURRENT)

        val soundUri:Uri = Uri.parse(
            "android.resource://" + context.packageName.toString()
                    + "/" + q7.com.eieruhrbackforenot.R.raw.i_feel_good)

        val notificationBuilder =
            getBasicNotificationBuilder(context, CHANNEL_ID, true) 
        notificationBuilder.setContentTitle("Timer Expired")
            .setContentText("Fertig")
            .setContentIntent(getPendingIntentWithStack(context, MainActivity::class.java))
            .addAction(q7.com.eieruhrbackforenot.R.drawable.ic_start, "Start", startPendingIntent)
            .setSound(soundUri, AudioManager.STREAM_NOTIFICATION)
        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        notificationManager.createNotificationChannel(
            CHANNEL_ID, NAME_CHANNEL_ID, true
        )
        notificationManager.notify(TIMER_ID, notificationBuilder.build())
    }
    private fun getBasicNotificationBuilder(
        context: Context, channelID: String, playSound: Boolean
    ): NotificationCompat.Builder {
        val soundUri:Uri = Uri.parse(
            "android.resource://" + context.packageName.toString()
                    + "/" + q7.com.eieruhrbackforenot.R.raw.i_feel_good)
        val notificationBuilder = NotificationCompat.Builder(context, channelID)
            .setSmallIcon(q7.com.eieruhrbackforenot.R.drawable.ic_timer)
            .setAutoCancel(true)// User drückt Notification zum schliessen
            .setDefaults(0)// keine Defaults
            .setSound(soundUri)
        if (playSound) {
            notificationBuilder.setSound(soundUri)
            //notificationBuilder.setSound(notificationSoundUri)
        }
        return notificationBuilder
    }
    private fun <T> getPendingIntentWithStack(
        context: Context,
        javaClass: Class<T>
    ): PendingIntent {
        val soundUri:Uri = Uri.parse(
            "android.resource://" + context.packageName.toString()
                    + "/" + q7.com.eieruhrbackforenot.R.raw.i_feel_good)
        val resultIntent = Intent(context, javaClass)
        resultIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
        val stackBuilder = TaskStackBuilder.create(context)
        stackBuilder.addParentStack(javaClass)
        stackBuilder.addNextIntent(resultIntent)
        return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
    }
    private fun NotificationManager.createNotificationChannel(
        channelID: String,
        channelName: String,
        playSound: Boolean
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelImportance = if (playSound) {
                NotificationManager.IMPORTANCE_DEFAULT
            } else {
                NotificationManager.IMPORTANCE_LOW
            }
            val notificationChannel =
                NotificationChannel(channelID, channelName, channelImportance)
            notificationChannel.enableLights(true)
            notificationChannel.lightColor = Color.CYAN
            notificationChannel.enableVibration(true)
            notificationChannel.vibrationPattern = longArrayOf(100,200,300,400,500,400,300,200,400)
            this.createNotificationChannel(notificationChannel)
            }
        }
    }
}

Ответы [ 2 ]

0 голосов
/ 02 апреля 2020

я нашел лучший способ !!! веселиться:

 private fun NotificationManager.createNotificationChannel(
        channelID: String,
        channelName: String,
        playSound: Boolean
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelImportance = if (playSound) {
                NotificationManager.IMPORTANCE_HIGH
            } else {
                NotificationManager.IMPORTANCE_LOW
            }
            val audioAttribute = AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build()
            val soundUri = Uri.Builder().scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
                .authority("blablabla")
                .path(R.raw.i_feel_good.toString()).build()
            val notyChannel =
                NotificationChannel(channelID, channelName, channelImportance)

            notyChannel.enableLights(true)
            notyChannel.lightColor = Color.RED
            notyChannel.enableVibration(true)
            notyChannel.vibrationPattern = longArrayOf(100, 1000, 100, 1000, 100,1000,100)
            notyChannel.setSound(soundUri,audioAttribute)
            this.createNotificationChannel(notyChannel)
        }
0 голосов
/ 30 марта 2020

Вместо изменения звука в mp3-файл. Я создал намерение с pendingintent, которое запускает musi c в конце таймера. Это работает, но это не то, что я хотел.

 fun showTimerIsExpired(context: Context) { 
            val playMusicIntent = Intent(context,MainActivity::class.java)
            playMusicIntent.action = MainActivity.musicStart().toString()
            val playMusicPendingIntent = PendingIntent.getBroadcast(
                context,0,playMusicIntent,PendingIntent.FLAG_UPDATE_CURRENT)

и установите pendingIntent равным .ContentIntent-> .setContentIntent (playMusicPendingIntent); в моем случае addAction-> .addAction (R.drawable.ic_start, «Пуск», playMusicPendingIntent)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...