Android 谷歌在iOS和安卓系统之间发送信息

Android 谷歌在iOS和安卓系统之间发送信息,android,ios,google-nearby,Android,Ios,Google Nearby,我正试图使用谷歌附近发送消息完全使用超声波(不是BLE或WiFi)。我不知道为什么它不起作用。 我还没有找到任何额外的步骤来完成这项工作 没有错误。日志说发布是成功的。但订户根本没有反应 应用程序是否应该请求麦克风权限? 应用程序是否应该检查其他内容? iOS和Android之间是否有现成的超声波信息样本 iOS部分: @implementation ViewController { GNSMessageManager *_messageManager; } - (void)viewD

我正试图使用谷歌附近发送消息完全使用超声波(不是BLE或WiFi)。我不知道为什么它不起作用。 我还没有找到任何额外的步骤来完成这项工作

没有错误。日志说发布是成功的。但订户根本没有反应

应用程序是否应该请求麦克风权限? 应用程序是否应该检查其他内容? iOS和Android之间是否有现成的超声波信息样本

iOS部分:

@implementation ViewController {
    GNSMessageManager *_messageManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _messageManager = [[GNSMessageManager alloc]
            initWithAPIKey:@"MY_API_KEY"
               paramsBlock:^(GNSMessageManagerParams *params) {
                   params.microphonePermissionErrorHandler = ^(BOOL hasError) {
                       NSLog(@"Microphone Permission Error:%@", hasError ? @"YES" : @"NO");

                   };
                   params.bluetoothPowerErrorHandler = ^(BOOL hasError) {
                       NSLog(@"Bluetooth Power Error:%@", hasError ? @"YES" : @"NO");

                   };
                   params.bluetoothPermissionErrorHandler = ^(BOOL hasError) {
                       NSLog(@"Bluetooth Permission Error:%@", hasError ? @"YES" : @"NO");
                   };
               }];
    [GNSMessageManager setDebugLoggingEnabled:YES];
    [GNSPermission setGranted:YES];
    GNSPermission *nearbyPermission = [[GNSPermission alloc] initWithChangedHandler:^(BOOL granted) {
        NSLog(@"Nearby Permission:%@", granted ? @"YES" : @"NO");
    }];

    id <GNSSubscription> subscription = [_messageManager subscriptionWithMessageFoundHandler:^(GNSMessage *message) {
                NSLog(@"subscriptionWithMessageFoundHandler");

                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Google Nearby Message" message:[[NSString alloc] initWithData:message.content encoding:NSUTF8StringEncoding] preferredStyle:UIAlertControllerStyleAlert];
                [alertController addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil]];
                [self presentViewController:alertController animated:YES completion:nil];
            }
                                                                          messageLostHandler:^(GNSMessage *message) {
                                                                              // Remove the name from the list
                                                                          }
                                                                                 paramsBlock:^(GNSSubscriptionParams *subscriptionParams) {
                                                                                     subscriptionParams.strategy = [GNSStrategy strategyWithParamsBlock:^(GNSStrategyParams *params) {
                                                                                         params.discoveryMediums = kGNSDiscoveryMediumsAudio;
                                                                                         params.discoveryMode = kGNSDiscoveryModeScan;
                                                                                     }];
                                                                                 }
    ];


}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)publishDidClick:(id)sender {
    NSString *string = self.publisherField.text;
    if (string == nil || string.length == 0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Google Nearby" message:@"Please put some text into field before publishing" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];

    } else {
        @try {
            GNSMessage *gnsMessage = [GNSMessage messageWithContent:[string dataUsingEncoding:NSUTF8StringEncoding]];
            id <GNSPublication> publication = [_messageManager publicationWithMessage:gnsMessage
                                                                          paramsBlock:^(GNSPublicationParams *params) {
                                                                              params.strategy = [GNSStrategy strategyWithParamsBlock:^(GNSStrategyParams *params) {
                                                                                  params.discoveryMediums = kGNSDiscoveryMediumsAudio;
                                                                              }];
                                                                          }];

        }
        @catch (NSException *exception) {
            NSLog(@"Exception occurred: %@, %@", exception, [exception userInfo]);
        }
    }


}
安卓部分:

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 12341;
    private GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        View view = findViewById(R.id.button);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PublishOptions publishOptions = new PublishOptions.Builder().setStrategy(new Strategy.Builder().setDiscoveryMode(Strategy.DISCOVERY_MODE_SCAN)
                        .setDistanceType(Strategy.DISTANCE_TYPE_EARSHOT).build()).build();
                Nearby.Messages.publish(mGoogleApiClient, new Message("Hello Artur".getBytes()), publishOptions).setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(@NonNull Status status) {
                        Log.i("Nearby", status.getStatusMessage());
                    }
                });

            }
        });
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Nearby.MESSAGES_API)
                    .addConnectionCallbacks(this)
                    .enableAutoManage(this, this)
                    .build();

        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.RECORD_AUDIO},
                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        SubscribeOptions subscribeOptions = new SubscribeOptions.Builder()
                .setStrategy(new Strategy.Builder().setDiscoveryMode(Strategy.DISCOVERY_MODE_SCAN)
                        .setDistanceType(Strategy.DISTANCE_TYPE_EARSHOT).build()).build();
        Nearby.Messages.subscribe(mGoogleApiClient, new MessageListener() {
            @Override
            public void onFound(Message message) {
                super.onFound(message);
                Log.i("Nearby", "Subscribed found.");
                Toast.makeText(getApplicationContext(), new String(message.getContent()), Toast.LENGTH_LONG).show();

            }
        }, subscribeOptions).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(Status status) {
                if (status.isSuccess()) {
                    Log.i("Nearby", "Subscribed successfully.");
                } else {
                    Log.i("Nearby", "Could not subscribe.");
                    // Check whether consent was given;
                    // if not, prompt the user for consent.
                    handleUnsuccessfulNearbyResult(status);
                }
            }
        });
    }

    private void handleUnsuccessfulNearbyResult(Status status) {
        Log.i("Nearby", "Processing error, status = " + status);

    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.d("onConnectionSuspended", String.valueOf(i));
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.d("onConnectionFailed", connectionResult.getErrorMessage());

    }
}

