Search code examples
androidandroid-activitylaunchaccessibilityserviceusagestatsmanager

Android - Listen for a specific application to launch and launch some other application instead


I am trying to make an application listen for a specific application (A1) to launch and then launch some other application (A2) instead (user's choice).

Currently I use two permissions, PACKAGE_USAGE_STATS and BIND_ACCESSIBILITY_SERVICE. The first permission is currently used to detect when the specific application (A1) launches. The second permission is used to simulate a button press, such as home or back.

I tried earlier to launch the other application (A2) as soon as the specific application (A1) launched using the code below with no success (application A1 is still on top).

Intent intent = activity.getPackageManager().getLaunchIntentForPackage(SPECIFIC_APPLICATION_PKG); activity.startActivity(intent);

I realised that when leaving the specific application (A1) and going to the launcher/home screen then it was possible to launch the other application (A2). I simulated a back press as soon as the specific application (A1) launched and then launched the other application (A2) with success. The problem with this method was that when being inside a third application (A3) and performing the steps above I would end up in the third application (A3), in other words not launching application A2. To try and find a solution for this I thought of the idea to change the back press to a home press instead, this always takes me to the launcher/home screen from all applications. However if I originate from a third application (A3) and launch A1 (through for example the recents menu) then press home (through code) and try to launch A2 (through code), instead we go to A3 for some reason that I can't figure out.

All help is appreciated!


Solution

  • I found the solution in a previous asked question here on SO.

    Starting an activity from a service after HOME button pressed without the 5 seconds delay

    See Chinibin's answer