I'm trying to send a system back press event via the AccessibilityService
and this works fine, but only if I'm not in my own app.
I'm always getting true
from performGlobalAction
no matter if I'm in my own app or not, but I only see that the event really is executed if I'm not in my own app but in any other one (in the sense of that the previous activity is shown or similar)
Any ideas why this happens? My app is a sidebar app with an overlay drawn on top in the WindowManager
and everything is working (AccessibilityService
is running and is handling my custom events and the service always returns success messages for my events, but my own app does not react to the back button event).
My service looks like following:
public class MyAccessibilityService extends AccessibilityService {
public static void sendBackIntent(Context context) {
Intent intent = new Intent(context, MyAccessibilityService.class);
intent.putExtra("action", GLOBAL_ACTION_BACK);
context.startService(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle extras = intent.getExtras();
Integer action = null;
if (extras != null) {
action = extras.getInt("action");
}
if (action != null) {
switch (action) {
case GLOBAL_ACTION_BACK:
boolean result = performGlobalAction(action);
L.d("Action %d executed: %b", action, result);
break;
default:
L.e("Unhandled action %d", action);
break;
}
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
}
@Override
public void onInterrupt() {
}
}
Edit
To make this clear:
- I do NOT start this service via
MyAccessibilityService.sendBackIntent(context)
, I send the intent like following:if (isAccessibilityserviceRunning) MyAccessibilityService.sendBackIntent(context)
- I start my service via the system service menu by simply enabling it there and let the system start it automatically afterwards
- I've setup everything for the
AccessibilityService
in anaccessibilityservice.xml
and use this to define my services settings and this is working perfectly fine as well, all events I want to receive are received reliably and correct
EDIT 2
Seems like in my case my overlay is still stealing the focus making it focusable and not has timing problems that sometimes make problems. Still, my solution can be improved by using BroadcastReceiver
to communicate with the service, as the startService
call is not safe as discussed in the accepted answer