java - java - android-how to detect key presses from a Service? - answerstu - answerstu.com answerstu

java - 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?

1 Answer

  1. Kenneth- Reply

    2019-11-14

    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!

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>