Android - Getting volume button long clicks

2019-01-29 08:01发布

问题:

Can someone please show me a code example about how to get a long click (2 sec for example) on the volume up hardware key?

Thanks :)

EDIT

The class that i want to capture the long click with is a Service. How can i do that?

回答1:

If you just need to capture long clicks, this answer might be helpful:

https://stackoverflow.com/a/5269673/1401257

EDIT:

I have never tried to have a key listener inside a service, but with a little help from Google I found this: Volume change listener?

It seems that normal key events can only be handled from Activities. I do not have time to try this out myself, but for capturing long clicks it might be possible to combine the answer from the link and Lukes answer. From what I understand about BroadcastReceivers, you would want to create a receiver, that notify the Service whenever someone click the volume buttons.



回答2:

Optionally you could do something like this:

if(clickedDown) {
if(beginningTime + 2000 < System.currentTimeMillis()) {
// Ok, the button has been clicked down for 2 seconds
}
}
else {
beginningTime = System.currentTimeMillis();
}

Applying something like this, you'll be able to define the amount of time to wait.