I would like either a BroadcastReceiver or IntentService (depending on how long my eventual processing takes) to start when a Google Awareness API "fence" fires. For example, perhaps I want to know how many times I activate a set of beacon fences over the course of the day (assuming I keep my phone with me). All the examples I've found show registering broadcast receivers in code, but my understanding is that I would need to register a broadcast receiver in the manifest in order for the OS to send the broadcast to it if my app isn't running. What's more, the intent ID appears to be a custom one, so I would guess I'd have to register it with the OS at least once via code?
I'm guessing I'm going to have to create one or more test apps to figure this out by trial and error, but would sure appreciate hearing from anyone who has tried this and would like to share your results!
It is just enough if you specify BroadCastReceiver in your Manifest file.
Its not a must that you need to register it in the code even after declaring the Manifest <receiver>
entry. Just think about how the platform is able to handle Activities you register it only in the Manifest file(if not we get ActivityNotFoundException) the same way Broadcasts can also be register only in the Manifest file.
You need to declare the receiver like:
<receiver android:name=".MyFenceReceiver" >
<intent-filter>
<action android:name="android.intent.action.FENCE_RECEIVER_ACTION" />
</intent-filter>
</receiver>
Extend the BroadcastReceiver class.
public class MyFenceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
FenceState fenceState = FenceState.extract(intent);
if (TextUtils.equals(fenceState.getFenceKey(), "geofence")) {
switch(fenceState.getCurrentState()) {
case FenceState.TRUE:
break;
case FenceState.FALSE:
break;
case FenceState.UNKNOWN:
break;
}
}
}
}
More info in https://developer.android.com/guide/topics/manifest/receiver-element.html
来源:https://stackoverflow.com/questions/39479521/google-awareness-api-events-while-app-isnt-running