你们很多人可能都知道,Android 有许多卷流,例如:
STREAM_ALARM The audio stream for alarms
STREAM_DTMF The audio stream for DTMF Tones
STREAM_MUSIC The audio stream for music playback
STREAM_NOTIFICATION The audio stream for notifications
STREAM_RING The audio stream for the phone ring
STREAM_SYSTEM The audio stream for system sounds
STREAM_VOICE_CALL The audio stream for phone calls
我一直在使用内容观察者。到目前为止,我可以检测一个卷流的变化,但我想知道如何检测上述任何流的变化。我遵循了这个答案中的方法https://stackoverflow.com/a/15292255/2433261
编辑:在将此问题标记为重复之前,请注意,我想检测是否有任何体积流的幅度发生变化。
每当任何流上的音量发生变化时,此流程都会为您提供一个布尔值:
val Context.volumeFlow
get() = callbackFlow {
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val newVolume = intent.getIntExtra(
"android.media.EXTRA_VOLUME_STREAM_VALUE",
0
)
val prevVolume = intent.getIntExtra(
"android.media.EXTRA_PREV_VOLUME_STREAM_VALUE",
0
)
// You can also obtain the type if needed.
// val type = intent.getIntExtra("android.media.EXTRA_VOLUME_STREAM_TYPE", 0)
trySend(newVolume != prevVolume)
}
}
registerReceiver(receiver, IntentFilter("android.media.VOLUME_CHANGED_ACTION"))
awaitClose { unregisterReceiver(receiver) }
}
然后您可以从
ContextWrapper
(例如,Activity
、Service
)中使用它,如下所示:
lifecycleScope.launch {
volumeFlow.collect { Log.d("SOME TAG", "Volume changed: $it") }
}