【问题标题】:Is it possible to publish messages using Google Nearby Messages in the background in Android?是否可以在 Android 的后台使用 Google Nearby Messages 发布消息?
【发布时间】:2017-09-12 15:40:30
【问题描述】:

我正在开发一个应用程序,它使用 Google Nearby Messages API 发布消息和订阅。文档说 因为 Nearby Messages API 可能会影响电池寿命,所以它们只能在前台活动中使用( BLE 后台订阅除外)。

但还有可能吗?

以及使用什么策略来达到最大距离?

谢谢。

【问题讨论】:

    标签: android google-nearby


    【解决方案1】:

    回答你的问题,on the official documentation

    示例GitHub Google

    谷歌解决方案

    // Subscribe to messages in the background.
    private void backgroundSubscribe() {
        Log.i(TAG, "Subscribing for background updates.");
        SubscribeOptions options = new SubscribeOptions.Builder()
                .setStrategy(Strategy.BLE_ONLY)
                .build();
        Nearby.getMessagesClient(this).subscribe(getPendingIntent(), options);
    }
    
    private PendingIntent getPendingIntent() {
        return PendingIntent.getBroadcast(this, 0, new Intent(this, BeaconMessageReceiver.class),
                PendingIntent.FLAG_UPDATE_CURRENT);
    }
    

    以下代码 sn-p 演示了在 BeaconMessageReceiver 类中处理 Intent。

    @Override
    public void onReceive(Context context, Intent intent) {
        Nearby.getMessagesClient(context).handleIntent(intent, new MessageListener() {
            @Override
            public void onFound(Message message) {
                Log.i(TAG, "Found message via PendingIntent: " + message);
            }
    
            @Override
            public void onLost(Message message) {
                Log.i(TAG, "Lost message via PendingIntent: " + message);
            }
        });
    }
    

    当不再需要订阅时,您的应用应通过调用 Nearby.getMessagesClient(Activity).unsubscribe(PendingIntent) 来取消订阅。

    使用 BLE 的解决方案

    SubscribeOptions.Builder builder = new SubscribeOptions.Builder();
    
    if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        builder.setStrategy(Strategy.BLE_ONLY);
    } else {
        builder.setStrategy(new Strategy.Builder().setDistanceType(Strategy.DISTANCE_TYPE_EARSHOT).build());
        Toast.makeText(this, "BLE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
    }
    
    mOptions = builder.build();
    

    发布

    Strategy s = new Strategy.Builder()
                        .setDistanceType(Strategy.DISTANCE_TYPE_EARSHOT)
                        .build();
    PublishOptions options = new PublishOptions.Builder()
                                    .setStrategy(s)
                                    .build();
    Nerby.getMessagesClient(this).publish(mMessageName, options);
    

    【讨论】:

      猜你喜欢
      • 2015-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多