首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >手机锁定后,收听android音量键关闭和打开事件

手机锁定后,收听android音量键关闭和打开事件
EN

Stack Overflow用户
提问于 2015-08-14 14:57:42
回答 1查看 362关注 0票数 0

我正在开发一个应用程序,需要听音量键下来和向上的事件做something.When的屏幕是明亮的,我可以覆盖onKeyDown和oneKeyUp methods.But如果手机是锁定的,这种方法是不可能解决的。我想知道手机锁定后如何实现?

EN

回答 1

Stack Overflow用户

发布于 2015-08-14 15:12:37

您可以使用SettingsObserver捕获卷更改作为备份解决方案:

代码语言:javascript
复制
SettingsObserver audioObserver = new SettingsObserver(context, new Handler());

对于设置观察者:

代码语言:javascript
复制
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:

代码语言:javascript
复制
context.getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, audioObserver);

这样,您可以检索所有类型的音量事件,这将使您知道音量键已被向上或向下按下

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32004058

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档