Restart service after update (Android)

Restart service after update through the Google Play Store

Maybe it is time to update your rusted background service?

For my Android project Stopeen, I implemented a functionality to schedule actions with a recurrence over time. But one of my problem was : when people will update my app from the store, the service in background will be killed, and so do they the pending intents handled by the alarm manager. So how could I restart the service without forcing my user to launch my app immediately after each update?

The action to automatically restart service after update

I found this action raised by the system : ACTION_MY_PACKAGE_REPLACED

ACTION_MY_PACKAGE_REPLACED — Notifies an application that it was updated, with a new version was installed over an existing version. This is only sent to the application that was replaced. It does not contain any additional data. To receive it, declare an intent filter for this action. You can use the intent to trigger code that helps get your application back in proper running shape after an upgrade. This intent is sent directly to the application, but only if the application was upgraded while it was in started state (not in a stopped state).

In simpler words, the system can call your app after an update, if the user has opened it at least once before.

Implementation

To use it, first create the following broadcast receiver in your project, by replacing MyServiceImplementation by the name of your service class:

It will start the service when called. After that, go in your manifest file and add a filter on the action MY_PACKAGE_REPLACED.

Here you go ! The service will be launched again just after the user update your app, even if he/she does not open the app starting it.

Cases when the service will not restart

This works only if the user has the service running in background when the update occurs, or if the service has stopped by itself earlier.

It will not works if the user has never used an app launching the service yet, or if the user has manually killed the service.

Header picture derived from a TrueMitra‘s picture

About Nicolas Form

I'm Nicolas Form, multi-skill programmer, aesthete and joyful French guy. On this blog I share my tips and tutorials about programming and IT in general. I am freelance, so you can also contact me about a website, an Android app or any other software you need. Check my portfolio and drop me a line!
This entry was posted in Android. Bookmark the permalink.

5 Responses to "Restart service after update (Android)"

Leave a Reply

Your email address will not be published. Required fields are marked *


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Restart service after update (Android)

by Nicolas Form time to read: 2 min
5