Artur,您需要将发布对象存储在属性或ivar中。只要发布对象存在,发布就处于活动状态。要停止发布,请释放发布对象。订阅也一样


我意识到中的发布/订阅代码示例具有误导性。我会在下一个版本中修复它。

当你说它“不起作用”时,你需要更详细地解释到底什么不起作用,你会遇到什么错误,预期的结果以及会发生什么。还有问题发生在哪一行代码。@Emil你是对的。没有错误。日志说发布是成功的。但是订阅者根本没有反应。当你运行应用程序并开始发布/订阅时,你能粘贴你看到的控制台日志消息吗?您已经打开了调试日志记录,所以您应该看到类似以下内容的日志:服务器URL:。。。设备ID:@丹韦伯我添加了日志
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 12341;
    private GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        View view = findViewById(R.id.button);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PublishOptions publishOptions = new PublishOptions.Builder().setStrategy(new Strategy.Builder().setDiscoveryMode(Strategy.DISCOVERY_MODE_SCAN)
                        .setDistanceType(Strategy.DISTANCE_TYPE_EARSHOT).build()).build();
                Nearby.Messages.publish(mGoogleApiClient, new Message("Hello Artur".getBytes()), publishOptions).setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(@NonNull Status status) {
                        Log.i("Nearby", status.getStatusMessage());
                    }
                });

            }
        });
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Nearby.MESSAGES_API)
                    .addConnectionCallbacks(this)
                    .enableAutoManage(this, this)
                    .build();

        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.RECORD_AUDIO},
                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        SubscribeOptions subscribeOptions = new SubscribeOptions.Builder()
                .setStrategy(new Strategy.Builder().setDiscoveryMode(Strategy.DISCOVERY_MODE_SCAN)
                        .setDistanceType(Strategy.DISTANCE_TYPE_EARSHOT).build()).build();
        Nearby.Messages.subscribe(mGoogleApiClient, new MessageListener() {
            @Override
            public void onFound(Message message) {
                super.onFound(message);
                Log.i("Nearby", "Subscribed found.");
                Toast.makeText(getApplicationContext(), new String(message.getContent()), Toast.LENGTH_LONG).show();

            }
        }, subscribeOptions).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(Status status) {
                if (status.isSuccess()) {
                    Log.i("Nearby", "Subscribed successfully.");
                } else {
                    Log.i("Nearby", "Could not subscribe.");
                    // Check whether consent was given;
                    // if not, prompt the user for consent.
                    handleUnsuccessfulNearbyResult(status);
                }
            }
        });
    }

    private void handleUnsuccessfulNearbyResult(Status status) {
        Log.i("Nearby", "Processing error, status = " + status);

    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.d("onConnectionSuspended", String.valueOf(i));
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.d("onConnectionFailed", connectionResult.getErrorMessage());

    }
}
02-17 22:32:56.158 11325-11325/? I/Nearby: Subscribed successfully.
02-17 22:32:59.929 11325-11325/? D/NearbyMessagesClient: Emitting client lifecycle event ACTIVITY_STOPPED
02-17 22:32:59.930 11325-11325/? D/NearbyMessagesClient: Emitting client lifecycle event CLIENT_DISCONNECTED
02-17 22:33:28.890 11325-11325/? I/Nearby: Subscribed successfully.
02-17 22:33:45.867 11325-11325/? I/Nearby: SUCCESS
02-17 22:33:46.542 11325-11325/? I/Nearby: SUCCESS
02-17 22:33:47.137 11325-11325/? I/Nearby: SUCCESS
02-17 22:33:47.779 11325-11325/? I/Nearby: SUCCESS
02-17 22:33:48.422 11325-11325/? I/Nearby: SUCCESS
02-17 22:33:49.053 11325-11325/? I/Nearby: SUCCESS
02-17 22:34:18.477 11325-11325/? D/NearbyMessagesClient: Emitting client lifecycle event ACTIVITY_STOPPED
02-17 22:34:18.479 11325-11325/? D/NearbyMessagesClient: Emitting client lifecycle event CLIENT_DISCONNECTED
02-17 22:36:47.996 11325-11325/? D/NearbyMessagesClient: Failed to emit client lifecycle event ACTIVITY_STOPPED due to GmsClient being disconnected
02-17 22:36:47.997 11325-11325/? D/NearbyMessagesClient: Failed to emit client lifecycle event CLIENT_DISCONNECTED due to GmsClient being disconnected