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
CodePudding user response:
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.
CodePudding user response:
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)
}