Java Code Examples for com.google.android.gms.tasks.Tasks#call()

The following examples show how to use com.google.android.gms.tasks.Tasks#call() . 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: DriveServiceHelper.java    From android-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Opens the file identified by {@code fileId} and returns a {@link Pair} of its name and
 * contents.
 */
public Task<Pair<String, String>> readFile(String fileId) {
    return Tasks.call(mExecutor, () -> {
            // Retrieve the metadata as a File object.
            File metadata = mDriveService.files().get(fileId).execute();
            String name = metadata.getName();

            // Stream the file contents to a String.
            try (InputStream is = mDriveService.files().get(fileId).executeMediaAsInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
                StringBuilder stringBuilder = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                String contents = stringBuilder.toString();

                return Pair.create(name, contents);
            }
        });
}
 
Example 2
Source File: GrpcCallProvider.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private void initChannelTask() {
  // We execute network initialization on a separate thread to not block operations that depend on
  // the AsyncQueue.
  this.channelTask =
      Tasks.call(
          Executors.BACKGROUND_EXECUTOR,
          () -> {
            ManagedChannel channel = initChannel(context, databaseInfo);
            asyncQueue.enqueueAndForget(() -> onConnectivityStateChange(channel));
            FirestoreGrpc.FirestoreStub firestoreStub =
                FirestoreGrpc.newStub(channel)
                    .withCallCredentials(firestoreHeaders)
                    // Ensure all callbacks are issued on the worker queue. If this call is
                    // removed, all calls need to be audited to make sure they are executed on the
                    // right thread.
                    .withExecutor(asyncQueue.getExecutor());
            callOptions = firestoreStub.getCallOptions();
            Logger.debug(LOG_TAG, "Channel successfully reset.");
            return channel;
          });
}
 
Example 3
Source File: CrashlyticsController.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private Task<Void> logAnalyticsAppExceptionEvent(long timestamp) {
  if (firebaseCrashExists()) {
    Logger.getLogger().d("Skipping logging Crashlytics event to Firebase, FirebaseCrash exists");
    return Tasks.forResult(null);
  }
  final ThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
  return Tasks.call(
      executor,
      new Callable<Void>() {
        @Override
        public Void call() throws Exception {
          final Bundle params = new Bundle();
          params.putInt(FIREBASE_CRASH_TYPE, FIREBASE_CRASH_TYPE_FATAL);
          params.putLong(FIREBASE_TIMESTAMP, timestamp);

          analyticsEventLogger.logEvent(FIREBASE_APPLICATION_EXCEPTION, params);

          return null;
        }
      });
}
 
Example 4
Source File: FirebaseRemoteConfig.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@link Task} representing the initialization status of this Firebase Remote Config
 * instance.
 */
@NonNull
public Task<FirebaseRemoteConfigInfo> ensureInitialized() {
  Task<ConfigContainer> activatedConfigsTask = activatedConfigsCache.get();
  Task<ConfigContainer> defaultsConfigsTask = defaultConfigsCache.get();
  Task<ConfigContainer> fetchedConfigsTask = fetchedConfigsCache.get();
  Task<FirebaseRemoteConfigInfo> metadataTask = Tasks.call(executor, this::getInfo);
  Task<String> installationIdTask = firebaseInstallations.getId();
  Task<InstallationTokenResult> installationTokenTask = firebaseInstallations.getToken(false);

  return Tasks.whenAllComplete(
          activatedConfigsTask,
          defaultsConfigsTask,
          fetchedConfigsTask,
          metadataTask,
          installationIdTask,
          installationTokenTask)
      .continueWith(executor, (unusedListOfCompletedTasks) -> metadataTask.getResult());
}
 
Example 5
Source File: FirebaseRemoteConfig.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Asynchronously changes the settings for this {@link FirebaseRemoteConfig} instance.
 *
 * @param settings The new settings to be applied.
 */
@NonNull
public Task<Void> setConfigSettingsAsync(@NonNull FirebaseRemoteConfigSettings settings) {
  return Tasks.call(
      executor,
      () -> {
        frcMetadata.setConfigSettings(settings);

        // Return value required; return null for Void.
        return null;
      });
}
 
Example 6
Source File: Fido2DemoActivity.java    From android-fido with Apache License 2.0 5 votes vote down vote up
private Task<String> asyncUpdateRegisterResponseToServer(
        final AuthenticatorAttestationResponse response) {
    return Tasks.call(
            THREAD_POOL_EXECUTOR,
            new Callable<String>() {
                @Override
                public String call() throws Exception {
                    gaeService = GAEService.getInstance(Fido2DemoActivity.this, googleSignInAccount);
                    return gaeService.getRegisterResponseFromServer(response);
                }
            });
}
 
