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

The following examples show how to use com.google.android.gms.tasks.Task#addOnSuccessListener() . 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: Fido2DemoActivity.java    From security-samples with Apache License 2.0 6 votes vote down vote up
private void sendRegisterRequestToClient(PublicKeyCredentialCreationOptions options) {
    Fido2ApiClient fido2ApiClient = Fido.getFido2ApiClient(this.getApplicationContext());

    Task<Fido2PendingIntent> result = fido2ApiClient.getRegisterIntent(options);

    result.addOnSuccessListener(
            new OnSuccessListener<Fido2PendingIntent>() {
                @Override
                public void onSuccess(Fido2PendingIntent fido2PendingIntent) {
                    if (fido2PendingIntent.hasPendingIntent()) {
                        try {
                            fido2PendingIntent.launchPendingIntent(
                                    Fido2DemoActivity.this, REQUEST_CODE_REGISTER);
                            Log.i(TAG, "Register request is sent out");
                        } catch (IntentSender.SendIntentException e) {
                            Log.e(TAG, "Error launching pending intent for register request", e);
                        }
                    }
                }
            });
}
 
Example 2
Source File: Fido2DemoActivity.java    From android-fido with Apache License 2.0 6 votes vote down vote up
private void sendRegisterRequestToClient(PublicKeyCredentialCreationOptions options) {
    Fido2ApiClient fido2ApiClient = Fido.getFido2ApiClient(this.getApplicationContext());

    Task<Fido2PendingIntent> result = fido2ApiClient.getRegisterIntent(options);

    result.addOnSuccessListener(
            new OnSuccessListener<Fido2PendingIntent>() {
                @Override
                public void onSuccess(Fido2PendingIntent fido2PendingIntent) {
                    if (fido2PendingIntent.hasPendingIntent()) {
                        try {
                            fido2PendingIntent.launchPendingIntent(
                                    Fido2DemoActivity.this, REQUEST_CODE_REGISTER);
                            Log.i(TAG, "Register request is sent out");
                        } catch (IntentSender.SendIntentException e) {
                            Log.e(TAG, "Error launching pending intent for register request", e);
                        }
                    }
                }
            });
}
 
Example 3
Source File: AndroidUtilities.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
public static void setWaitingForSms(boolean value) {
    synchronized (smsLock) {
        waitingForSms = value;
        try {
            if (waitingForSms) {
                SmsRetrieverClient client = SmsRetriever.getClient(ApplicationLoader.applicationContext);
                Task<Void> task = client.startSmsRetriever();
                task.addOnSuccessListener(aVoid -> {
                    if (BuildVars.DEBUG_VERSION) {
                        FileLog.d("sms listener registered");
                    }
                });
            }
        } catch (Throwable e) {
            FileLog.e(e);
        }
    }
}
 
Example 4
Source File: FeedBackActivity.java    From Google-Hosts with Apache License 2.0 6 votes vote down vote up
private void submitFeedbackData() {
    //记录当前时间
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
    String currentDate = dateFormat.format(new Date());
    //创建数据对象
    FeedbackInfo feedbackInfo = new FeedbackInfo(mContent.getEditText().getText().toString(),
            mAddress.getEditText().getText().toString());
    Log.i(TAG, "开始提交数据");
    //开始提交数据
    Task<Void> voidTask = myRef.child(currentDate).setValue(feedbackInfo);
    voidTask.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.i(TAG, "数据提交提交成功");
        }
    });
    //结束当前界面
    finish();
    //提示信息
    Toast.makeText(getApplicationContext(), "您的反馈已经提交\n感谢您的支持", Toast.LENGTH_LONG).show();
}
 
Example 5
Source File: WearableMainActivity.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
private void addLocationEntry(double latitude, double longitude) {
    if (!mGpsPermissionApproved) {
        return;
    }
    mCalendar.setTimeInMillis(System.currentTimeMillis());
    LocationEntry entry = new LocationEntry(mCalendar, latitude, longitude);
    String path = Constants.PATH + "/" + mCalendar.getTimeInMillis();
    PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(path);
    putDataMapRequest.getDataMap().putDouble(Constants.KEY_LATITUDE, entry.latitude);
    putDataMapRequest.getDataMap().putDouble(Constants.KEY_LONGITUDE, entry.longitude);
    putDataMapRequest.getDataMap()
            .putLong(Constants.KEY_TIME, entry.calendar.getTimeInMillis());
    PutDataRequest request = putDataMapRequest.asPutDataRequest();
    request.setUrgent();

    Task<DataItem> dataItemTask =
            Wearable.getDataClient(getApplicationContext()).putDataItem(request);

    dataItemTask.addOnSuccessListener(dataItem -> {
        Log.d(TAG, "Data successfully sent: " + dataItem.toString());
    });
    dataItemTask.addOnFailureListener(exception -> {
        Log.e(TAG, "AddPoint:onClick(): Failed to set the data, "
                + "exception: " + exception);
    });
}
 
