Android系统如何从服务检测关键presses? [英] android-how to detect key presses from a Service?

查看:114
本文介绍了Android系统如何从服务检测关键presses?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就可以检测到何时返回键是通过覆盖的onkeydown 活动 pssed $ P $:

it is possible to detect when the back key is pressed via overriding onKeyDown in an Activity:

public boolean onKeyDown(int keyCode, KeyEvent event) { 
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            //do your work
            return true;
        }
        return super.onKeyDown(keyCode, event); 
    }

现在,如何检测,从一个服务

now, how to detect that from a Service?

推荐答案

有没有办法做到这一点没有做的一塌糊涂原生Android和机会,你实际上是做错了什么,如果你需要做的是高,因为作为服务文档中指定的服务是一个应用程序组件重新presenting无论是应用程序的愿望,执行长时间运行的操作,而不是相互作用与用户。该服务组件,就是​​要只为长时间执行任务,不需要任何互动,也不依赖于所有从具体行动上的活动比启动和停止等。默认情况下该服务不包含像你需要的输入法,但只是为了无论如何回答你的问题。这样做将是由服务结合的活性,得到从该活动的服务引用方式之一,实施在服务的方法,然后从活动执行该方法时onKey preSS被称为在它

There's no way to do that "without doing a complete mess" natively in android, and chances that you are actually doing something wrong if you need to do that are high because as specified in the Service Documentation "A Service is an application component representing either an application's desire to perform a longer-running operation while NOT INTERACTING WITH USER". The service component is meant to be just for long perform tasks that do not require any interaction nor depend at all from specific actions on activity other than start and stop. By default the service do not contain input methods like the one you need, but just to answer your question anyway. One way to do it would be by binding the service to an activity, getting the service reference from the activity, implement a method in the service and then execute that method from your activity when onKeyPress is called in it.

这是您绑定的活动,以服务的方式:的ServiceBinder

This is the way you bind an activity to a Service: ServiceBinder

希望这有助于。

商祺!

这篇关于Android系统如何从服务检测关键presses?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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