How to start another application from broadcast-receiver or a service when my application is in background

201 Views Asked by At

My application needs to open some other applications when it will receive a notification. Now when my application is on front and i open an application upon notification, It works fine. But when there is already another application is open on top of my application, upon launching another application doesn't get launched. I have tried this way.

class AppReceiver : BroadcastReceiver() {
    companion object {
        const val TAG = "AppReceiver"
    }

    override fun onReceive(context: Context, intent: Intent) {
        try {
            if (intent.action == "packageUpdated") {
                val packageName = intent.getStringExtra("packageName") ?: ""
                launchPackage(context, packageName)
            }
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
    }


fun launchPackage(context: Context, packageName: String) {
    try {
        val intent = context.packageManager.getLaunchIntentForPackage(packageName)
        if (intent == null) {
            Log.e(TAG,"Intent not found")
        } else {
            context.startActivity(intent)
        }
    } catch (ex: Exception) {
        ex.printStackTrace()
    }
}


}

The Manifest for receiver:

<receiver
    android:name=".AppReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="packageUpdated" />
    </intent-filter>
</receiver>

launchPackage works first time when application is on top, but not in the case when application is in backstack. Also it doesn't through any exception in this case.

I need whenever broadcast receiver listens if there is an updated package name of application. It should launch that application.

0

There are 0 best solutions below