Example 6
Source File: ConfigCacheClient.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Reimplementation of {@link Tasks#await(Task, long, TimeUnit)} because that method has a
 * precondition that fails when run on the main thread.
 *
 * <p>This blocking method is required because the current FRC API has synchronous getters that
 * read from a cache that is loaded from disk. In other words, the synchronous methods rely on an
 * async task, so the getters have to block at some point.
 *
 * <p>Until the next breaking change in the API, this use case must be implemented, even though it
 * is against Android best practices.
 */
private static <TResult> TResult await(Task<TResult> task, long timeout, TimeUnit unit)
    throws ExecutionException, InterruptedException, TimeoutException {
  AwaitListener<TResult> waiter = new AwaitListener<>();

  task.addOnSuccessListener(DIRECT_EXECUTOR, waiter);
  task.addOnFailureListener(DIRECT_EXECUTOR, waiter);
  task.addOnCanceledListener(DIRECT_EXECUTOR, waiter);

  if (!waiter.await(timeout, unit)) {
    throw new TimeoutException("Task await timed out.");
  }

  if (task.isSuccessful()) {
    return task.getResult();
  } else {
    throw new ExecutionException(task.getException());
  }
}
 
Example 7
Source File: RecipeActivity.java    From search-samples with Apache License 2.0 6 votes vote down vote up
private void indexNote() {
    Note note = mRecipe.getNote();
    Indexable noteToIndex = Indexables.noteDigitalDocumentBuilder()
            .setName(mRecipe.getTitle() + " Note")
            .setText(note.getText())
            .setUrl(mRecipe.getNoteUrl())
            .build();

    Task<Void> task = FirebaseAppIndex.getInstance().update(noteToIndex);
    // [START_EXCLUDE]
    task.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "App Indexing API: Successfully added note to index");
        }
    });

    task.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            Log.e(TAG, "App Indexing API: Failed to add note to index. " + exception
                    .getMessage());
        }
    });
    // [END_EXCLUDE]
}
 
Example 8
Source File: Fido2DemoActivity.java    From android-fido with Apache License 2.0 6 votes vote down vote up
private void sendSignRequestToClient(PublicKeyCredentialRequestOptions options) {
    Fido2ApiClient fido2ApiClient = Fido.getFido2ApiClient(this.getApplicationContext());

    Task<Fido2PendingIntent> result = fido2ApiClient.getSignIntent(options);

    result.addOnSuccessListener(
            new OnSuccessListener<Fido2PendingIntent>() {
                @Override
                public void onSuccess(Fido2PendingIntent fido2PendingIntent) {
                    if (fido2PendingIntent.hasPendingIntent()) {
                        try {
                            fido2PendingIntent.launchPendingIntent(Fido2DemoActivity.this, REQUEST_CODE_SIGN);
                        } catch (IntentSender.SendIntentException e) {
                            Log.e(TAG, "Error launching pending intent for sign request", e);
                        }
                    }
                }
            });
}
 
Example 9
Source File: MainActivity.java    From location-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Removes activity recognition updates using
 * {@link ActivityRecognitionClient#removeActivityUpdates(PendingIntent)}. Registers success and
 * failure callbacks.
 */
public void removeActivityUpdatesButtonHandler(View view) {
    Task<Void> task = mActivityRecognitionClient.removeActivityUpdates(
            getActivityDetectionPendingIntent());
    task.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void result) {
            Toast.makeText(mContext,
                    getString(R.string.activity_updates_removed),
                    Toast.LENGTH_SHORT)
                    .show();
            setUpdatesRequestedState(false);
            // Reset the display.
            mAdapter.updateActivities(new ArrayList<DetectedActivity>());
        }
    });

    task.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.w(TAG, "Failed to enable activity recognition.");
            Toast.makeText(mContext, getString(R.string.activity_updates_not_removed),
                    Toast.LENGTH_SHORT).show();
            setUpdatesRequestedState(true);
        }
    });
}
 
Example 10
Source File: CreateGroupChatActivity.java    From NaviBee with GNU General Public License v3.0 5 votes vote down vote up
public void submit(){
    setSubmitting(true);
    EditText editText = findViewById(R.id.activity_createGroupChat_group_name);
    String groupName = editText.getText().toString();

    String groupCreator = FirebaseAuth.getInstance().getCurrentUser().getUid();
    ArrayList<String> selectedUidList = new ArrayList<>();

    CoordinatorLayout c = findViewById(R.id.chat_createGroup_coordinator);

    for (String uid: selectedFriendMap.keySet()){
        if (selectedFriendMap.get(uid)){
            selectedUidList.add(uid);
        }
    }
    if (selectedUidList.size() < 1){
        Snackbar.make(c, R.string.chat_group_create_friend_required, Snackbar.LENGTH_SHORT).show();
        setSubmitting(false);
    } else {
        selectedUidList.add(groupCreator);
        Task<HttpsCallableResult> createGroupTask = cm.createGroupChat(selectedUidList, groupName, "1");

        createGroupTask.addOnFailureListener(httpsCallableResult -> {
            Snackbar.make(c, R.string.error_failed_to_connect_to_server, Snackbar.LENGTH_SHORT).show();
            setSubmitting(false);
        });
        createGroupTask.addOnSuccessListener(httpsCallableResult -> {
            this.finish();
            setSubmitting(false);
        });
    }
}
 
Example 11
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 12
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 13
Source File: MainActivity.java    From wear-os-samples with Apache License 2.0 5 votes vote down vote up
/** Find the connected nodes that provide at least one of the given capabilities. */
private void showNodes(final String... capabilityNames) {

    Task<Map<String, CapabilityInfo>> capabilitiesTask =
            Wearable.getCapabilityClient(this)
                    .getAllCapabilities(CapabilityClient.FILTER_REACHABLE);

    capabilitiesTask.addOnSuccessListener(
            new OnSuccessListener<Map<String, CapabilityInfo>>() {
                @Override
                public void onSuccess(Map<String, CapabilityInfo> capabilityInfoMap) {
                    Set<Node> nodes = new HashSet<>();

                    if (capabilityInfoMap.isEmpty()) {
                        showDiscoveredNodes(nodes);
                        return;
                    }
                    for (String capabilityName : capabilityNames) {
                        CapabilityInfo capabilityInfo = capabilityInfoMap.get(capabilityName);
                        if (capabilityInfo != null) {
                            nodes.addAll(capabilityInfo.getNodes());
                        }
                    }
                    showDiscoveredNodes(nodes);
                }
            });
}
 
Example 14
Source File: UpdateService.java    From wear-os-samples with Apache License 2.0 5 votes vote down vote up
private void removeWearableData(Uri dataItemUri) {

        Task<Integer> dataDeleteTask =
                Wearable.getDataClient(getApplicationContext()).deleteDataItems(dataItemUri);

        dataDeleteTask.addOnSuccessListener(getIntegerOnSuccessListener());
        dataDeleteTask.addOnFailureListener(getOnFailureListener(dataItemUri));
    }
 
Example 15
Source File: PlaceAndPhotoTestActivity.java    From android-places-demos with Apache License 2.0 4 votes vote down vote up
/**
 * Fetches a Bitmap using the Places API and displays it.
 *
 * @param photoMetadata from a {@link Place} instance.
 */
private void fetchPhoto(PhotoMetadata photoMetadata) {
  photo = photoMetadata;

  photoView.setImageBitmap(null);
  setLoading(true);

  String customPhotoReference = getCustomPhotoReference();
  if (!TextUtils.isEmpty(customPhotoReference)) {
    photoMetadata = PhotoMetadata.builder(customPhotoReference).build();
  }

  FetchPhotoRequest.Builder photoRequestBuilder = FetchPhotoRequest.builder(photoMetadata);

  Integer maxWidth = readIntFromTextView(R.id.photo_max_width);
  if (maxWidth != null) {
    photoRequestBuilder.setMaxWidth(maxWidth);
  }

  Integer maxHeight = readIntFromTextView(R.id.photo_max_height);
  if (maxHeight != null) {
    photoRequestBuilder.setMaxHeight(maxHeight);
  }

  Task<FetchPhotoResponse> photoTask = placesClient.fetchPhoto(photoRequestBuilder.build());

  photoTask.addOnSuccessListener(
      response -> {
        Bitmap bitmap = response.getBitmap();
        photoView.setImageBitmap(bitmap);
        StringUtil.prepend(responseView, StringUtil.stringify(bitmap));
      });

  photoTask.addOnFailureListener(
      exception -> {
        exception.printStackTrace();
        StringUtil.prepend(responseView, "Photo: " + exception.getMessage());
      });

  photoTask.addOnCompleteListener(response -> setLoading(false));
}
 
