有什么方法可以收听Android上的音量变化事件,而不仅仅是接管音量按钮?
我发现唯一可以工作的是here,但它只有在音量控制消失后才能工作。
并非所有设备都有音量按钮,我需要在音量变化发生时立即捕捉它们,而不是在音量对话框消失后捕捉它们。
有什么方法可以收听Android上的音量变化事件,而不仅仅是接管音量按钮?
我发现唯一可以工作的是here,但它只有在音量控制消失后才能工作。
并非所有设备都有音量按钮,我需要在音量变化发生时立即捕捉它们,而不是在音量对话框消失后捕捉它们。
更好的是,您可以ContentObserver
按如下方式注册 a:
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, new ContentObserver(){...} );
您的 ContentObserver 可能如下所示:
public class SettingsContentObserver extends ContentObserver {
private AudioManager audioManager;
public SettingsContentObserver(Context context, Handler handler) {
super(handler);
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
}
@Override
public boolean deliverSelfNotifications() {
return false;
}
@Override
public void onChange(boolean selfChange) {
int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
Log.d(TAG, "Volume now " + currentVolume);
}
}
完成后:
getApplicationContext().getContentResolver().unregisterContentObserver(mContentObserver);
不过需要注意的是 - 如果快速按下大量按钮,有时通知似乎会延迟。
好的,现在,我要做的是使用 onKeyDown 听音量按钮(并检查 KEYCODE_VOLUME_DOWN、KEYCODE_VOLUME_MUTE、KEYCODE_VOLUME_UP),并使用一个处理程序,我发布了一个新的可运行文件来检查音量级别。
另外,由于某些设备具有音量对话框,因此根据此链接,我在它消失时添加了一个侦听器。
Use broadcast receiver VOLUME_CHANGED_ACTION then use AudioManager to obtain current volume.
<receiver android:name="VolumeChangeReceiver" >
<intent-filter>
<action android:name="android.media.VOLUME_CHANGED_ACTION" />
</intent-filter>
</receiver>
You can use : registerMediaButtonEventReceiver (ComponentName eventReceiver) which registers a component to be the sole receiver of MEDIA_BUTTON intents.
// in your activity.
MediaButtonReceiver receiver = new MediaButtonReceiver();
// in onCreate put
registerMediaButtonEventReceiver(receiver);
class MediaButtonReceiver implements BroadcastReceiver {
void onReceive(Intent intent) {
KeyEvent ke = (KeyEvent)intent.getExtra(Intent.EXTRA_KEY_EVENT);
if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
//action when volume goes down
}
if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
//action when volume goes up
}
}
}
//In both onStop and onPause put :
unregisterMediaButtonEventReceiver(receiver);
what we are doing here is defining a BroadcastReceiver that deals with ACTION_MEDIA_BUTTON. and use EXTRA_KEY_EVENT which is containing the key event that caused the broadcast to get what was pressed and act upon that.