You can also subscribe in the background to receive Intent notifications instead of MessageListener notifications. Background scanning is a low-power scanning, so latency can be very long (even minutes to detect a beacon). Scanning is performed when an event occurs on the screen or when another application is requested. Thus, you get the results of other application scans.
You can create a GoogleApiClient using an application context instead of an activity context. Call it, that is, from a broadcast receiver that responds to a BOOT_COMPLETED broadcast.
GoogleApiClient client = new GoogleApiClient.Builder(appContext) .addApi(Nearby.MESSAGES_API, new MessagesOptions.Builder() .setPermissions(NearbyPermissions.BLE) .build()) .build(); client.connect();
Once the client is connected ( onConnected ConnectionCallbacks method), you can subscribe using PendingIntent and create a Broadcast receiver that processes the intent.
In the broadcast receiver, you can process the intent using the Near.Messages.handleIntent method, which uses the same MessageListener as for the foreground scan.
One of the problems with this approach is access permissions in the neighborhood. To allow a user to approve access to a site, you need an interface. My solution was to wait with background scanning until the user first opened the application and accepted the permission. Once accepted, you can subscribe in the background.
source share