Google Awareness Api events while app isn't running

a 夏天 提交于 2019-12-10 04:34:05

问题


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!


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!