我正在使用带有两个自定义按钮的自定义Android设备进行操作,在该设备上,我需要执行两次单独的单击和长按操作。由于某种原因,我尝试使用onKeyUp()和onKeyDown()每次都只触发dispatchKeyEvent()。
我正在尝试运行处理程序以使用dispatchKeyEvent对长按事件执行操作。但是没有运气。这就是我要达到的目的,请按向左/向右按钮以调低/调高音量。长按向左/向右按钮可向后/向前跳过歌曲。
我正在发布我的尝试。
private var isKeyHeld = false
var repeatInterval: Long = 250
private fun isValidKeyEvent(keyCode: Int): Boolean = (keyCode == BUTTON_RIGHT
|| keyCode == BUTTON_LEFT)
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (isValidKeyEvent(event.keyCode)) {
if (event.action == KeyEvent.ACTION_DOWN && event.isLongPress) {
isKeyHeld = true
repeatInterval = 250
startKeyHoldTimer(event.keyCode)
return true
} else if (event.action == KeyEvent.ACTION_UP && isKeyHeld &&
!event.isLongPress) {
isKeyHeld = false
return true
} else if (event.action == KeyEvent.ACTION_UP &
!event.isLongPress) {
event.startTracking()
// increase/decrease the volume
}
}
return super.dispatchKeyEvent(event)
}
var mHandler = Handler()
private var mRunnable: Runnable? = null
private fun startKeyHoldTimer(keyCode: Int){
mRunnable = Runnable {
if (isKeyHeld) {
// skip song
}
}
if (repeatInterval > 0){
mHandler.postDelayed(mRunnable, repeatInterval)
}else{
mHandler.removeCallbacks(mRunnable)
}
}