Java Code Examples for com.google.android.gms.tasks.Task#addOnCompleteListener()

The following examples show how to use com.google.android.gms.tasks.Task#addOnCompleteListener() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CurrentPlaceTestActivity.java    From android-places-demos with Apache License 2.0 6 votes vote down vote up
/**
 * Fetches a list of {@link PlaceLikelihood} instances that represent the Places the user is
 * most
 * likely to be at currently.
 */
@RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
private void findCurrentPlaceWithPermissions() {
  setLoading(true);

  FindCurrentPlaceRequest currentPlaceRequest =
      FindCurrentPlaceRequest.newInstance(getPlaceFields());
  Task<FindCurrentPlaceResponse> currentPlaceTask =
      placesClient.findCurrentPlace(currentPlaceRequest);

  currentPlaceTask.addOnSuccessListener(
      (response) ->
          responseView.setText(StringUtil.stringify(response, isDisplayRawResultsChecked())));

  currentPlaceTask.addOnFailureListener(
      (exception) -> {
        exception.printStackTrace();
        responseView.setText(exception.getMessage());
      });

  currentPlaceTask.addOnCompleteListener(task -> setLoading(false));
}
 
Example 2
Source File: MainWearActivity.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
private void checkIfPhoneHasApp() {
    Log.d(TAG, "checkIfPhoneHasApp()");

    Task<CapabilityInfo> capabilityInfoTask = Wearable.getCapabilityClient(this)
            .getCapability(CAPABILITY_PHONE_APP, CapabilityClient.FILTER_ALL);

    capabilityInfoTask.addOnCompleteListener(new OnCompleteListener<CapabilityInfo>() {
        @Override
        public void onComplete(Task<CapabilityInfo> task) {

            if (task.isSuccessful()) {
                Log.d(TAG, "Capability request succeeded.");
                CapabilityInfo capabilityInfo = task.getResult();
                mAndroidPhoneNodeWithApp = pickBestNodeId(capabilityInfo.getNodes());

            } else {
                Log.d(TAG, "Capability request failed to return any results.");
            }

            verifyNodeAndUpdateUI();
        }
    });
}
 
Example 3
Source File: Fido2DemoActivity.java    From android-fido with Apache License 2.0 6 votes vote down vote up
private void getRegisterRequest() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS)
            == PackageManager.PERMISSION_GRANTED) {
        Log.i(TAG, "getRegisterRequest permission is granted");

        Task<PublicKeyCredentialCreationOptions> getRegisterRequestTask = asyncGetRegisterRequest();
        getRegisterRequestTask.addOnCompleteListener(
                new OnCompleteListener<PublicKeyCredentialCreationOptions>() {
                    @Override
                    public void onComplete(@NonNull Task<PublicKeyCredentialCreationOptions> task) {
                        PublicKeyCredentialCreationOptions options = task.getResult();
                        if (options == null) {
                            Log.d(TAG, "Register request is null");
                            return;
                        }
                        sendRegisterRequestToClient(options);
                    }
                });
    } else {
        Log.i(TAG, "getRegisterRequest permission is requested");
        ActivityCompat.requestPermissions(
                this,
                new String[] {Manifest.permission.GET_ACCOUNTS},
                GET_ACCOUNTS_PERMISSIONS_REQUEST_REGISTER);
    }
}
 
Example 4
Source File: MainPhoneActivity.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
private void sendMessage(DataMap dataMap) {
    Log.d(TAG, "sendMessage(): " + mWearNodeIds);

    if ((mWearNodeIds != null) && (!mWearNodeIds.isEmpty())) {
        
        Task<Integer> sendMessageTask;

        for (Node node : mWearNodeIds) {

            sendMessageTask = Wearable.getMessageClient(this).sendMessage(
                    node.getId(),
                    Constants.MESSAGE_PATH_WEAR,
                    dataMap.toByteArray());

            sendMessageTask.addOnCompleteListener(this);
        }
    } else {
        // Unable to retrieve node with proper capability
        mWearBodySensorsPermissionApproved = false;
        updateWearButtonOnUiThread();
        logToUi("Wear devices not available to send message.");
    }
}
 
