How to change Android notifications sound intercepting them?

41 Views Asked by At

I'm trying to intercept android's notifications and change their audio programmatically using NotificationListenerService.

I've tried using NotificationListenerService and change the statusBarNotification sound, but it doesn't seem to work.

class NotificationModifierService : NotificationListenerService() {
    private var notificationManager: NotificationManager? = null

    override fun onCreate() {
        super.onCreate()
        notificationManager = super.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    }

    override fun onBind(intent: Intent?): IBinder? {
        return super.onBind(intent)
    }

    override fun onNotificationPosted(sbn: StatusBarNotification) {
        val channel = notificationManager!!.getNotificationChannel(sbn.notification.channelId)
        channel.setSound(null, null)
        
        Toast.makeText(this, "This is my Toast message!", Toast.LENGTH_LONG).show()
    }

    override fun onNotificationRemoved(sbn: StatusBarNotification?) {
        super.onNotificationRemoved(sbn)
    }
}

channel ends up being null, even though sbn.notification.channelId is not null, so I'm not able to change the sound...

I also tried to cancel the notification and create another one, I was able to cancel, but not able to create it...

    override fun onNotificationPosted(sbn: StatusBarNotification) {
        this.cancelNotification(sbn.key)
        
        // CREATE NEW CHANNEL HERE

        // ...
        
        notificationManager!!.notify(123, sbn.notification)

        Toast.makeText(this, "This is my Toast message!", Toast.LENGTH_LONG).show()
    }
0

There are 0 best solutions below