Is it possible to publish messages using Google Nearby Messages in the background in Android?

793 views Asked by At

I am developing an app,which is publishing messages and subscribe using Google Nearby Messages API.The documentation says Because the Nearby Messages APIs have the potential to impact battery life, they should only be used from a foreground activity (with the exception of BLE background subscribe).

But is it still possible?

And what strategy to use to achieve maximum distance?

Thx.

1

There are 1 answers

0
Maxime Jallu On

Answer to your question, on the official documentation

Sample GitHub Google

Google Solution

// Subscribe to messages in the background.
private void backgroundSubscribe() {
    Log.i(TAG, "Subscribing for background updates.");
    SubscribeOptions options = new SubscribeOptions.Builder()
            .setStrategy(Strategy.BLE_ONLY)
            .build();
    Nearby.getMessagesClient(this).subscribe(getPendingIntent(), options);
}

private PendingIntent getPendingIntent() {
    return PendingIntent.getBroadcast(this, 0, new Intent(this, BeaconMessageReceiver.class),
            PendingIntent.FLAG_UPDATE_CURRENT);
}

The following code snippet demonstrates handling the intent in the BeaconMessageReceiver class.

@Override
public void onReceive(Context context, Intent intent) {
    Nearby.getMessagesClient(context).handleIntent(intent, new MessageListener() {
        @Override
        public void onFound(Message message) {
            Log.i(TAG, "Found message via PendingIntent: " + message);
        }

        @Override
        public void onLost(Message message) {
            Log.i(TAG, "Lost message via PendingIntent: " + message);
        }
    });
}

When the subscription is no longer required, your app should unsubscribe by calling Nearby.getMessagesClient(Activity).unsubscribe(PendingIntent).

A solution to use BLE

SubscribeOptions.Builder builder = new SubscribeOptions.Builder();

if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    builder.setStrategy(Strategy.BLE_ONLY);
} else {
    builder.setStrategy(new Strategy.Builder().setDistanceType(Strategy.DISTANCE_TYPE_EARSHOT).build());
    Toast.makeText(this, "BLE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}

mOptions = builder.build();

Publish

Strategy s = new Strategy.Builder()
                    .setDistanceType(Strategy.DISTANCE_TYPE_EARSHOT)
                    .build();
PublishOptions options = new PublishOptions.Builder()
                                .setStrategy(s)
                                .build();
Nerby.getMessagesClient(this).publish(mMessageName, options);