在Android上聆听音量更改事件 [英] Listen to volume changes events on Android
问题描述
有没有办法在Android上收听音量更改的事件,而不用接管音量按钮?
Is there any way to listen to the event of volume change on Android, without just taking over the volume buttons?
我发现唯一的工作是这里,但它只在卷之后有效控制已经消失了。
The only thing I've found that works is here, but it works only after the volume control has disappeared.
并不是所有的设备都有音量按钮,我需要在音量发生时立即捕获音量更改,而不是音量对话框之后。 / p>
Not all devices have volume buttons, and I need to capture the volume changes as soon as they occur, and not after the volume dialog is gone.
推荐答案
更好的是,您可以注册一个 ContentObserver
,如下所示:
Better, you can register a ContentObserver
as follows:
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, new ContentObserver(){...} );
您的ContentObserver可能如下所示:
Your ContentObserver might look like this:
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);
尽管如此,一些注意事项有时候如果快速按下按钮,通知似乎会延迟。
One caution, though - sometimes the notifications seem to be delayed if there are lots of button presses quickly.
这篇关于在Android上聆听音量更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!