Search code examples
androidandroid-intentandroid-activityandroid-resourcesandroid-broadcast

Upgrade receiver trigger multiple times


I am currently facing a problem in my application where application upgrade receiver is called multiple times. Below is the manifest code:

<receiver android:name=".receiver.UpgradeReceiver">
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_REPLACED" />
                <data android:scheme="package" android:path="com.example" />
            </intent-filter>
        </receiver>

UpgradeReceiver.java

public Context context;
private static final String TAG = "UpgradeReceiver";

@Override
public void onReceive(Context context, Intent intent) {
    this.context = context;
    if (null == intent) {
        return;
    }

    String action = intent.getAction();
    Log.i(TAG, "Upgrade_Intent_Package[" + intent.getPackage() + "]");
    Bundle bundle = intent.getExtras();
    StringBuilder str = new StringBuilder();
    if (bundle != null) {
        Set<String> keys = bundle.keySet();
        Iterator<String> it = keys.iterator();
        while (it.hasNext()) {
            String key = it.next();
            str.append(key);
            str.append(":");
            str.append(bundle.get(key));
        }
    }
    Log.i(TAG, str.toString());
    if (Constants.UPGRADE_COMPLETED.equalsIgnoreCase(action)) {

    }
}

}

I am trying to filter the upgrade broadcast intents with the application package so that only when my application is upgraded the receiver gets executed.

I tried setting the application package name under the path tag in the manifest but it was of no help. In addition, I also tried to extract the package name from the intent using intent.getPackage() but it returns null. However, Android states that:

Broadcast Action: A new version of an application package has been installed, replacing an existing version that was previously installed. The data contains the name of the package.

I am unable to figure out why my application package name is null. Any help will be highly appreciated.


Solution

  • intent.getPackage() returns the package/application this intent was specifically adressed to but it was sent to any interested receiver therefore there isn't such package.

    Use intent.getData() which returns the updated package as an Uri