service receive keyevent

http://stackoverflow.com/questions/2986337/is-it-possible-to-create-an-android-service-that-listens-for-hardware-key-presse

1, 

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.

Hope that helped...


2 创建不可见的Activity

Aandroid开发中有时候会用到一些后台的Activity,但又不适合使用service,比如直接点击程序图标时只是执行一段代码,不需要弹出程序界面。此时可以在项目的AndroidManifest.xml文件中相应的Activity标签中添加这样一行:

android:theme=”@android:style/Theme.NoDisplay”

这样一来,当这个Activity启动的时候,就不会显示出界面了。

P.S. Activity有个属性是“visible”,我尝试了在AndroidManifest.xml中添加 android:visible=”false”和在onCreate函数中添加setVisible(false)两种方法,都没有取得预期的效果,后 来在网上查到了Theme.NoDisplay,终于到达效果。


你可能感兴趣的:(android)