Removing the view is easy. I noticed you have set it to invisible, this is an acceptable solution. You can also keep a reference to it around and do the following:
windowManager.removeView(mYourView); The problem is going to be detecting the back button press. You cannot do this reliably. You're relying on a hardware expectation, namely that the back button press sends a key event with KEYCODE_BACK, and the OS does not make this guarantee. However, on my Droid turbo the following works:
First you need a separate xml file to configure your accessibility service.
contents of service_config.xml:
<?xml version="1.0" encoding="utf-8"?> <accessibility-service xmlns:android="http://schemas.android.com/apk/res/android" ... android:canRequestFilterKeyEvents="true" android:accessibilityFlags="flagDefault|flagRequestFilterKeyEvents" ... /> Contents of AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" ... <application ...> <service ...> <meta-data android:name="android.accessibilityservice" android:resource="@xml/service_config" /> </service> </application> </manifest>