android Ringtone API,android - Notification sound on API 26 - Stack Overflow

I've been developing app with similar functionality. And as mentioned Paweł Nadolski we have to recreate channel each time to change ringtone. For this I wrote helper. Hope it can help someone.

@RequiresApi(Build.VERSION_CODES.O)

object ChannelHelper {

// channel id for 8.0 OS version and higher

private const val OREO_CHANNEL_ID = "com.ar.app.notifications"

private const val CHANNEL_ID_PREF = "com.ar.app.notifications_prefs"

@JvmStatic

fun createChannel(context: Context, playSound: Boolean, isVibrated: Boolean, uri: Uri) {

// establish name and importance of channel

val name = context.getString(R.string.main_channel_name)

val importance = if (playSound) {

NotificationManager.IMPORTANCE_DEFAULT

} else {

NotificationManager.IMPORTANCE_LOW

}

// create channel

val channelId = OREO_CHANNEL_ID + UUID.randomUUID().toString()

saveChannelId(context, channelId)

val channel = NotificationChannel(channelId, name, importance).apply {

enableLights(true)

lightColor = Color.GREEN

lockscreenVisibility = Notification.VISIBILITY_PUBLIC

// add vibration

enableVibration(isVibrated)

vibrationPattern = longArrayOf(0L, 300L, 300L, 300L)

// add sound

val attr = AudioAttributes.Builder()

.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)

.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)

.build()

setSound(uri, attr)

}

// register the channel in the system

val notificationManager = context.getSystemService(NotificationManager::class.java)

notificationManager.createNotificationChannel(channel)

}

@JvmStatic

fun rebuildChannel(context: Context, playSound: Boolean, isVibrated: Boolean, uri: Uri) {

val notificationManager = context.getSystemService(NOTIFICATION_SERVICE)

as NotificationManager

notificationManager.deleteNotificationChannel(

getChannelId(context) ?: OREO_CHANNEL_ID

)

createChannel(context, playSound, isVibrated, uri)

}

@JvmStatic

fun getChannel(context: Context): NotificationChannel? {

val notificationManager = context.getSystemService(NOTIFICATION_SERVICE)

as NotificationManager

return notificationManager.getNotificationChannel(

getChannelId(context) ?: OREO_CHANNEL_ID

)

}

@JvmStatic

fun isChannelAlreadyExist(context: Context) = getChannel(context) != null

@JvmStatic

fun getChannelId(context: Context) =

PreferenceManager.getDefaultSharedPreferences(context)

.getString(CHANNEL_ID_PREF, OREO_CHANNEL_ID)

private fun saveChannelId(context: Context, channelId: String) =

PreferenceManager.getDefaultSharedPreferences(context)

.edit()

.putString(CHANNEL_ID_PREF, channelId)

.apply()

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值