51 lines
1.5 KiB
Kotlin
51 lines
1.5 KiB
Kotlin
package com.gh.common.observer
|
|
|
|
import android.content.Context
|
|
import android.database.ContentObserver
|
|
import android.media.AudioManager
|
|
import android.os.Handler
|
|
import com.gh.common.util.tryCatchInRelease
|
|
import com.halo.assistant.HaloApp
|
|
|
|
class VolumeObserver(var callback: MuteCallback? = null)
|
|
: ContentObserver(Handler()) {
|
|
var previousVolume: Int = 0
|
|
|
|
init {
|
|
val audio = HaloApp.getInstance().application.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
|
// 部分设备的 audioManager getStreamVolume 内部会触发空指针 :(
|
|
tryCatchInRelease { previousVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC) }
|
|
}
|
|
|
|
override fun onChange(selfChange: Boolean) {
|
|
super.onChange(selfChange)
|
|
|
|
val audio = HaloApp.getInstance().application.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
|
var currentVolume = 0
|
|
|
|
tryCatchInRelease {
|
|
// 部分设备(Meizu 7.1.2 M6 Note)的 audioManager getStreamVolume 内部会触发空指针 :(
|
|
currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
|
|
}
|
|
|
|
val delta = previousVolume - currentVolume
|
|
|
|
if (delta != 0) {
|
|
if (currentVolume == 0) {
|
|
callback?.onMute(true)
|
|
} else {
|
|
callback?.onMute(false)
|
|
}
|
|
}
|
|
|
|
if (delta > 0) {
|
|
previousVolume = currentVolume
|
|
} else if (delta < 0) {
|
|
previousVolume = currentVolume
|
|
}
|
|
}
|
|
}
|
|
|
|
interface MuteCallback {
|
|
fun onMute(isMute: Boolean)
|
|
} |