For those using kotlin flows, you can use the following approach to listen to volume changes for a specific stream:
```
val Context.musicVolumeFlow
get() = callbackFlow {
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.getIntExtra("android.media.EXTRA_VOLUME_STREAM_TYPE", 0)) {
AudioManager.STREAM_MUSIC -> trySend(
intent.getIntExtra(
"android.media.EXTRA_VOLUME_STREAM_VALUE",
0
)
)
}
}
}
registerReceiver(receiver, IntentFilter("android.media.VOLUME_CHANGED_ACTION"))
awaitClose { unregisterReceiver(receiver) }
}
```
You can then collect it as follows from a Service (`LifecycleService` in this case but you can use your own coroutine scope):
```
lifecycleScope.launch {
musicVolumeFlow.collect { Log.d("AppLog", "stream volume: $it") }
}
```
Notice this example is only interested in `AudioManager.STREAM_MUSIC`. Make sure to target the audio streams relevant to your application.
For those using kotlin flows, you can use the following approach to listen to volume changes for a specific stream:
```
val Context.musicVolumeFlow
get() = callbackFlow {
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.getIntExtra("android.media.EXTRA_VOLUME_STREAM_TYPE", 0)) {
AudioManager.STREAM_MUSIC -> trySend(
intent.getIntExtra(
"android.media.EXTRA_VOLUME_STREAM_VALUE",
0
)
)
}
}
}
registerReceiver(receiver, IntentFilter("android.media.VOLUME_CHANGED_ACTION"))
awaitClose { unregisterReceiver(receiver) }
}
```
You can then collect it as follows from an Activity or Service:
```
lifecycleScope.launch {
musicVolumeFlow.collect { Log.d("AppLog", "stream volume: $it") }
}
```
Notice this example is only interested in `AudioManager.STREAM_MUSIC`. Make sure to target the audio stream relevant to your application.