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
IT IS POSSIBLE. Use code below (FOR NEWER ANDROIDS, ESP. MARSHMALLOW, SEE BOTTOM OF THE ANSWER):
Then in your service onCreate register it with:
Then unregister in onDestroy:
Note that this example judges by change of media volume, if you want to use other volume, change it!
UPDATE:
Above method supposedly doesn't work on Marshmallow, BUT there's much better way now since MediaSession was introduced! So first you have to migrate your code to MediaController/MediaSession pattern and then use this code:
Somehow volume button presses are detected even with screen off (just be sure to register proper media button intent receiver if applicable for your platform!)
UPDATE 2 since GalDude requested some more info on getting media MediaSession/MediaController. Sorry, but since I stopped using Java it will be in Kotlin:
You need to play blank sound from service then only you can listen to volume changes. Following worked for me
Steps
1. Put blank.mp3 in raw folder (Download from here)
2. Start media at onStartCommand()
3. You must choose to stop and release mediaplayer. It's better to do so in onDestroy()
4. Create Broadcast receiver that will listen for volume changes
5. Register the broadcast receiver in onStartCommand()
6. Unregister broadccast receiver in onDestroy()
That's all
This requires Lollipop (v5.0/API 21) or higher
My goal was to adjust system volume from a Service. Any action can be taken on press though.