您收到此错误是因为您没有明确向用户询问权限,您必须这样做才能使用 Nearby API。这是执行此操作的一种方法:
// GoogleApiClient connection callback. Initiate permission check here.
@Override
public void onConnected(Bundle connectionHint) {
Nearby.Messages.getPermissionStatus(mGoogleApiClient).setResultCallback(
new ErrorCheckingCallback("getPermissionStatus", new Runnable() {
@Override
public void run() {
publishAndSubscribe();
}
})
);
}
// This is called in response to a button tap in the Nearby permission dialog.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
// Permission granted or error resolved successfully then we proceed
// with publish or subscribe..
publishAndSubscribe();
} else {
// This may mean that user had rejected to grant nearby permission.
showToast("Failed to resolve error with code " + resultCode);
}
}
}
/**
* A simple ResultCallback that displays a toast when errors occur.
* It also displays the Nearby opt-in dialog when necessary.
*/
private class ErrorCheckingCallback implements ResultCallback<Status> {
private final String method;
private final Runnable runOnSuccess;
private ErrorCheckingCallback(String method) {
this(method, null);
}
private ErrorCheckingCallback(String method, @Nullable Runnable runOnSuccess) {
this.method = method;
this.runOnSuccess = runOnSuccess;
}
@Override
public void onResult(@NonNull Status status) {
if (status.isSuccess()) {
Log.i(TAG, method + " succeeded.");
if (runOnSuccess != null) {
runOnSuccess.run();
}
} else {
// Currently, the only resolvable error is that the device is not opted
// in to Nearby. Starting the resolution displays an opt-in dialog.
if (status.hasResolution()) {
if (!mResolvingError) {
try {
status.startResolutionForResult(MainActivity.this,
REQUEST_RESOLVE_ERROR);
mResolvingError = true;
} catch (IntentSender.SendIntentException e) {
showToastAndLog(Log.ERROR, method + " failed with exception: " + e);
}
} else {
// This will be encountered on initial startup because we do
// both publish and subscribe together. So having a toast while
// resolving dialog is in progress is confusing, so just log it.
Log.i(TAG, method + " failed with status: " + status
+ " while resolving error.");
}
} else {
showToastAndLog(Log.ERROR, method + " failed with : " + status
+ " resolving error: " + mResolvingError);
}
}
}
}
您可以在文档中找到完整的示例。
另外,请记住指南:
不要让用户感到惊讶。要求用户执行明确的操作(点击按钮、转到应用程序中的某个部分、特殊开关等)以激活附近。
在 iOS 和 Android 上,第一次调用 Nearby 会触发权限对话框。在调用 Nearby 之前等待明确的用户操作将有助于用户将对话框上下文化并将其与您的应用程序的基于邻近的功能相关联。