Example 16
Source File: WhereAmIActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 4 votes vote down vote up
@Override
protected void onStart() {
  super.onStart();

  // Check if we have permission to access high accuracy fine location.
  int permission = ActivityCompat.checkSelfPermission(this,
    ACCESS_FINE_LOCATION);

  // If permission is granted, fetch the last location.
  if (permission == PERMISSION_GRANTED) {
    getLastLocation();
  } else {
    // If permission has not been granted, request permission.
    ActivityCompat.requestPermissions(this,
      new String[]{ACCESS_FINE_LOCATION},
      LOCATION_PERMISSION_REQUEST);
  }

  // Check of the location settings are compatible with our Location Request.
  LocationSettingsRequest.Builder builder =
    new LocationSettingsRequest.Builder()
      .addLocationRequest(mLocationRequest);

  SettingsClient client = LocationServices.getSettingsClient(this);

  Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
  task.addOnSuccessListener(this,
    new OnSuccessListener<LocationSettingsResponse>() {
      @Override
      public void onSuccess(LocationSettingsResponse
                              locationSettingsResponse) {
        // Location settings satisfy the requirements of the Location Request.
        // Request location updates.
        requestLocationUpdates();
      }
    });

  task.addOnFailureListener(this, new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
      // Extract the status code for the failure from within the Exception.
      int statusCode = ((ApiException) e).getStatusCode();

      switch (statusCode) {
        case CommonStatusCodes.RESOLUTION_REQUIRED:
          try {
            // Display a user dialog to resolve the location settings
            // issue.
            ResolvableApiException resolvable = (ResolvableApiException) e;
            resolvable.startResolutionForResult(WhereAmIActivity.this,
              REQUEST_CHECK_SETTINGS);
          } catch (IntentSender.SendIntentException sendEx) {
            Log.e(TAG, "Location Settings resolution failed.", sendEx);
          }
          break;
        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
          // Location settings issues can't be resolved by user.
          // Request location updates anyway.
          Log.d(TAG, "Location Settings can't be resolved.");
          requestLocationUpdates();
          break;
      }
    }
  });
}
 
Example 17
Source File: SamLocationRequestService.java    From SamLocationAndGeocoding with MIT License 4 votes vote down vote up
private void setGoogleClient(){

            mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setInterval(30 * 1000);
            mLocationRequest.setFastestInterval(5 * 1000);
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(mLocationRequest);

            //**************************
            builder.setAlwaysShow(true); //this is the key ingredient
            //**************************

            Task<LocationSettingsResponse> result =
                    LocationServices.getSettingsClient(context).checkLocationSettings( builder.build());

            result.addOnFailureListener((Activity) context, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    int statusCode = ((ApiException) e).getStatusCode();
                    if (statusCode
                            == LocationSettingsStatusCodes
                            .RESOLUTION_REQUIRED) {
                        // Location settings are not satisfied, but this can
                        // be fixed by showing the user a dialog
                        try {
                            // Show the dialog by calling
                            // startResolutionForResult(), and check the
                            // result in onActivityResult()
                            ResolvableApiException resolvable =
                                    (ResolvableApiException) e;
                            resolvable.startResolutionForResult
                                    ((Activity) context,
                                            REQUEST_CODE);
                        } catch (IntentSender.SendIntentException sendEx) {
                            // Ignore the error
                        }
                    }
                }
            });

            result.addOnSuccessListener((Activity) context, new OnSuccessListener<LocationSettingsResponse>() {
                @Override
                public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                    startLocationUpdates();
                }
            });


    }
 
