On an Android device, where the only buttons are the volume buttons and a power button, I want to make the app react to presses on the power button (long and short). How is this done?
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
Use Broadcast receiver for power button (Screen On/Off)event
here is solution: create broadcast receiver class
then follow below steps: 1. Initialize receiver in activity
2.Declare receiver in manifest file in tag
3.For send action and data from activity to receiver put below code in onCreate() or onStrat() method
4.Don't forget to unregister receiver in onDestory() method
The existing answers don't completely answer the question and leave out enough details that they won't work without more investigation. I'll share what I've learned solving this.
First you need to add the following permission to your manifest file:
To handle short and long presses add the following overrides to your activity class:
Note: It is worth noting that onKeyDown() will fire multiple times before onKeyLongPress does so you may want to trigger on onKeyUp() instead or other logic to prevent acting upon a series of onKeyDown() calls when the user is really holding it down.
I think this next part is for Cyanogenmod only. If the PREVENT_POWER_KEY constant is undefined then you should not need it.
To start intercepting the power key you need to set the following flag from your activity:
To stop intercepting the power key (allowing standard functionality):
You can switch back and forth between the two modes repeatedly in your program if you wish.
For all android versions use this code.
I tried R. Zagórski's answer, but I am not able to run this code on Pie. However, I have updated their code in my answer.
PowerButtonService:
and service_layout:
you have to use this:
On you activity add:
Though... this kind of keys are somehow special... not sure if it can give problems to you.
Solution: