Search code examples
androidgoogle-nearby

How do I get the status from the Task<Void> returned by ConnectionsClient methods?


I am using the ConnectionsClient API, including startAdvertising(), which returns a Task<Void>. The javadoc for startAdvertising() includes this statement:

Possible result status codes include:

  • STATUS_OK if advertising started successfully.
  • STATUS_ALREADY_ADVERTISING if the app is already advertising.
  • STATUS_OUT_OF_ORDER_API_CALL if the app is currently connected to remote endpoints; call stopAllEndpoints() first.

How do I get these status values after calling startAdvertising()?

I know that the Task API enables me to create an OnSuccessListener and OnFailureListener, but I want to be able to distinguish among different failure cases (specifically, STATUS_ALREADY_ADVERTISING is a benign failure). Because the type is Task<Void>, calling getResult() when it is passed to the onSuccess() method doesn't provide useful information.


Solution

  • Here's a helper method for converting a Task into a status code. This example method is blocking but it would look similar for when asynchronous. The try/catch maps directly to OnSuccessListener/OnFailureListener.

    import static com.google.android.gms.common.api.CommonStatusCodes.ERROR;
    import static com.google.android.gms.common.api.CommonStatusCodes.SUCCESS;
    
    import android.support.annotation.CheckResult;
    import com.google.android.gms.common.api.ApiException;
    import com.google.android.gms.tasks.Task;
    import com.google.android.gms.tasks.Tasks;
    import java.util.concurrent.ExecutionException;
    
    @CheckResult
    public static int waitForTask(String methodName, Task<?> task) {
      try {
        Tasks.await(task);
        return SUCCESS;
      } catch (InterruptedException | ExecutionException e) {    
        if (e instanceof InterruptedException) {
          Thread.currentThread().interrupt();
        }
    
        Exception taskException = task.getException();
        if (taskException instanceof ApiException) {
          return ((ApiException) taskException).getStatusCode();
        }
    
        return ERROR;
      }
    }