Mahdi-bagvand
Mahdi-bagvand

Reputation: 1407

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.

Upvotes: 0

Views: 5472

Answers (2)

Stephan John
Stephan John

Reputation: 331

The dispatchKeyEvent and other key events will only work when the UI present inside the class like Activity and View classes, It will not work in Service. This because of security purposes. But you can do this using Accessibility service.

Refer the below link :https://developer.android.com/training/game-controllers/controller-input

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007584

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.

Upvotes: 2

Related Questions