Example 18
Source File: LocationPickerActivity.java    From LocationPicker with MIT License 4 votes vote down vote up
private void showCurrentLocationOnMap(final boolean isDirectionClicked) {

        if (checkAndRequestPermissions()) {

            @SuppressLint("MissingPermission")
            Task<Location> lastLocation = fusedLocationProviderClient.getLastLocation();
            lastLocation.addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if (location != null) {
                        mMap.clear();
                        if (isDirectionClicked) {
                            currentLatitude = location.getLatitude();
                            currentLongitude = location.getLongitude();
                            //Go to Map for Directions
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(
                                    "http://maps.google.com/maps?saddr=" + currentLatitude + ", " + currentLongitude + "&daddr=" + mLatitude + ", " + mLongitude + ""));
                            LocationPickerActivity.this.startActivity(intent);
                        } else {
                            //Go to Current Location
                            mLatitude = location.getLatitude();
                            mLongitude = location.getLongitude();
                            LocationPickerActivity.this.getAddressByGeoCodingLatLng();
                        }

                    } else {
                        //Gps not enabled if loc is null
                        LocationPickerActivity.this.getSettingsLocation();
                        Toast.makeText(LocationPickerActivity.this, "Location not Available", Toast.LENGTH_SHORT).show();

                    }
                }
            });
            lastLocation.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    //If perm provided then gps not enabled
//                getSettingsLocation();
                    Toast.makeText(LocationPickerActivity.this, "Location Not Availabe", Toast.LENGTH_SHORT).show();

                }
            });
        }

    }
 
Example 19
Source File: PhoneNumberVerifier.java    From identity-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Handle action Foo in the provided background thread with the provided
 * parameters.
 */
private void startVerify(String phoneNo) {
    // Make this a foreground service
    notifyStatus(STATUS_STARTED, phoneNo);
    setVerificationState(phoneNo, false);

    // Start SMS receiver code
    Task<Void> task = smsRetrieverClient.startSmsRetriever();
    task.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            smsReceiver.setTimeout();
            notifyStatus(STATUS_REQUEST_SENT, null);
            Log.d(TAG, "SmsRetrievalResult status: Success");
            Toast.makeText(PhoneNumberVerifier.this, getString(R.string.verifier_registered),
                    Toast.LENGTH_SHORT).show();
        }
    });
    task.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.e(TAG, "SmsRetrievalResult start failed.", e);
            stopSelf();
        }
    });


    // Communicate to background servers to send SMS and get the expect OTP
    notifyStatus(STATUS_REQUESTING, phoneNo);
    api.request(phoneNo,
            new ApiHelper.RequestResponse() {
                @Override
                public void onResponse(boolean success) {
                    if (success) {
                        Toast.makeText(PhoneNumberVerifier.this,
                                getString(R.string.verifier_server_response),
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Log.e(TAG, "Unsuccessful request call.");
                        Toast.makeText(PhoneNumberVerifier.this,
                                getString(R.string.toast_unverified), Toast.LENGTH_LONG).show();
                        stopSelf();
                    }
                }
            }, new ApiHelper.ApiError() {
                @Override
                public void onError(VolleyError error) {
                    // Do something else.
                    Log.d(TAG, "Error getting response");
                    Toast.makeText(PhoneNumberVerifier.this,
                            getString(R.string.toast_request_error), Toast.LENGTH_LONG).show();
                    stopSelf();
                }
            });
}
 
Example 20
Source File: LocationGetLocationActivity.java    From coursera-android with MIT License 4 votes vote down vote up
private void continueAcquiringLocations() {

        // Start location services
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(POLLING_FREQ);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(mLocationRequest);

        // Used if needed to turn on settings related to location services
        SettingsClient client = LocationServices.getSettingsClient(this);
        Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
        task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
            @Override
            public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                // All location settings are satisfied. The client can initialize location requests here.
                if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    mLocationCallback = getLocationCallback();
                    mLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);

                    // Schedule a runnable to stop location updates after a period of time
                    Executors.newScheduledThreadPool(1).schedule(new Runnable() {
                        @Override
                        public void run() {
                            mLocationClient.removeLocationUpdates(mLocationCallback);
                        }
                    }, MEASURE_TIME, TimeUnit.MILLISECONDS);
                }
            }
        });

        task.addOnFailureListener(this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                int statusCode = ((ApiException) e).getStatusCode();
                switch (statusCode) {
                    case CommonStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied, but this can be fixed
                        // by showing the user a dialog.
                        try {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            ResolvableApiException resolvable = (ResolvableApiException) e;
                            resolvable.startResolutionForResult(LocationGetLocationActivity.this,
                                    REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException sendEx) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way
                        // to fix the settings so we won't show the dialog.
                        break;
                }
            }
        });
    }