Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dispatchKeyEvent from Service

I have a floating view created in service, and I need to dispatch key events when I touch this view. I have found out that view.dispatchKeyEvent() needs context of foreground activity, and key event dispatching only works when activity is foreground. When you close/pause the activity and touch the view - nothing happens, even no NPE in LogCat.

Is there any way to use this method outside of main activity?

like image 529
Nursultan Talapbekov Avatar asked Jan 07 '14 14:01

Nursultan Talapbekov


2 Answers

If I right understand (you did not post any source you have), you need to have floating view over all over apps receives key events, outside your app.

There is some projects shows this ability. (forum-thread androidFloatingImage-repo)

Try to use this floating views example to create each other, or use exactly the same. I think, using something i wrote above you can use callback on key event correctly. Hope it helps;

like image 63
busylee Avatar answered Sep 21 '22 01:09

busylee


This may be a bit too little too late but I found a solution. (Assuming the OP still wants to trigger OS back button from a floating view or service.)

It seems like it is possible to tell Android to press the back button, if you're a registered Accessibility Service. (Once your component is registered with Android, user must explicitly enable it in System Settings. So if this is simply a niche feature for your app rather than a critical function, it may be an overkill.)

Once you're done registering .etc. accordingly, your background service may tell the Accessibility Service to perform the back button, which can be done by calling

performGlobalAction( GLOBAL_ACTION_BACK )

from the Accessibility Service.

You do need API Level 16 or above for this to work.

I haven't got around to test this, but according to docs, this should work. Tried and works on a number of recent devices. (Kitkat, Marshmellow and Nouget)

I found the app Back Button (No root) on play store which seem to employ this technique to draw soft buttons for back, home .etc. (which works on LG Nexus 5X and Samsung Galaxy Tab A 2016)

HTH

like image 41
Madushan Avatar answered Sep 22 '22 01:09

Madushan