是否有可能创建一个Android服务监听硬件密钥presses?有可能、密钥、创建一个、硬件

2023-09-12 21:36:56 作者:将回忆锁好

我想运行Android的后台服务,将作为从主屏幕或当的KeyListener手机是睡着了。这可能吗?

I'd like to run an Android background service that will act as a keylistener from the home screen or when the phone is asleep. Is this possible?

从半相关的例子在线,我放在一起下列服务,但得到的错误,的onkeydown未定义该类型服务。这是否意味着它不能在没有改写启动完成,或者是有什么明显的我失踪?

From semi-related examples online, I put together the following service, but get the error, "onKeyDown is undefined for the type Service". Does this mean it can't be done without rewriting Launcher, or is there something obvious I'm missing?

public class ServiceName extends Service {

    @Override
    public void onCreate() {
        //Stuff
    }

    public IBinder onBind(Intent intent) {
        //Stuff
        return null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN) {
        switch(keyCode) {
        case KeyEvent.KEYCODE_A:
            //Stuff
            return true;
        case KeyEvent.KEYCODE_B:
            //Stuff
            return true;

            //etc.
        }
        }

        return super.onKeyDown(keyCode, event);
    }
}

我知道Android的默认搜索栏,当你从主屏幕类型,但是这真的只是一个非常特殊的用途。我真的不指望任何人,但我想这一点。我只是觉得这是很好的,例如,用相机按钮来唤醒手机。

I realize Android defaults to the search bar when you type from the home screen, but this really is just for a very particular use. I don't really expect anyone but me to want this. I just think it'd be nice, for example, to use the camera button to wake the phone.

推荐答案

据我所知的KeyEvent只能通过活动来处理,因为它们的接口给用户pressing键。在后台运行的服务并且不旨在对用户输入作出反应。这也是你的编译器警告的原因的onkeydown是不确定的该类型服务。服务或任何它的超类没有实现KeyEvent.Callback接口。作为一种解决方法,你可以注册在活动的的Andr​​oidManifest.xml 来的,如 android.intent.action.SCREEN_ON 。当电源按钮pssed打开屏幕你的活动可以开始,初始化某种类型的服务,并返回到后台$ P $。如果这就是你想要做的事。请参见意向文档为可能采取的行动。

As far as I know KeyEvents can only be handled by Activities as they are the interface to the user pressing the keys. Services run in the background and are not intended to react on user input. That's also the reason of your compiler warning "onKeyDown is undefined for the type Service". Service or any of it's Superclasses don't implement the KeyEvent.Callback interface. As a workaround you could register an Activity in your AndroidManifest.xml to react on certain system notifications such as android.intent.action.SCREEN_ON. When the power button is pressed to turn on the screen your activity could be started, initializing a service of some kind and go back to the background. If that's what you intend to do. See Intent docs for possible Actions.

希望这有助于...

 
精彩推荐
图片推荐