Google Nearby Messages API: Attempting to perform a high-power operation from a non-Activity Context

Tags: , , , ,



Calling subscribe on the Google Nearby Messages API for Android results in the Exception:

Attempting to perform a high-power operation from a non-Activity Context

My code:

public void subscribe(final Promise promise) {
    _messagesClient = Nearby.getMessagesClient(reactContext.getApplicationContext(), new MessagesOptions.Builder().setPermissions(NearbyPermissions.BLE).build());
    _subscribeOptions = new SubscribeOptions.Builder()
            .setStrategy(Strategy.BLE_ONLY)
            .setCallback(new SubscribeCallback() {
                @Override
                public void onExpired() {
                    super.onExpired();
                    emitErrorEvent(EventType.BLUETOOTH_ERROR, true);
                }
            }).build();
    Log.d(getName(), "Subscribing...");
    if (_messagesClient != null) {
        if (_isSubscribed) {
            promise.reject(new Exception("An existing callback is already subscribed to the Google Nearby Messages API! Please unsubscribe before subscribing again!"));
        } else {
            _messagesClient.subscribe(_listener, _subscribeOptions).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    Exception e = task.getException();
                    Log.d(getName(), "Subscribed!" + e.getLocalizedMessage());
                    if (e != null) {
                        _isSubscribed = false;
                        promise.reject(e);
                    } else {
                        _isSubscribed = true;
                        promise.resolve(null);
                    }
                }
            });
        }
    } else {
        promise.reject(new Exception("The Messages Client was null. Did the GoogleNearbyMessagesModule native constructor fail to execute?"));
    }
}

Note: The promise Parameter is from React Native, I’m trying to create a wrapper for the API.

At the Log.d event inside my OnCompleteListener, it prints:

Subscribed!2803: Attempting to perform a high-power operation from a non-Activity Context

I do have the API Key and the required Permissions (BLUETOOTH, BLUETOOTH_ADMIN) in my AndroidManifest.xml.

On iOS the API calls work fine.

Answer

Solved it! The context

reactContext.getApplicationContext()

is not a valid Activity Context for the Nearby API! I had to use

getCurrentActivity()

which is a method from the base class ReactContextBaseJavaModule.



Source: stackoverflow