Google 附近消息 API:尝试从非活动上下文执行高功率操作



在适用于 Android 的 Google Nearby Messages API 上调用subscribe会导致异常:

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

注意:promise 参数来自 React Native,我正在尝试为 API 创建一个包装器。

在我的OnCompleteListenerLog.d事件中,它打印:

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

我的AndroidManifest.xml中确实有API密钥和所需的权限(BLUETOOTHBLUETOOTH_ADMIN(。

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

解决了!背景

reactContext.getApplicationContext()

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

getCurrentActivity()

这是基类ReactContextBaseJavaModule中的方法。

最新更新