音量变化监听器? [英] Volume change listener?
问题描述
有没有办法通过 Android 服务监听音量变化并做出反应?
Is there any way to listen for volume changes with an Android service and react to that?
顺便说一句:即使音乐在后台播放,Google 音乐应用程序如何允许用户控制媒体音量?
Btw: How does the Google music app allow the user to control the media volume even when the music is playing in the background?
推荐答案
查看registerMediaButtonEventReceiver(ComponentName broadcastReceiver);
定义处理 ACTION_MEDIA_BUTTON
的 BroadcastReceiver
.收到的 intent
包括一个额外的字段,EXTRA_KEY_EVENT
,包含导致广播的关键事件.您可以使用此键事件来获取按下了哪个键.
Define a BroadcastReceiver
that handles ACTION_MEDIA_BUTTON
. The recieved intent
includes a single extra field, EXTRA_KEY_EVENT
, containing the key event that caused the broadcast. You can use this key event to get which key was pressed.
这只是一个示例代码.可能存在语法错误.
This is just a sample code. syntax errors may be there.
// in onCreate of activity
registerMediaButtonEventReceiver(mediaReceiver );
// later somewhere in activity.
MediaButton_Receiver mediaReceiver = new MediaButton_Receiver();
class MediaButton_Receiver implements BroadcastReceiver {
void onReceive(Intent intent) {
KeyEvent ke = (KeyEvent)intent.getExtra(Intent.EXTRA_KEY_EVENT);
if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
}
// Similarly other key codes .......
}
}
在 onPause()
或 onStop()
这篇关于音量变化监听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!