Android的 - 监听器的硬键preSS的背景 [英] Android - Listener for hard keys press at background

查看:119
本文介绍了Android的 - 监听器的硬键preSS的背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android提供了一些回调方法,帮助我们处理应用程序内的关键事件。但如果我要听关键事件时,我的应用程序在后台运行?例如。我要听长preSS事件上的搜索按钮做一个特殊的功能。

Android provides some callback methods which help our to handle key event inside the apps. But what if I want to listen key events when my app is running at background? Eg. I want to listen for long press event on search button to do a special feature.

推荐答案

的KeyEvent只能由活动处理,因为他们的界面向用户pressing键和只有当他们在前台。甚至在后台运行的服务并不打算对用户的输入作出反应。

KeyEvents can only be handled by Activities as they are the interface to the user pressing the keys and only when they are in the foreground. Even Services that run in the background are not intended to react on user input.

不过,通过使用服务,您可以有变通的方法。您可以创建通过注册一个BroadcastReceiver响应硬键preSS事件的服务。例如,在AOSP音乐应用程序,他们有一个服务(<一href="https://github.com/android/platform_packages_apps_music/blob/master/src/com/android/music/MediaPlaybackService.java">MediaPlaybackService)通过注册一个BroadcastReceiver(<一个响应音量键事件href="https://github.com/android/platform_packages_apps_music/blob/master/src/com/android/music/MediaButtonIntentReceiver.java">MediaButtonIntentReceiver).

But by using a service you can have a workaround. You can create a service that responds to hard key press events by registering a BroadcastReceiver. For example in the AOSP music app, they have a Service (MediaPlaybackService) that responds to volume key events by registering a BroadcastReceiver (MediaButtonIntentReceiver).

这里的code在那里注册的接收器:

Here's the code where it registers the receiver:

mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
ComponentName rec = new ComponentName(getPackageName(),
        MediaButtonIntentReceiver.class.getName());
mAudioManager.registerMediaButtonEventReceiver(rec);

这个工程,即使在音乐应用程序是不是在前台。从的答案。

This works even if the Music app is not in the foreground. Code snippet from this answer.

这篇关于Android的 - 监听器的硬键preSS的背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