我正在开发一个应用程序,需要听音量键下来和向上的事件做something.When的屏幕是明亮的,我可以覆盖onKeyDown和oneKeyUp methods.But如果手机是锁定的,这种方法是不可能解决的。我想知道手机锁定后如何实现?
发布于 2015-08-14 15:12:37
您可以使用SettingsObserver捕获卷更改作为备份解决方案:
SettingsObserver audioObserver = new SettingsObserver(context, new Handler());对于设置观察者:
public class SettingsObserver extends ContentObserver {
/**
* Application context
*/
private Context context = null;
/**
* build SettingsObserver
*
* @param context retrieve application context to look for Audio Manager service
* @param handler The handler to run {@link #onChange} on, or null if none.
*/
public SettingsObserver(Context context, Handler handler, DroidEvent manager) {
super(handler);
this.context = context;
}
@Override
public boolean deliverSelfNotifications() {
return super.deliverSelfNotifications();
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (audio != null) {
byte newVolumeMedia = (byte) audio.getStreamVolume(AudioManager.STREAM_MUSIC);
byte newVolumeSystem = (byte) audio.getStreamVolume(AudioManager.STREAM_SYSTEM);
byte newVolumeRing = (byte) audio.getStreamVolume(AudioManager.STREAM_RING);
byte newVolumeNotification = (byte) audio.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
byte newVolumeDtmf = (byte) audio.getStreamVolume(AudioManager.STREAM_DTMF);
byte newVolumeVoiceCall = (byte) audio.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
}
}
}并注册您的ContentObserver:
context.getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, audioObserver);这样,您可以检索所有类型的音量事件,这将使您知道音量键已被向上或向下按下
https://stackoverflow.com/questions/32004058
复制相似问题