Cannot get ActivityRecognitionResult

291 Views Asked by At

I'm registering Broadcast receiver to receive activity events from Android's ActivityRecognition api.

Registering Broadcast receiver in Manifest:

<receiver
        android:name=".ActivityBroadcastReceiver"
        android:exported="true"
        android:permission="com.google.android.gms.permission.ACTIVITY_RECOGNITION">
        <intent-filter>
            <action android:name="my_action" />
        </intent-filter>
    </receiver>

Requesting activity updates:

val broadCastIntent = Intent(this, ActivityBroadcastReceiver::class.java)

ActivityRecognition.getClient(this)
        .requestActivityUpdates(
            100,
            PendingIntent.getBroadcast(
                this,
                0,
                broadCastIntent,
                PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
            )
        )

Inside Broadcast Receiver:

class ActivityBroadcastReceiver : BroadcastReceiver() {

override fun onReceive(context: Context?, intent: Intent) {
    Toast.makeText(
        context,
        ActivityRecognitionResult.hasResult(intent).toString(),
        Toast.LENGTH_SHORT
    ).show()
  }
}

When activity change is recognized (for example: change from WALKING to STILL) onReceive gets triggered inside broadcast receiver but ActivityRecognitionResult.hasResult(intent) always returns false.

1

There are 1 best solutions below

0
Sagar Patel On

From Android 12, the PendingIntent must declare either the flag PendingIntent.IMMUTABLE or the flag PendingIntent.MUTABLE, and here we need PendingIntent.MUTABLE.

Ref: https://developer.android.com/reference/android/app/PendingIntent#constants_1

Hence, try after replacing your current PendingIntent definition with the below one:


     PendingIntent.getBroadcast(
                this,
                0,
                broadCastIntent,
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE 
            )