I have used the Activity Transition API launched by Google recently to detect when a User gets in and out of the vehicle. Below is the code I am using to achieve the same.
val intent = Intent(context, ActivityTransitionReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT)
transitions.apply {
add(ActivityTransition.Builder()
.setActivityType(DetectedActivity.IN_VEHICLE)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
.build())
add(ActivityTransition.Builder()
.setActivityType(DetectedActivity.IN_VEHICLE)
.setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
.build())
}
var transitionRequest = ActivityTransitionRequest(transitions)
// myPendingIntent is the instance of PendingIntent where the app receives callbacks.
val task = ActivityRecognition.getClient(context).requestActivityTransitionUpdates(transitionRequest, pendingIntent)
task.addOnSuccessListener {
// Handle success
context.toast("Task added successfully")
}
task.addOnFailureListener {
// Handle error
context.toast("Error adding task")
}
The app works fine and receives the broadcast when it is not removed from the recent apps tab. But when the app is removed from the recent apps tab or killed by the system, I am unable to receive the broadcasts. I don't know what I am doing wrong. Is there any other way I can achieve the same?
I considered using foreground service so that the app doesn't get killed but then thought that showing a permanent notification just to detect User Activity Transition is not a good idea.
Edit: I have seen that some apps ask for special permission like "Ignore battery Optimisations" and when this permission is given, that app always seems to work and keeps sending the notification.
onDestroy
? Have you tested on multiple devices? There is a need to be a 'protected app' for some https://mcmap.net/q/131509/-ontaskremoved-not-getting-called-in-huawei-and-xiaomi-devices – PrevotPendingIntent pendingIntent = PendingIntent.getBroadcast(this, 4, intent, PendingIntent.FLAG_NO_CREATE);
pendingIntent = PendingIntent.getBroadcast(this, 4, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
– Sadye