I know how to listen to volume buttons in an activity. But can I do that in a background service? If yes, how to do that?
相关问题
- 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
checkout Controlling Your App’s Volume and Playback ...This will help to solve your problem... multiple applications might want to listen for button presses from background, this may be the reason why KeyEvents can only be handled by Activities as they are the interface to the user pressing the keys.
I was able to make it work on android 5+ devices using
MediaSession
. However,ContentObserver
suggested by @ssuukk didn't work for me on both 4.4 and 7.0 devices (at least on ROMs that I've been testing on). Here is a full example which works on android 5+.Service:
In
AndroidManifest.xml
:In your activity:
There are several things to be aware of:
Settings->Applications
, find the app and force stop it to get volume buttons back.Note: this only works for Activities, and not Services as the question states.
Depending on the context in which the callback is required an alternative solution might be available.
To be capable of detecting the volume button an Activity would need to override the
dispatchKeyEvent
function. For this to be present in multiple activities could could write a superclass containing the overridden function which is extended by all subsequent activities.Here is the code for detecting Volume Up/Down key presses:
Android doesn't document APIs on interacting with volume buttons in that case. So I guess the answer is no…
The AOSP Music app has a Service (MediaPlaybackService) that responds to volume key events by registering a BroadcastReceiver (MediaButtonIntentReceiver).
Here's the code snippet where it registers the receiver:
Also, don't forget about manifest:
This works even if the Music app is not in the foreground. Isn't that what you want?
Judging by the couple of other questions about this topic, no.
Other question 1, Other question 2
Services simply do not receive KeyEvent callbacks.