MM-BB MM-BB - 2 months ago 86
Android Question

How use dispatchKeyEvent() in Service?

I use below code fine in my activity.

dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));


Problem:


How i can use above line code in Service.

I think dispatchKeyEvent method exist in Activity class and not Exist in Service class.

So are any other way or how fix it.

Answer

How i can use above line code in Service

You can't.

I think dispatchKeyEvent method exist in Activity class and not Exist in Service class.

Correct. Services do not have a UI and therefore do not have key events to be dispatched.

So are any other way or how fix it.

Do not attempt to dispatch a key event from a service. dispatchKeyEvent(), to the extent that anyone uses it, is for simulating key events in an activity's own UI. Your service is welcome to tell your activity to dispatch a key event. You might use an event bus implementation (e.g., greenrobot's EventBus) for this.

Comments