如何在此代码段中添加成功和失败处理程序?

时间:2018-11-17 18:25:54

标签: android

我正在使用附近的示例应用程序中的代码段:

public void startAdvertising() {
    // Note: Advertising may fail. To keep this demo simple, we don't handle failures.
    connectionsClient.startAdvertising(
            "Tester", getPackageName(), connectionLifecycleCallback,
            new AdvertisingOptions.Builder().setStrategy(STRATEGY).build());
}

如何更改此代码,使其具有“成功”和“失败”处理程序,如附近的网站所示:

private void startAdvertising() {
  Nearby.getConnectionsClient(context).startAdvertising(
          getUserNickname(),
          SERVICE_ID,
          mConnectionLifecycleCallback,
          new AdvertisingOptions(STRATEGY))
      .addOnSuccessListener(
        new OnSuccessListener<Void>() {
          @Override
          public void onSuccess(Void unusedResult) {
            // We're advertising!
          }
        })
      .addOnFailureListener(
        new OnFailureListener() {
          @Override
          public void onFailure(@NonNull Exception e) {
            // We were unable to start advertising.
          }
        });
  }

我不知道如何更改第一个代码片段以使其像第二个代码一样工作,因为看起来网站中使用的代码略有不同(也许是较旧的API?),所以我不知道如何使它起作用,以便我开始做广告,而且还添加成功/失败处理程序

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

connectionsClient.startAdvertising(
        "Tester", getPackageName(), connectionLifecycleCallback,
        new AdvertisingOptions.Builder().setStrategy(STRATEGY).build())
    .addOnSuccessListener(
        new OnSuccessListener < Void > () {
            @Override
            public void onSuccess(Void aVoid) {
                Log.i(TAG, "OnSuccess...");
            }
        }
    )
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.e(TAG, "OnFailure 1");
            e.printStackTrace();
        }
    });