谷歌附近信息API。试图从非活动上下文中执行高能操作。

问题描述 投票:1回答:1

呼叫 subscribe 在Google Nearby Messages API for Android上,结果出现了Exception。

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

我的代码。

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?"));
    }
}

注意:承诺参数来自React Native,我正试图为API创建一个包装器。

Log.d 我的 OnCompleteListener,它打印出来了。

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

我确实有API密钥和所需的权限(BLUETOOTH, BLUETOOTH_ADMIN)在我 AndroidManifest.xml.

在iOS上,API调用可以正常工作。

java android react-native google-api google-nearby
1个回答
0
投票

解决了 上下文

reactContext.getApplicationContext()

不是附近API的有效活动上下文! 我不得不使用

getCurrentActivity()

是基类的一个方法 ReactContextBaseJavaModule.

© www.soinside.com 2019 - 2024. All rights reserved.