Is it possible to create a Service that listens for hardware key presses?

Posted by VoteBrian on Stack Overflow See other posts from Stack Overflow or by VoteBrian
Published on 2010-06-06T23:22:44Z Indexed on 2010/06/06 23:32 UTC
Read the original article Hit count: 150

Filed under:

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?

From semi-related examples online, I put together the following service, but get the error, "onKeyDown is undefined for the type Service"

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);
    }
}

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 to distribute this. Also, it'd be nice to use the camera button to wake the phone.

© Stack Overflow or respective owner

Related posts about android