Example 5
Source File: Fido2DemoActivity.java    From android-fido with Apache License 2.0 6 votes vote down vote up
private void updateRegisterResponseToServer(AuthenticatorAttestationResponse response) {
    Task<String> updateRegisterResponseToServerTask = asyncUpdateRegisterResponseToServer(response);
    updateRegisterResponseToServerTask.addOnCompleteListener(
            new OnCompleteListener<String>() {
                @Override
                public void onComplete(@NonNull Task<String> task) {
                    String securityKeyToken = task.getResult();
                    if (securityKeyToken == null) {
                        Toast.makeText(
                                Fido2DemoActivity.this,
                                "security key registration failed",
                                Toast.LENGTH_SHORT)
                                .show();
                        return;
                    }
                    updateAndDisplayRegisteredKeys();
                    Log.i(
                            TAG,
                            "Update register response to server with securityKeyToken: " + securityKeyToken);
                }
            });
}
 
Example 6
Source File: MainWearActivity.java    From wear-os-samples with Apache License 2.0 5 votes vote down vote up
private void sendMessage(DataMap dataMap) {
    Log.d(TAG, "sendMessage(): " + mPhoneNodeId);

    if (mPhoneNodeId != null) {
        // Clients are inexpensive to create, so in this case we aren't creating member variables.
        // (They are cached and shared between GoogleApi instances.)
        Task<Integer> sendMessageTask = Wearable.getMessageClient(this)
                .sendMessage(mPhoneNodeId, Constants.MESSAGE_PATH_PHONE, dataMap.toByteArray());

        sendMessageTask.addOnCompleteListener(new OnCompleteListener<Integer>() {
            @Override
            public void onComplete(Task<Integer> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "Message sent successfully");
                } else {
                    Log.d(TAG, "Message failed.");
                }
            }
        });

    } else {
        // Unable to retrieve node with proper capability
        mPhoneStoragePermissionApproved = false;
        updatePhoneButtonOnUiThread();
        logToUi("Phone not available to send message.");
    }
}
 
Example 7
Source File: PlaceAndPhotoTestActivity.java    From android-places-demos with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches the {@link Place} specified via the UI and displays it. May also trigger {@link
 * #fetchPhoto(PhotoMetadata)} if set in the UI.
 */
private void fetchPlace() {
  responseView.setText(null);
  photoView.setImageBitmap(null);
  dismissKeyboard(findViewById(R.id.place_id_field));

  final boolean isFetchPhotoChecked = isFetchPhotoChecked();
  List<Field> placeFields = getPlaceFields();
  String customPhotoReference = getCustomPhotoReference();
  if (!validateInputs(isFetchPhotoChecked, placeFields, customPhotoReference)) {
    return;
  }

  setLoading(true);

  FetchPlaceRequest request = FetchPlaceRequest.newInstance(getPlaceId(), placeFields);
  Task<FetchPlaceResponse> placeTask = placesClient.fetchPlace(request);

  placeTask.addOnSuccessListener(
      (response) -> {
        responseView.setText(StringUtil.stringify(response, isDisplayRawResultsChecked()));
        if (isFetchPhotoChecked) {
          attemptFetchPhoto(response.getPlace());
        }
      });

  placeTask.addOnFailureListener(
      (exception) -> {
        exception.printStackTrace();
        responseView.setText(exception.getMessage());
      });

  placeTask.addOnCompleteListener(response -> setLoading(false));
}
 
Example 8
Source File: CurrentPlaceActivity.java    From android-places-demos with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // [START maps_places_current_place]
    // Use fields to define the data types to return.
    List<Place.Field> placeFields = Collections.singletonList(Place.Field.NAME);

    // Use the builder to create a FindCurrentPlaceRequest.
    FindCurrentPlaceRequest request = FindCurrentPlaceRequest.newInstance(placeFields);

    // Call findCurrentPlace and handle the response (first check that the user has granted permission).
    if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        Task<FindCurrentPlaceResponse> placeResponse = placesClient.findCurrentPlace(request);
        placeResponse.addOnCompleteListener(task -> {
            if (task.isSuccessful()){
                FindCurrentPlaceResponse response = task.getResult();
                for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()) {
                    Log.i(TAG, String.format("Place '%s' has likelihood: %f",
                        placeLikelihood.getPlace().getName(),
                        placeLikelihood.getLikelihood()));
                }
            } else {
                Exception exception = task.getException();
                if (exception instanceof ApiException) {
                    ApiException apiException = (ApiException) exception;
                    Log.e(TAG, "Place not found: " + apiException.getStatusCode());
                }
            }
        });
    } else {
        // A local method to request required permissions;
        // See https://developer.android.com/training/permissions/requesting
        getLocationPermission();
    }
    // [END maps_places_current_place]
}
 
Example 9
Source File: AttendeeDetailFragment.java    From white-label-event-app with Apache License 2.0 5 votes vote down vote up
@Override
public void onStart() {
    super.onStart();

    firebaseMultiQuery = new FirebaseMultiQuery(eventRef, attendeeRef);
    final Task<Map<DatabaseReference, DataSnapshot>> allLoad = firebaseMultiQuery.start();
    allLoad.addOnCompleteListener(getActivity(), new AllOnCompleteListener());
}
 
Example 10
Source File: MainActivity.java    From identity-samples with Apache License 2.0 5 votes vote down vote up
private void fetchData() {
    // The logic can be modified according to your need.
    sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
    firstTime = sharedPreferences.getBoolean(KEY_FIRST_TIME, true);
    if (firstTime) {
        Log.v(TAG, "Fetching account info from API");
        AccountTransferClient client = AccountTransfer.getAccountTransferClient(this);
        final Task<byte[]> transferBytes = client.retrieveData(ACCOUNT_TYPE);
        transferBytes.addOnCompleteListener(this, new OnCompleteListener<byte[]>() {
            @Override
            public void onComplete(@NonNull Task<byte[]> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "Success retrieving data. Importing it.");
                    try {
                        AccountTransferUtil.importAccounts(task.getResult(), MainActivity.this);
                    } catch (JSONException e) {
                        Log.e(TAG, "Encountered failure while retrieving data", e);
                        return;
                    }
                    populateAccountTextView();
                } else {
                    // No need to notify API about failure, as it's running outside setup of
                    // device.
                    Log.e(TAG, "Encountered failure while retrieving data", task.getException());
                }
                // Don't try the next time
                sharedPreferences.edit().putBoolean(KEY_FIRST_TIME, false).apply();
            }
        });
    }
}
 
Example 11
Source File: ProfileInteractor.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public void createOrUpdateProfile(final Profile profile, final OnProfileCreatedListener onProfileCreatedListener) {
    Task<Void> task = databaseHelper
            .getDatabaseReference()
            .child(DatabaseHelper.PROFILES_DB_KEY)
            .child(profile.getId())
            .setValue(profile);
    task.addOnCompleteListener(task1 -> {
        onProfileCreatedListener.onProfileCreated(task1.isSuccessful());
        addRegistrationToken(FirebaseInstanceId.getInstance().getToken(), profile.getId());
        LogUtil.logDebug(TAG, "createOrUpdateProfile, success: " + task1.isSuccessful());
    });
}
 
Example 12
Source File: ProfileInteractor.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public void addRegistrationToken(String token, String userId) {
    Task<Void> task = databaseHelper
            .getDatabaseReference()
            .child(DatabaseHelper.PROFILES_DB_KEY)
            .child(userId).child("notificationTokens")
            .child(token).setValue(true);
    task.addOnCompleteListener(task1 -> LogUtil.logDebug(TAG, "addRegistrationToken, success: " + task1.isSuccessful()));
}
 
Example 13
Source File: FirebaseInstallationsTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAuthToken_serverError_failure() throws Exception {
  // start the test with a registered FID
  persistedInstallation.insertOrUpdatePersistedInstallationEntry(
      PersistedInstallationEntry.INSTANCE.withRegisteredFid(
          TEST_FID_1,
          TEST_REFRESH_TOKEN,
          utils.currentTimeInSecs(),
          TEST_AUTH_TOKEN,
          TEST_TOKEN_EXPIRATION_TIMESTAMP));

  // have the backend fail when generateAuthToken is invoked.
  when(mockBackend.generateAuthToken(anyString(), anyString(), anyString(), anyString()))
      .thenReturn(
          TokenResult.builder().setResponseCode(TokenResult.ResponseCode.BAD_CONFIG).build());

  // Make the forced getAuthToken call, which should fail.
  try {
    TestOnCompleteListener<InstallationTokenResult> onCompleteListener =
        new TestOnCompleteListener<>();
    Task<InstallationTokenResult> task = firebaseInstallations.getToken(true);
    task.addOnCompleteListener(executor, onCompleteListener);
    onCompleteListener.await();
    fail(
        "getAuthToken() succeeded but should have failed due to the BAD_CONFIG error "
            + "returned by the network call.");
  } catch (ExecutionException expected) {
    assertWithMessage("Exception class doesn't match")
        .that(expected)
        .hasCauseThat()
        .isInstanceOf(FirebaseInstallationsException.class);
    assertWithMessage("Exception status doesn't match")
        .that(((FirebaseInstallationsException) expected.getCause()).getStatus())
        .isEqualTo(Status.BAD_CONFIG);
  }
}
 