Example 7
Source File: Fido2DemoActivity.java    From android-fido with Apache License 2.0 5 votes vote down vote up
private Task<PublicKeyCredentialRequestOptions> asyncGetSignRequest() {
    return Tasks.call(
            THREAD_POOL_EXECUTOR,
            new Callable<PublicKeyCredentialRequestOptions>() {
                @Override
                public PublicKeyCredentialRequestOptions call() {
                    gaeService = GAEService.getInstance(Fido2DemoActivity.this, googleSignInAccount);
                    return gaeService.getSignRequest(
                            FluentIterable.from(adapter.getCheckedItems())
                                    .transform(i -> i.get(KEY_KEY_HANDLE))
                                    .filter(i -> !Strings.isNullOrEmpty(i))
                                    .toList());
                }
            });
}
 
Example 8
Source File: Fido2DemoActivity.java    From android-fido with Apache License 2.0 5 votes vote down vote up
private Task<List<Map<String, String>>> asyncRefreshSecurityKey() {
    return Tasks.call(
            THREAD_POOL_EXECUTOR,
            new Callable<List<Map<String, String>>>() {
                @Override
                public List<Map<String, String>> call() {
                    gaeService = GAEService.getInstance(Fido2DemoActivity.this, googleSignInAccount);
                    return gaeService.getAllSecurityTokens();
                }
            });
}
 
Example 9
Source File: ConfigCacheClientTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void clear_hasOngoingGetCall_setsCacheContainerToNull() throws Exception {
  when(mockStorageClient.read()).thenReturn(configContainer);
  Tasks.call(testingThreadPool, () -> Tasks.await(cacheClient.get()));

  cacheClient.clear();

  verify(mockStorageClient).clear();

  assertThat(cacheClient.getCachedContainerTask().getResult()).isNull();
  assertThat(Tasks.await(cacheClient.get())).isNull();
}
 
Example 10
Source File: MainActivity.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
private Task<Void> writeStringToFile(final String filename, final String content) {
    return Tasks.call(
            AsyncTask.THREAD_POOL_EXECUTOR,
            new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    FileOutputStream fos = new FileOutputStream(filename, true);
                    fos.write(content.getBytes());
                    fos.close();
                    return null;
                }
            });
}
 
Example 11
Source File: RemoteConfigComponent.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/** Firebase Remote Config Component constructor for testing component logic. */
@VisibleForTesting
protected RemoteConfigComponent(
    Context context,
    ExecutorService executorService,
    FirebaseApp firebaseApp,
    FirebaseInstallationsApi firebaseInstallations,
    FirebaseABTesting firebaseAbt,
    @Nullable AnalyticsConnector analyticsConnector,
    LegacyConfigsHandler legacyConfigsHandler,
    boolean loadGetDefault) {
  this.context = context;
  this.executorService = executorService;
  this.firebaseApp = firebaseApp;
  this.firebaseInstallations = firebaseInstallations;
  this.firebaseAbt = firebaseAbt;
  this.analyticsConnector = analyticsConnector;

  this.appId = firebaseApp.getOptions().getApplicationId();

  // When the component is first loaded, it will use a cached executor.
  // The getDefault call creates race conditions in tests, where the getDefault might be executing
  // while another test has already cleared the component but hasn't gotten a new one yet.
  if (loadGetDefault) {
    // Loads the default namespace's configs from disk on App startup.
    Tasks.call(executorService, this::getDefault);
    Tasks.call(executorService, legacyConfigsHandler::saveLegacyConfigsIfNecessary);
  }
}
 
Example 12
Source File: DriveServiceHelper.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Opens the file at the {@code uri} returned by a Storage Access Framework {@link Intent}
 * created by {@link #createFilePickerIntent()} using the given {@code contentResolver}.
 */
public Task<Pair<String, String>> openFileUsingStorageAccessFramework(
        ContentResolver contentResolver, Uri uri) {
    return Tasks.call(mExecutor, () -> {
            // Retrieve the document's display name from its metadata.
            String name;
            try (Cursor cursor = contentResolver.query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    name = cursor.getString(nameIndex);
                } else {
                    throw new IOException("Empty cursor returned for file.");
                }
            }

            // Read the document's contents as a String.
            String content;
            try (InputStream is = contentResolver.openInputStream(uri);
                 BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                content = stringBuilder.toString();
            }

            return Pair.create(name, content);
        });
}
 
