how to capture long press volume down key in android?

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

Just wondering whether anyone could tell me how to capture the long keypress of the volume down key in android.

Elaborated question:

I wanted to create a BroadcastReceiver which will receive volume long keypress event. (without any UI interaction). I know it's possible for the search button. is it available for the Volume Keys?

Thanks

回答1:

may be below code will help you:

@Override public boolean onKeyLongPress(int keyCode, KeyEvent event) {   if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {      // to your stuff here      return true;   }   return super.onKeyLongPress(keyCode, event); } 


回答2:

Note that to handle onKeyLongPress() you should track event onKeyDown(). and override both of them. please note the following examples.

 @Override public boolean onKeyDown(int keyCode, KeyEvent event){     if(keyCode==KeyEvent.KEYCODE_VOLUME_UP){         event.startTracking();         return true;     }     return super.onKeyDown(keyCode,event); }  @Override public boolean onKeyLongPress(int keyCode,KeyEvent event){     if(keyCode==KeyEvent.KEYCODE_VOLUME_UP){         //Do your stuff here         return true;     }     return onKeyLongPress(keyCode,event); } 

Also note that onKeyDown by default returns false. So by triggering onKeyDown() volume won't be increased.



回答3:

I think that it is in theory possibly to accomplish the capturing of long key presses of the volume button, but is ill advised. The process would involve overriding the onKeyLongPress() method.

As to why it is ill advised: Volume Control in android application and How can I manage audio volumes sanely in my Android app?

It has been discussed before and basically, the keys have default behaviors that should not be overwritten because it is possible to "break the behavior of the volume keys".



回答4:

Try with this command

adb shell input keyevent --longpress KEYCODE_VOLUME_DOWN



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!