Example 14
Source File: AttendeesFragment.java    From white-label-event-app with Apache License 2.0 5 votes vote down vote up
@Override
public void onStart() {
    super.onStart();

    firebaseMultiQuery = new FirebaseMultiQuery(attendeesRef);
    final Task<Map<DatabaseReference, DataSnapshot>> allLoad = firebaseMultiQuery.start();
    allLoad.addOnCompleteListener(getActivity(), new AllOnCompleteListener());
}
 
Example 15
Source File: ProfileInteractor.java    From social-app-android with Apache License 2.0 5 votes vote down vote up
public void addRegistrationToken(String token, String userId) {
    Task<Void> task = databaseHelper
            .getDatabaseReference()
            .child(DatabaseHelper.PROFILES_DB_KEY)
            .child(userId).child("notificationTokens")
            .child(token).setValue(true);
    task.addOnCompleteListener(task1 -> LogUtil.logDebug(TAG, "addRegistrationToken, success: " + task1.isSuccessful()));
}
 
Example 16
Source File: AutocompleteTestActivity.java    From android-places-demos with Apache License 2.0 5 votes vote down vote up
private void findAutocompletePredictions() {
  setLoading(true);

  FindAutocompletePredictionsRequest.Builder requestBuilder =
      FindAutocompletePredictionsRequest.builder()
              .setQuery(getQuery())
              .setCountries(getCountries())
              .setOrigin((getOrigin()))
              .setLocationBias(getLocationBias())
              .setLocationRestriction(getLocationRestriction())
              .setTypeFilter(getTypeFilter());

  if (isUseSessionTokenChecked()) {
    requestBuilder.setSessionToken(AutocompleteSessionToken.newInstance());
  }

  Task<FindAutocompletePredictionsResponse> task =
      placesClient.findAutocompletePredictions(requestBuilder.build());

  task.addOnSuccessListener(
      (response) ->
          responseView.setText(StringUtil.stringify(response, isDisplayRawResultsChecked())));

  task.addOnFailureListener(
      (exception) -> {
        exception.printStackTrace();
        responseView.setText(exception.getMessage());
      });

  task.addOnCompleteListener(response -> setLoading(false));
}
 
Example 17
Source File: FirebaseAuthManager.java    From Android-MVP-vs-MVVM-Samples with Apache License 2.0 4 votes vote down vote up
public final void signInWithEmailAndPassword(final @NonNull String email, final @NonNull String password, final @Nullable OnCompleteListener<AuthResult> onCompleteListener) {
    final Task<AuthResult> resultTask = mAuth.signInWithEmailAndPassword(email, password);
    if (onCompleteListener != null) {
        resultTask.addOnCompleteListener(onCompleteListener);
    }
}
 
Example 18
Source File: FirebaseAuthManager.java    From Android-MVP-vs-MVVM-Samples with Apache License 2.0 4 votes vote down vote up
public final void createUserWithEmailAndPassword(final @NonNull String email, final @NonNull String password, final @Nullable OnCompleteListener<AuthResult> onCompleteListener) {
    final Task<AuthResult> resultTask = mAuth.createUserWithEmailAndPassword(email, password);
    if (onCompleteListener != null) {
        resultTask.addOnCompleteListener(onCompleteListener);
    }
}
 
Example 19
Source File: ProfileInteractor.java    From social-app-android with Apache License 2.0 4 votes vote down vote up
public void removeRegistrationToken(String token, String userId) {
    DatabaseReference databaseReference = ApplicationHelper.getDatabaseHelper().getDatabaseReference();
    DatabaseReference tokenRef = databaseReference.child(DatabaseHelper.PROFILES_DB_KEY).child(userId).child("notificationTokens").child(token);
    Task<Void> task = tokenRef.removeValue();
    task.addOnCompleteListener(task1 -> LogUtil.logDebug(TAG, "removeRegistrationToken, success: " + task1.isSuccessful()));
}
 
Example 20
Source File: ProfileInteractor.java    From social-app-android with Apache License 2.0 4 votes vote down vote up
public void removeRegistrationToken(String token, String userId) {
    DatabaseReference databaseReference = ApplicationHelper.getDatabaseHelper().getDatabaseReference();
    DatabaseReference tokenRef = databaseReference.child(DatabaseHelper.PROFILES_DB_KEY).child(userId).child("notificationTokens").child(token);
    Task<Void> task = tokenRef.removeValue();
    task.addOnCompleteListener(task1 -> LogUtil.logDebug(TAG, "removeRegistrationToken, success: " + task1.isSuccessful()));
}