6

My background service performs the core functionality of my app and is first started when the UI is opened.

So when the app is updated on the play store, the service is killed but the UI may not be opened again(So I guess the Service does not start again too).This is bad for me as the service performs the core functionality of the app. How do I overcome this?

Any help is deeply appreciated

abhilash poojary
  • 117
  • 1
  • 2
  • 8

2 Answers2

5

Your service will be killed during upgrade. You need to catch upgrade event and start it again.

In Manifest.xml

<receiver android:name=".yourpackage.UpgradeReceiver" android:enabled="true" android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
            </intent-filter>
        </receiver>

In UpgradeReceiver.java

public class UpgradeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            if (!Intent.ACTION_MY_PACKAGE_REPLACED.equals(intent.getAction()))
                return;

            // Start your service here. 
        } catch (Exception e) {
            Utils.handleException(e);
        }
    }
}
thanhbinh84
  • 17,876
  • 6
  • 62
  • 69
2

Yes every app gets killed during update-refer my answer here

You can make your service as STICKY service,this services are restarted when killed.From the docs:

public static final int START_STICKY Added in API level 5

Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

Other thing you can try is detect app update and start the service again.To detect app update you can listen to PACKAGE_INSTALL broadcast or use following workaround:

  1. Implement a dummy database and override SQLiteOpenHelper.html onUpgrade().The onUpgrade() method is called whenever a new database version is installed.For more info-refer here
  2. Now everytime you have a new update for an app..update the database version too.In this way you will have one to one mapping between database version and the app version.
  3. Now when the user updates the app onUpgrade() is called and you can write whatever logic you want to track the update.(If you are using database in your app, you might need some extra logic to differentiate between actual database upgrade and app upgrade.)
Community
  • 1
  • 1
rupesh jain
  • 3,410
  • 1
  • 14
  • 22