'Service not opening activity while app in background

I have a broadcastReceiver opening a service when a time is reached.

If the app is open and running in foreground then the service is called and then calls an activity.

If the app is open but running in background then the service is called but doesn't open the app.

service: class AlarmRingService : Service() {

override fun onCreate() {
    super.onCreate()
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    val ringIntent = Intent(this, AlarmRingActivity::class.java)
    ringIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    startActivity(ringIntent)
    Toast.makeText(this, "activity should have started", Toast.LENGTH_LONG).show()
    return START_STICKY
}

override fun onDestroy() {
    super.onDestroy()
}

override fun onBind(intent: Intent): IBinder? {
    return null
}
}

The toast is called even when looking at the phones home screen with app open in background.

Activity:

    lateinit var binding: ActivityAlarmRingBinding
private val fragmentManager = supportFragmentManager


@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityAlarmRingBinding.inflate(layoutInflater)
    setContentView(binding.root)
    supportActionBar?.title = ""

    val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)

    Toast.makeText(this, "activity started", Toast.LENGTH_LONG).show()

    if (prefs.getBoolean("sp_shake", true)) {
        val fragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.add(R.id.fragmentContainerViewAlarm, ShakeAlarmRingFragment())
        fragmentTransaction.addToBackStack(null)
        fragmentTransaction.commit()
    } else {
        val fragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.add(R.id.fragmentContainerViewAlarm, AlarmRingFragment())
        fragmentTransaction.addToBackStack(null)
        fragmentTransaction.commit()
    }
}

override fun onBackPressed() {
    // back not allowed
}

}

I have seen elsewhere that this doesn't work on Xiaomi phones, which is where I a testing physically, but testing multiple phones in the emulator also yields the same results.



Solution 1:[1]

As mentioned in comments this can't really be worked around after Android 10.

You need to open a notification which can start your activity.

In the case of an alarm though, vibrate and the ringtone etc can still be called from the service, just not the activity itself.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joe Pleavin