Soheil
Soheil

Reputation: 1706

android-how to detect key presses from a Service?

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?

Upvotes: 2

Views: 4267

Answers (1)

Martin Cazares
Martin Cazares

Reputation: 13705

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.

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

Hope this Helps.

Regards!

Upvotes: 2

Related Questions