Search code examples
androidkotlinbroadcastreceiver

Is there any way to receive implicit broadcasts in android API 26 and above


I want to receive BroadCast if an application on the target device is updated or uninstalled. Based on the document I can use ACTION_PACKAGE_REPLACED and ACTION_PACKAGE_REMOVED.

Replace action: A new version of an application package has been installed, replacing an existing version that was previously installed.

Remove Action: An existing application package has been removed from the device. The data contains the name of the package. The package that is being removed does not receive this Intent.

so I implemented this in my foreground service:

        val mIntentFilter = IntentFilter()
        mIntentFilter.addAction("android.intent.action.PACKAGE_REMOVED")
        mIntentFilter.addAction("android.intent.action.PACKAGE_REPLACED")
        mIntentFilter.addDataScheme("package")
        this.registerReceiver(applicationReceiver, mIntentFilter)

It works perfectly for removing action, But unfortunately, I didn't receive any broadcast for updating action.

I found out that it is because of the Limits imposed by Google on API 26 and above:

As part of the Android 8.0 (API level 26) Background Execution Limits, apps that target the API level 26 or higher can no longer register broadcast receivers for implicit broadcasts in their manifest.

As this is one of the key features of my application, can anybody help me how to handle this?


Solution

  • You could try this

    class Test(var context: Context) {
      var version: Long = -1
      var pm: PackageManager = context.packageManager
      var e: PackageManager.NameNotFoundException? = null
    
      init {
          val info = pm.getPackageInfo("com.google.maps", 0)
          version = if (Build.VERSION.SDK_INT == Build.VERSION_CODES.P) {
                        info.longVersionCode
                    } else info.versionCode.toLong()
       }
    
      init {
          e!!.printStackTrace()
       }
    

    }

    And then compare your retrieved value to a stored value