Some time ago, I wrote a code to restart the running application on Android.
You might well ask why such a thing was needed. It was needed because there are cases where, whenever a user changes the theme, the application has to restart to apply the change (it can't be applied on the fly). In my example I used it to restart Qt Quick Controls 2 gallery.
Sadly my fix was not accepted, because other platforms (iOS, IIRC) have this missing feature too, so it was decided to remove Android code so it didn't stand out.
Anyway, because I think this piece of code might help other people, I'm going to share it with you today.
Our goal is to use AlarmManager.set() method to set an alarm (a PendingIntent) that will start our application in the near future (in our case 100ms from now), then quits the application. When the alarm timeouts it will start our application. Be aware that the AlarmManager is anything but accurate, so it might take more than 100ms to restart the application (in some cases it takes up to 5s to restart it).
Here is the code that does all the magic:
6 Comments
24 - Mar - 2017
ekke
If I want to restart the APP for a specific user - per ex. user 10 for work version on a managed device (Android for Work) is there a way to restart app for a given user ? (same as adb shell am start --user 10 .....) thx
27 - Nov - 2017
JO
Many thanks, works great! But I had to make the pause a little longer (1 sec) for a slow, old phone.
9 - Feb - 2018
Le Minh Tu
I have a strange error. After I start application and send some ping message to service (server), but after that, the service not working, I cannot get any pong event. When I go to setting, I saw the service restarting 0 processes and 1 service.
5 - Mar - 2018
Bogdan Cristea
Hi I need a way to bring in front the UI when the background service receives some event (an incoming call for example in the case of a VoIP application). Usually such applications only start an activity with launchMode="singleInstance". Is it possible to restart the current activity for such situation ? How ?
thanks Bogdan
21 - Oct - 2021
Bel
Great solution. Thank you!
29 - Jul - 2022
Sebastian Diel
I needed to add to my AndroidManifest.xml and the user has to explicitly allow my app to show things in front of other apps. Qt 5.15, deployed to a Galaxy Tab S4 (SM-T830) with Android 10