Example 13
Source File: Fido2DemoActivity.java    From security-samples with Apache License 2.0 5 votes vote down vote up
private Task<PublicKeyCredentialCreationOptions> asyncGetRegisterRequest() {
    return Tasks.call(
            THREAD_POOL_EXECUTOR,
            new Callable<PublicKeyCredentialCreationOptions>() {
                @Override
                public PublicKeyCredentialCreationOptions call() throws Exception {
                    gaeService = GAEService.getInstance(Fido2DemoActivity.this, googleSignInAccount);
                    return gaeService.getRegistrationRequest(
                            FluentIterable.from(adapter.getCheckedItems())
                                    .transform(i -> i.get(KEY_KEY_HANDLE))
                                    .filter(i -> !Strings.isNullOrEmpty(i))
                                    .toList());
                }
            });
}
 
Example 14
Source File: Fido2DemoActivity.java    From android-fido with Apache License 2.0 5 votes vote down vote up
private Task<String> asyncUpdateSignResponseToServer(
        final AuthenticatorAssertionResponse response) {
    return Tasks.call(
            THREAD_POOL_EXECUTOR,
            new Callable<String>() {
                @Override
                public String call() throws Exception {
                    gaeService = GAEService.getInstance(Fido2DemoActivity.this, googleSignInAccount);
                    return gaeService.getSignResponseFromServer(response);
                }
            });
}
 
Example 15
Source File: Fido2DemoActivity.java    From security-samples with Apache License 2.0 5 votes vote down vote up
private Task<String> asyncRemoveSecurityKey(final int tokenPositionInList) {
    return Tasks.call(
            THREAD_POOL_EXECUTOR,
            new Callable<String>() {
                @Override
                public String call() throws Exception {
                    gaeService = GAEService.getInstance(Fido2DemoActivity.this, googleSignInAccount);
                    return gaeService.removeSecurityKey(
                            securityTokens.get(tokenPositionInList).get(KEY_CREDENTIAL_ID));
                }
            });
}
 
Example 16
Source File: Fido2DemoActivity.java    From security-samples with Apache License 2.0 5 votes vote down vote up
private Task<List<Map<String, String>>> asyncRefreshSecurityKey() {
    return Tasks.call(
            THREAD_POOL_EXECUTOR,
            new Callable<List<Map<String, String>>>() {
                @Override
                public List<Map<String, String>> call() {
                    gaeService = GAEService.getInstance(Fido2DemoActivity.this, googleSignInAccount);
                    return gaeService.getAllSecurityTokens();
                }
            });
}
 
Example 17
Source File: Fido2DemoActivity.java    From security-samples with Apache License 2.0 5 votes vote down vote up
private Task<String> asyncUpdateSignResponseToServer(
        final AuthenticatorAssertionResponse response) {
    return Tasks.call(
            THREAD_POOL_EXECUTOR,
            new Callable<String>() {
                @Override
                public String call() throws Exception {
                    gaeService = GAEService.getInstance(Fido2DemoActivity.this, googleSignInAccount);
                    return gaeService.getSignResponseFromServer(response);
                }
            });
}
 
Example 18
Source File: Fido2DemoActivity.java    From security-samples with Apache License 2.0 5 votes vote down vote up
private Task<PublicKeyCredentialRequestOptions> asyncGetSignRequest() {
    return Tasks.call(
            THREAD_POOL_EXECUTOR,
            new Callable<PublicKeyCredentialRequestOptions>() {
                @Override
                public PublicKeyCredentialRequestOptions call() {
                    gaeService = GAEService.getInstance(Fido2DemoActivity.this, googleSignInAccount);
                    return gaeService.getSignRequest(
                            FluentIterable.from(adapter.getCheckedItems())
                                    .transform(i -> i.get(KEY_KEY_HANDLE))
                                    .filter(i -> !Strings.isNullOrEmpty(i))
                                    .toList());
                }
            });
}
 
Example 19
Source File: Fido2DemoActivity.java    From security-samples with Apache License 2.0 5 votes vote down vote up
private Task<String> asyncUpdateRegisterResponseToServer(
        final AuthenticatorAttestationResponse response) {
    return Tasks.call(
            THREAD_POOL_EXECUTOR,
            new Callable<String>() {
                @Override
                public String call() throws Exception {
                    gaeService = GAEService.getInstance(Fido2DemoActivity.this, googleSignInAccount);
                    return gaeService.getRegisterResponseFromServer(response);
                }
            });
}
 
Example 20
Source File: FirebaseInstallations.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Call to delete this Firebase app installation from the Firebase backend. This call may cause
 * Firebase Cloud Messaging, Firebase Remote Config, Firebase Predictions, or Firebase In-App
 * Messaging to not function properly.
 */
@NonNull
@Override
public Task<Void> delete() {
  return Tasks.call(backgroundExecutor, this::deleteFirebaseInstallationId);
}