1

I have a simple app to count the number of repetitions of different exercises.

What I would like to do is to move to a new window (Activity in my case) when the set number of repetitions is reached. To do that, I call a new activity in onSensorChanged like:

override fun onSensorChanged(event: SensorEvent?) {
    if(repetitionTracker.getNumberOfRepetitions() <= maxRepetitions ){
        intent_next = Intent(this, End::class.java)
        intent_next.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(intent_next)

    }

}

But the application crash when reaching this point

I tried everything that was suggested here: Start Activity from Service in Android.

But I couldn't find a way to make it work. I suppose that the problem is to use Android 10+

Do you know what is the right pattern/method to do this kind of operations? I'm also open to not call a new activity but something else if this is the correct way of doing it

  • 1
    What's the stacktrace/error logs of the crash?, have you checked that "End" is declared in your manifest? – z.g.y Nov 30 '22 at 09:13
  • From Android 9+, we can not start an activity when the app is in the background. I have experienced this from the broadcast receiver. May be the service has the same issue. – Muaz Nov 30 '22 at 09:23
  • @Muaz yes I think it's the same problem. Do you have any idea on how to solve it? I can't think of anything that could obtain the same result without having the app in background since it's the sensor event that trigger this change – user3784015 Nov 30 '22 at 09:30
  • I haven't found anything related to that. – Muaz Nov 30 '22 at 09:31

2 Answers2

1

technically, its not possible, "Android 10 (API level 29) and higher place restrictions on when apps can start activities when the app is running in the background. These restrictions help minimize interruptions for the user and keep the user more in control of what's shown on their screen."

however, you can read this for alternative solutions.

ther'es also Exceptions to the restriction you can check out.

nope
  • 106
  • 9
1

Ok after thinking a bit about what's happening under the hood I find a way to solve the problem. Maybe this can help other people in the same situation. What I did is to add the following lines in onSensorChanged()

override fun onSensorChanged(event: SensorEvent?) {
    if(repetitionTracker.getNumberOfRepetitions() <= maxRepetitions ){
        intent_next = Intent(this, End::class.java)
        intent_next.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        
        sensorManager.unregisterListener(this)
        
        startActivity(intent_next)

    }

Where sensorManager is defined in the onCreate() as:

sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION)?.also{
            sensorManager.registerListener(this, it,SensorManager.SENSOR_DELAY_GAME, SensorManager.SENSOR_DELAY_FASTEST)
        }