我正在开发一个应用程序,它需要按下音量键和向上事件来做某事。当屏幕很亮时,我可以覆盖onKeyDown和oneKeyUp方法。但如果手机被锁定,这种方法是不可行的出。我想知道手机锁定后如何实现它?
答案 0 :(得分:0)
您可以使用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);
这样您就可以检索所有类型的音量事件,这会让您知道音量键已被按下或按下