How to know my Android application has been upgraded in order to reset an alarm?

Android

Android Problem Overview


I noticed that an alarm is disabled when the application which sets this alarm has been upgraded. Is that true ?

Until now, I used the SharedPreferences with a FIRST_RUN key in order to know if it's the first run of my application. If I don't find this key, I enable the alarm and set FIRST_RUN to false, else I do nothing.

But I noticed also that these preferences remain intact between app upgrade !

So after an upgrade, the FIRST_RUN key is already false, so I do nothing while my alarm need to be enabled.

How to handle such case ?

Thanks in advance

Android Solutions


Solution 1 - Android

> Solution by Daniel Lew :

Need a receiver with the following lines in manifest :

<receiver android:name=".OnUpgradeReceiver">
  <intent-filter>
    <action android:name="android.intent.action.PACKAGE_REPLACED" />
    <data android:scheme="package" android:path="your.app.package" />
  </intent-filter>
</receiver>

android:path is used in order to prevent OnUpgradeReceiver to be triggered by any upgrade of any application.

Solution 2 - Android

I've never tried this myself, but what about creating a BroadcastReceiver that listens to the ACTION_PACKAGE_REPLACED Intent?

I've thought about trying this before, but I'm not sure if there's a chicken-and-egg problem with it or not (e.g., does the Intent get sent before the new upgraded application can receive it?). Worth a try, though.

Solution 3 - Android

Simply, listen to the android.intent.action.MY_PACKAGE_REPLACED ... This INTENT will notify you if a new version of your application has been installed over an existing one

Note: This intent can is available starting from API 12

Solution 4 - Android

For the Android API level 12 and above, you need to register BroadcastReceiver with action ACTION_MY_PACKAGE_REPLACED

<receiver android:name=".MyBroadcastReceiver">
  <intent-filter>
    <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
  </intent-filter>
</receiver>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontbruyelleView Question on Stackoverflow
Solution 1 - AndroidtbruyelleView Answer on Stackoverflow
Solution 2 - AndroidDan LewView Answer on Stackoverflow
Solution 3 - AndroidSami EltamawyView Answer on Stackoverflow
Solution 4 - Androidarmansimonyan13View Answer on Stackoverflow