Maybe there's something really simple that I don't see. I'm trying to call a method from some API, and this method asks for a PendingIntent to send me asynchronously some value. I've read the doc and examples for half an hour, and can't wrap my head around a simple way to do it.
More precisely, I want to call the ActivityRecognitionApi. To illustrate, here's how I receive the location from a similar api:
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient,
mLocationRequest,
new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// I can do something with the location
}
});
So I want to do the same to receive the recognized activity :
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient,
1000,
// ... what here ?);
So what would be the simple way to create a pendingIntent to just receive the value ? I tried to create an anonymous PendingIntent but the class is final. I don't want to start a Service, or Activity, or broadcast anything... Is there just a simple way to create this PendingIntent to execute just a block of code?
Thanks in advance,
Then you cannot use
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates()
.No.
The conventional use case for this API is to find out about changes in the device state over a period of time, and your process may not be running in between those changes of state. Hence, they optimized this API for the conventional use case, requiring a
PendingIntent
so they can get your app running again to tell you about the state change.If you happen to be using this API to find out about state changes only while one magic activity of yours happens to be in the foreground, you can use
createPendingResult()
on that activity to get aPendingIntent
that will invokeonActivityResult()
on that same activity. However, this is a fairly niche scenario, particularly for this API.Otherwise, you need to treat this no differently than if you were scheduling an alarm with
AlarmManager
or a job withJobScheduler
:If the work that you are doing will take less than 1 millisecond, create a manifest-registered
BroadcastReceiver
and use agetReceiver()
PendingIntent
If the work that you are doing will take between 1 millisecond and 15 seconds, create an
IntentService
and use agetService()
PendingIntent
If the work that you are doing may take in excess of 15 seconds, create a manifest-registered
WakefulBroadcastReceiver
and anIntentService
, use agetReceiver()
PendingIntent
, and have theWakefulBroadcastReceiver
pass the work to theIntentService
viastartWakefulService()
.