Java 类com.google.android.gms.tasks.Tasks 实例源码

项目:account-transfer-api    文件:AccountTransferService.java   
private void importAccount() {
    // Handle to client object
    AccountTransferClient client = AccountTransfer.getAccountTransferClient(this);

    // Make RetrieveData api call to get the transferred over data.
    Task<byte[]> transferTask = client.retrieveData(ACCOUNT_TYPE);
    try {
        byte[] transferBytes = Tasks.await(transferTask, TIMEOUT_API, TIME_UNIT);
        AccountTransferUtil.importAccounts(transferBytes, this);
    } catch (ExecutionException | InterruptedException | TimeoutException | JSONException e) {
        Log.e(TAG, "Exception while calling importAccounts()", e);
        client.notifyCompletion(
                ACCOUNT_TYPE, AuthenticatorTransferCompletionStatus.COMPLETED_FAILURE);
        return;
    }
    client.notifyCompletion(
            ACCOUNT_TYPE, AuthenticatorTransferCompletionStatus.COMPLETED_SUCCESS);

}
项目:account-transfer-api    文件:AccountTransferService.java   
private void exportAccount() {
    Log.d(TAG, "exportAccount()");
    byte[] transferBytes = AccountTransferUtil.getTransferBytes(this);
    AccountTransferClient client = AccountTransfer.getAccountTransferClient(this);
    if (transferBytes == null) {
        Log.d(TAG, "Nothing to export");
        // Notifying is important.
        client.notifyCompletion(
                ACCOUNT_TYPE, AuthenticatorTransferCompletionStatus.COMPLETED_SUCCESS);
        return;
    }

    // Send the data over to the other device.
    Task<Void> exportTask = client.sendData(ACCOUNT_TYPE, transferBytes);
    try {
        Tasks.await(exportTask, TIMEOUT_API, TIME_UNIT);
    } catch (ExecutionException | InterruptedException | TimeoutException e) {
        Log.e(TAG, "Exception while calling exportAccounts()", e);
        // Notifying is important.
        client.notifyCompletion(
                ACCOUNT_TYPE, AuthenticatorTransferCompletionStatus.COMPLETED_FAILURE);
        return;
    }
}
项目:digits-migration-helper-android    文件:AuthMigratorTest.java   
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    when(mockStorageHelpers.getApiKeyFromManifest(any(Context.class), eq(StorageHelpers
            .DIGITS_CONSUMER_KEY_KEY))).thenReturn(DIGITS_CONSUMER_KEY);
    when(mockStorageHelpers.getApiKeyFromManifest(any(Context.class), eq(StorageHelpers
            .DIGITS_CONSUMER_SECRET_KEY))).thenReturn(DIGITS_CONSUMER_SECRET);
    when(mockStorageHelpers.getApiKeyFromManifest(any(Context.class), eq(StorageHelpers
            .FABRIC_API_KEY_KEY))).thenReturn(FABRIC_API_KEY);
    authResult = new AuthResult() {
        @Override
        public FirebaseUser getUser() {
            return mockFirebaseUser;
        }

        @Override
        public AdditionalUserInfo getAdditionalUserInfo() {
            return null;
        }
    };

    authResultTask = Tasks.forResult(authResult);
}
项目:stitch-android-sdk    文件:StitchClient.java   
/**
 * Logs out the current user.
 *
 * @return A task that can be resolved upon completion of logout.
 */
public Task<Void> logout() {
    if (!isAuthenticated()) {
        return Tasks.forResult(null);
    }
    return executeRequest(Request.Method.DELETE, routes.AUTH_SESSION, null, false, true).continueWith(new Continuation<String, Void>() {
        @Override
        public Void then(@NonNull final Task<String> task) throws Exception {
            if (task.isSuccessful()) {
                clearAuth();
                return null;
            }
            throw task.getException();
        }
    });
}
项目:snippets-android    文件:SolutionCounters.java   
public Task<Void> createCounter(final DocumentReference ref, final int numShards) {
    // Initialize the counter document, then initialize each shard.
    return ref.set(new Counter(numShards))
            .continueWithTask(new Continuation<Void, Task<Void>>() {
                @Override
                public Task<Void> then(@NonNull Task<Void> task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }

                    List<Task<Void>> tasks = new ArrayList<>();

                    // Initialize each shard with count=0
                    for (int i = 0; i < numShards; i++) {
                        Task<Void> makeShard = ref.collection("shards")
                                .document(String.valueOf(i))
                                .set(new Shard(0));

                        tasks.add(makeShard);
                    }

                    return Tasks.whenAll(tasks);
                }
            });
}
项目:StraaS-android-sdk-sample    文件:MainActivity.java   
private Task<CameraController> preview() {
    if (mStreamManager != null && mStreamManager.getStreamState() == StreamManager.STATE_IDLE) {
        return mStreamManager.prepare(getConfig(), mTextureView)
                .addOnCompleteListener(this, new OnCompleteListener<CameraController>() {
                    @Override
                    public void onComplete(@NonNull Task<CameraController> task) {
                        if (task.isSuccessful()) {
                            Log.d(TAG, "Prepare succeeds");
                            mCameraController = task.getResult();
                            enableAllButtons();
                        } else {
                            Log.e(TAG, "Prepare fails " + task.getException());
                        }
                    }
                });
    }
    return Tasks.forException(new IllegalStateException());
}
项目:flavordex    文件:PhotoSyncHelper.java   
/**
 * Get a file from the Drive folder.
 *
 * @param hash The file hash
 * @return The DriveFile or null if it doesn't exist.
 */
@Nullable
private DriveFile getDriveFile(@NonNull String hash) {
    if(mResourceClient == null || mDriveFolder == null) {
        return null;
    }

    try {
        final Query query = new Query.Builder().addFilter(Filters.eq(sHashKey, hash)).build();
        final MetadataBuffer buffer =
                Tasks.await(mResourceClient.queryChildren(mDriveFolder, query));
        if(buffer != null && buffer.getCount() > 0) {
            final DriveFile driveFile = buffer.get(0).getDriveId().asDriveFile();
            buffer.release();
            return driveFile;
        }
    } catch(ExecutionException | InterruptedException ignored) {
    }

    return null;
}
项目:flavordex    文件:PhotoSyncHelper.java   
/**
 * Create a new file on Drive.
 *
 * @param title    The name of the file
 * @param hash     The file hash
 * @param contents The file content
 */
private void createNewFile(@NonNull String title, @NonNull String hash,
                           @NonNull DriveContents contents) {
    if(mResourceClient == null || mDriveFolder == null) {
        return;
    }
    final MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
            .setTitle(title)
            .setCustomProperty(sHashKey, hash).build();
    final ExecutionOptions options = new ExecutionOptions.Builder()
            .setNotifyOnCompletion(true).build();
    try {
        Tasks.await(mResourceClient.createFile(mDriveFolder, changeSet, contents, options));
    } catch(ExecutionException | InterruptedException e) {
        Log.w(TAG, "Failed to create remote file", e);
    }
}
项目:android-trash    文件:MainActivity.java   
/**
 * Initializes the folder view after the given task completes.
 *
 * @return Task which resolves after the view has been initialized
 */
private Task<Void> initializeFolderView() {
    Task<DriveFolder> folderTask;
    if (mNavigationPath.isEmpty()) {
        folderTask = mDriveResourceClient.getRootFolder();
    } else {
        folderTask = Tasks.forResult(mNavigationPath.peek().asDriveFolder());
    }
    Task<Void> initFolderTask = folderTask.continueWith(new Continuation<DriveFolder, Void>() {
        @Override
        public Void then(@NonNull Task<DriveFolder> task) throws Exception {
            DriveId id = task.getResult().getDriveId();
            if (mNavigationPath.isEmpty()) {
                mNavigationPath.push(id);
            }
            return null;
        }
    });
    return updateUiAfterTask(initFolderTask);
}
项目:white-label-event-app    文件:FirebaseMultiQuery.java   
public Task<Map<DatabaseReference, DataSnapshot>> start() {
    // Create a Task<DataSnapshot> to trigger in response to each database listener.
    //
    final ArrayList<Task<DataSnapshot>> tasks = new ArrayList<>(refs.size());
    for (final DatabaseReference ref : refs) {
        final TaskCompletionSource<DataSnapshot> source = new TaskCompletionSource<>();
        final ValueEventListener listener = new MyValueEventListener(ref, source);
        ref.addListenerForSingleValueEvent(listener);
        listeners.put(ref, listener);
        tasks.add(source.getTask());
    }

    // Return a single Task that triggers when all queries are complete.  It contains
    // a map of all original DatabaseReferences originally given here to their resulting
    // DataSnapshot.
    //
    return Tasks.whenAll(tasks).continueWith(new Continuation<Void, Map<DatabaseReference, DataSnapshot>>() {
        @Override
        public Map<DatabaseReference, DataSnapshot> then(@NonNull Task<Void> task) throws Exception {
            task.getResult();
            return new HashMap<>(snaps);
        }
    });
}
项目:FirebaseUI-Android    文件:ProviderUtils.java   
public static Task<String> fetchTopProvider(FirebaseAuth auth, @NonNull String email) {
    if (TextUtils.isEmpty(email)) {
        return Tasks.forException(new NullPointerException("Email cannot be empty"));
    }

    return auth.fetchProvidersForEmail(email)
            .continueWith(new Continuation<ProviderQueryResult, String>() {
                @Override
                public String then(@NonNull Task<ProviderQueryResult> task) {
                    if (!task.isSuccessful()) return null;

                    List<String> providers = task.getResult().getProviders();
                    return providers == null || providers.isEmpty()
                            ? null : providers.get(providers.size() - 1);
                }
            });
}
项目:android-quickeditor    文件:EditDriveFileAsyncTask.java   
/**
 * Opens contents for the given file, executes the editing tasks, saves the
 * metadata and content changes.
 */
@Override
protected Boolean doInBackground(DriveId... params) {
    DriveFile file = params[0].asDriveFile();
    try {
        DriveContents contents =
            Tasks.await(driveResourceClient.openFile(file, DriveFile.MODE_WRITE_ONLY));

        Changes changes = edit(contents);
        MetadataChangeSet changeSet = changes.getMetadataChangeSet();
        DriveContents updatedContents = changes.getDriveContents();

        if (changeSet != null) {
            Tasks.await(driveResourceClient.updateMetadata(file, changeSet));
        }

        if (updatedContents != null) {
            Tasks.await(driveResourceClient.commitContents(updatedContents, changeSet));
        }
    } catch (ExecutionException | InterruptedException e) {
        Log.e(TAG, "Error editing DriveFile.", e);
        return false;
    }

    return true;
}
项目:firestore-android-arch-components    文件:RestaurantUtil.java   
/**
 * Delete all documents in a collection. Uses an Executor to perform work on a background
 * thread. This does *not* automatically discover and delete subcollections.
 */
private static Task<Void> deleteCollection(final CollectionReference collection,
                                           final int batchSize,
                                           Executor executor) {

    // Perform the delete operation on the provided Executor, which allows us to use
    // simpler synchronous logic without blocking the main thread.
    return Tasks.call(executor, () -> {
        // Get the first batch of documents in the collection
        Query query = collection.orderBy("__name__").limit(batchSize);

        // Get a list of deleted documents
        List<DocumentSnapshot> deleted = deleteQueryBatch(query);

        // While the deleted documents in the last batch indicate that there
        // may still be more documents in the collection, page down to the
        // next batch and delete again
        while (deleted.size() >= batchSize) {
            // Move the query cursor to start after the last doc in the batch
            DocumentSnapshot last = deleted.get(deleted.size() - 1);
            query = collection.orderBy("__name__")
                    .startAfter(last.getId())
                    .limit(batchSize);

            deleted = deleteQueryBatch(query);
        }

        return null;
    });

}
项目:firestore-android-arch-components    文件:RestaurantUtil.java   
/**
 * Delete all results from a query in a single WriteBatch. Must be run on a worker thread
 * to avoid blocking/crashing the main thread.
 */
@WorkerThread
private static List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception {
    QuerySnapshot querySnapshot = Tasks.await(query.get());

    WriteBatch batch = query.getFirestore().batch();
    for (DocumentSnapshot snapshot : querySnapshot) {
        batch.delete(snapshot.getReference());
    }
    Tasks.await(batch.commit());

    return querySnapshot.getDocuments();
}
项目:digits-migration-helper-android    文件:AuthMigrator.java   
@Override
public Task<Void> then(@NonNull Task<AuthResult> task) throws Exception {
    if(task.isSuccessful()) {
        return VOID_TASK;
    }
    try {
        throw task.getException();
    } catch (Exception e) {
        return Tasks.forException(e);
    }
}
项目:digits-migration-helper-android    文件:AuthMigratorTest.java   
@Test
public void migrateAndClear_badSessionResponse() throws JSONException {
    Task<AuthResult> task = Tasks.forException(new FirebaseWebRequestException("msg", 400));

    when(mockStorageHelpers.getDigitsSessionJson()).thenReturn(VALID_DIGITS_SESSION);
    when(mockStorageHelpers.getUnsignedJWT(mjsonCaptor.capture())).thenReturn(DIGITS_JWT);
    when(mockFirebaseAuth.signInWithCustomToken(DIGITS_JWT)).thenReturn(task);
    AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers,
            mockFirebaseAuth);
    assertFalse(authMigrator.migrate(true).isSuccessful());
    verify(mockFirebaseAuth).signInWithCustomToken(DIGITS_JWT);
    verify(mockStorageHelpers).clearDigitsSession();
    checkCompleteJsonObject(mjsonCaptor.getValue());
}
项目:digits-migration-helper-android    文件:AuthMigratorTest.java   
@Test
public void migrateAndClear_unauthorizedSessionResponse() throws JSONException {
    Task<AuthResult> task = Tasks.forException(new FirebaseWebRequestException("msg", 403));

    when(mockStorageHelpers.getDigitsSessionJson()).thenReturn(VALID_DIGITS_SESSION);
    when(mockStorageHelpers.getUnsignedJWT(mjsonCaptor.capture())).thenReturn(DIGITS_JWT);
    when(mockFirebaseAuth.signInWithCustomToken(DIGITS_JWT)).thenReturn(task);
    AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers,
            mockFirebaseAuth);
    assertFalse(authMigrator.migrate(true).isSuccessful());
    verify(mockFirebaseAuth).signInWithCustomToken(DIGITS_JWT);
    verify(mockStorageHelpers).clearDigitsSession();
    checkCompleteJsonObject(mjsonCaptor.getValue());
}
项目:digits-migration-helper-android    文件:AuthMigratorTest.java   
@Test
public void migrateAndKeep_unauthorizedSessionResponse() throws JSONException {
    Task<AuthResult> task = Tasks.forException(new FirebaseWebRequestException("msg", 403));

    when(mockStorageHelpers.getDigitsSessionJson()).thenReturn(VALID_DIGITS_SESSION);
    when(mockStorageHelpers.getUnsignedJWT(mjsonCaptor.capture())).thenReturn(DIGITS_JWT);
    when(mockFirebaseAuth.signInWithCustomToken(DIGITS_JWT)).thenReturn(task);
    AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers,
            mockFirebaseAuth);
    assertFalse(authMigrator.migrate(false).isSuccessful());
    verify(mockFirebaseAuth).signInWithCustomToken(DIGITS_JWT);
    verify(mockStorageHelpers, times(0)).clearDigitsSession();
    checkCompleteJsonObject(mjsonCaptor.getValue());
}
项目:RxFirestore    文件:DeleteCollectionOnSubscribe.java   
/**
 * Delete all results from a query in a single WriteBatch. Must be run on a worker thread
 * to avoid blocking/crashing the main thread.
 */
@WorkerThread
private List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception {
    QuerySnapshot querySnapshot = Tasks.await(query.get());

    WriteBatch batch = query.getFirestore().batch();
    for (DocumentSnapshot snapshot : querySnapshot) {
        batch.delete(snapshot.getReference());
    }
    Tasks.await(batch.commit());

    return querySnapshot.getDocuments();
}
项目:android-fido    文件:U2FDemoActivity.java   
private Task<RegisterRequestParams> asyncGetRegisterRequest(final Boolean allowReregistration) {
    return Tasks.call(THREAD_POOL_EXECUTOR, new Callable<RegisterRequestParams>() {
        @Override
        public RegisterRequestParams call() throws Exception {
            gaeService = GAEService.getInstance(U2FDemoActivity.this, mGoogleSignInAccount);
            return gaeService.getRegistrationRequest(allowReregistration);
        }
    });
}
项目:android-fido    文件:U2FDemoActivity.java   
private Task<String> asyncUpdateRegisterResponseToServer(
    final RegisterResponseData registerResponseData) {
    return Tasks.call(THREAD_POOL_EXECUTOR, new Callable<String>() {
        @Override
        public String call() throws Exception {
            gaeService = GAEService.getInstance(U2FDemoActivity.this, mGoogleSignInAccount);
            return gaeService.getRegisterResponseFromServer(registerResponseData);
        }
    });
}
项目:android-fido    文件:U2FDemoActivity.java   
private Task<SignRequestParams> asyncGetSignRequest() {
    return Tasks.call(THREAD_POOL_EXECUTOR, new Callable<SignRequestParams>() {
        @Override
        public SignRequestParams call() throws Exception {
            gaeService = GAEService.getInstance(U2FDemoActivity.this, mGoogleSignInAccount);
            return gaeService.getSignRequest();
        }
    });
}
项目:android-fido    文件:U2FDemoActivity.java   
private Task<String> asyncUpdateSignResponseToServer(final SignResponseData signResponseData) {
    return Tasks.call(THREAD_POOL_EXECUTOR, new Callable<String>() {
        @Override
        public String call() throws Exception {
            gaeService = GAEService.getInstance(U2FDemoActivity.this, mGoogleSignInAccount);
            return gaeService.getSignResponseFromServer(signResponseData);
        }
    });
}
项目:android-fido    文件:U2FDemoActivity.java   
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(U2FDemoActivity.this, mGoogleSignInAccount);
            return gaeService.getAllSecurityTokens();
        }
    });
}
项目:android-fido    文件:U2FDemoActivity.java   
private Task<String> asyncRemoveSecurityKey(final int tokenPositionInList) {
    return Tasks.call(THREAD_POOL_EXECUTOR, new Callable<String>() {
        @Override
        public String call() {
            gaeService = GAEService.getInstance(U2FDemoActivity.this, mGoogleSignInAccount);
            return gaeService.removeSecurityKey(securityTokens.get(tokenPositionInList)
                .get(KEY_PUB_KEY));
        }
    });
}
项目:snippets-android    文件:DocSnippets.java   
/**
 * Delete all documents in a collection. Uses an Executor to perform work on a background
 * thread. This does *not* automatically discover and delete subcollections.
 */
private Task<Void> deleteCollection(final CollectionReference collection,
                                    final int batchSize,
                                    Executor executor) {

    // Perform the delete operation on the provided Executor, which allows us to use
    // simpler synchronous logic without blocking the main thread.
    return Tasks.call(executor, new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            // Get the first batch of documents in the collection
            Query query = collection.orderBy(FieldPath.documentId()).limit(batchSize);

            // Get a list of deleted documents
            List<DocumentSnapshot> deleted = deleteQueryBatch(query);

            // While the deleted documents in the last batch indicate that there
            // may still be more documents in the collection, page down to the
            // next batch and delete again
            while (deleted.size() >= batchSize) {
                // Move the query cursor to start after the last doc in the batch
                DocumentSnapshot last = deleted.get(deleted.size() - 1);
                query = collection.orderBy(FieldPath.documentId())
                        .startAfter(last.getId())
                        .limit(batchSize);

                deleted = deleteQueryBatch(query);
            }

            return null;
        }
    });

}
项目:snippets-android    文件:DocSnippets.java   
/**
 * Delete all results from a query in a single WriteBatch. Must be run on a worker thread
 * to avoid blocking/crashing the main thread.
 */
@WorkerThread
private List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception {
    QuerySnapshot querySnapshot = Tasks.await(query.get());

    WriteBatch batch = query.getFirestore().batch();
    for (DocumentSnapshot snapshot : querySnapshot) {
        batch.delete(snapshot.getReference());
    }
    Tasks.await(batch.commit());

    return querySnapshot.getDocuments();
}
项目:android-instant-apps-demo    文件:FirebaseRequestHandler.java   
@Override
public Result load(Request request, int networkPolicy) throws IOException {
    Log.i(TAG, "load " + request.uri.toString());
    StorageReference gsReference = firebaseStorage.getReferenceFromUrl(request.uri.toString());
    StreamDownloadTask mStreamTask = gsReference.getStream();

    InputStream inputStream;
    try {
        inputStream = Tasks.await(mStreamTask).getStream();
        return new Result(BitmapFactory.decodeStream(inputStream), Picasso.LoadedFrom.NETWORK);
    } catch (ExecutionException | InterruptedException e) {
        throw new IOException(e);
    }
}
项目:quickstart-android    文件:RestaurantUtil.java   
/**
 * Delete all documents in a collection. Uses an Executor to perform work on a background
 * thread. This does *not* automatically discover and delete subcollections.
 */
private static Task<Void> deleteCollection(final CollectionReference collection,
                                           final int batchSize,
                                           Executor executor) {

    // Perform the delete operation on the provided Executor, which allows us to use
    // simpler synchronous logic without blocking the main thread.
    return Tasks.call(executor, new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            // Get the first batch of documents in the collection
            Query query = collection.orderBy("__name__").limit(batchSize);

            // Get a list of deleted documents
            List<DocumentSnapshot> deleted = deleteQueryBatch(query);

            // While the deleted documents in the last batch indicate that there
            // may still be more documents in the collection, page down to the
            // next batch and delete again
            while (deleted.size() >= batchSize) {
                // Move the query cursor to start after the last doc in the batch
                DocumentSnapshot last = deleted.get(deleted.size() - 1);
                query = collection.orderBy("__name__")
                        .startAfter(last.getId())
                        .limit(batchSize);

                deleted = deleteQueryBatch(query);
            }

            return null;
        }
    });

}
项目:quickstart-android    文件:RestaurantUtil.java   
/**
 * Delete all results from a query in a single WriteBatch. Must be run on a worker thread
 * to avoid blocking/crashing the main thread.
 */
@WorkerThread
private static List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception {
    QuerySnapshot querySnapshot = Tasks.await(query.get());

    WriteBatch batch = query.getFirestore().batch();
    for (DocumentSnapshot snapshot : querySnapshot) {
        batch.delete(snapshot.getReference());
    }
    Tasks.await(batch.commit());

    return querySnapshot.getDocuments();
}
项目:BookJobs    文件:FirebaseImageLoader.java   
@Override
public InputStream loadData(Priority priority) throws Exception {
    mStreamTask = mRef.getStream();
    mInputStream = Tasks.await(mStreamTask).getStream();

    return mInputStream;
}
项目:flavordex    文件:PhotoSyncHelper.java   
/**
 * Set up the Drive API client.
 *
 * @param prefs The SharedPreferences
 * @return Whether the setup was successful
 */
private boolean setupClient(@NonNull SharedPreferences prefs) {
    final GoogleSignInOptions signInOptions =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestScopes(Drive.SCOPE_APPFOLDER)
                    .build();
    final GoogleSignInClient signInClient = GoogleSignIn.getClient(mContext, signInOptions);
    try {
        final GoogleSignInAccount signInAccount = Tasks.await(signInClient.silentSignIn());

        mClient = Drive.getDriveClient(mContext, signInAccount);
        mResourceClient = Drive.getDriveResourceClient(mContext, signInAccount);

        Log.d(TAG, "Connection successful. sync: " + mShouldSync + " media: " + mMediaMounted);

        return true;
    } catch(ExecutionException e) {
        final ApiException result = (ApiException)e.getCause();
        switch(result.getStatusCode()) {
            case GoogleSignInStatusCodes.SIGN_IN_REQUIRED:
            case GoogleSignInStatusCodes.INVALID_ACCOUNT:
                Log.i(TAG, "User not signed in. Disabling photo syncing.");
                prefs.edit().putBoolean(FlavordexApp.PREF_SYNC_PHOTOS, false).apply();
                break;
            case GoogleSignInStatusCodes.API_NOT_CONNECTED:
            case GoogleSignInStatusCodes.NETWORK_ERROR:
            case GoogleSignInStatusCodes.INTERNAL_ERROR:
                Log.i(TAG, "Google Drive service unavailable. Disabling photo syncing.");
                prefs.edit().putBoolean(FlavordexApp.PREF_SYNC_PHOTOS, false).apply();
        }

        Log.w(TAG, "Connection failed! Reason: " + result.getMessage());
    } catch(InterruptedException ignored) {
    }

    return false;
}
项目:flavordex    文件:PhotoSyncHelper.java   
/**
 * Delete photos from Drive that were removed from the app.
 */
void deletePhotos() {
    if(mResourceClient == null) {
        return;
    }

    Log.d(TAG, "Deleting photos.");
    final ContentResolver cr = mContext.getContentResolver();
    final String[] projection = new String[] {
            Tables.Deleted._ID,
            Tables.Deleted.UUID
    };
    final String where = Tables.Deleted.TYPE + " = " + Tables.Deleted.TYPE_PHOTO;
    final Cursor cursor = cr.query(Tables.Deleted.CONTENT_URI, projection, where, null, null);
    if(cursor != null) {
        try {
            DriveFile driveFile;
            long id;
            String hash;
            while(cursor.moveToNext()) {
                hash = cursor.getString(cursor.getColumnIndex(Tables.Deleted.UUID));
                driveFile = getDriveFile(hash);
                if(driveFile == null) {
                    continue;
                }

                try {
                    Tasks.await(mResourceClient.delete(driveFile));
                } catch(ExecutionException | InterruptedException e) {
                    continue;
                }
                id = cursor.getLong(cursor.getColumnIndex(Tables.Deleted._ID));
                cr.delete(Tables.Deleted.CONTENT_URI, Tables.Deleted._ID + " = " + id, null);
            }
        } finally {
            cursor.close();
        }
    }
}
项目:flavordex    文件:Endpoint.java   
/**
 * Load the user's auth token if it is available.
 */
private void loadAuthToken() {
    final FirebaseUser auth = FirebaseAuth.getInstance().getCurrentUser();
    if(auth != null) {
        try {
            final GetTokenResult result = Tasks.await(auth.getIdToken(true));
            mAuthToken = result.getToken();
        } catch(ExecutionException | InterruptedException e) {
            Log.e(TAG, "Failed to obtain authorization token", e);
        }
    }
}
项目:DietDiaryApp    文件:DriveBackupService.java   
private void createNewDriveBackup() {
    final Task<DriveFolder> appFolderTask = getmDriveResourceClient().getAppFolder();
    final Task<DriveContents> createContentsTask = getmDriveResourceClient().createContents();
    Tasks.whenAll(appFolderTask, createContentsTask)
            .continueWithTask(new Continuation<Void, Task<DriveFile>>() {
                @Override
                public Task<DriveFile> then(@NonNull Task<Void> task) throws Exception {
                    Log.d(TAG, "Creating drive file... ");

                    DriveContents driveContents = createContentsTask.getResult();

                    writeBackupToOutputStream(driveContents.getOutputStream());

                    MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                            .setTitle(BACKUP_FILE_NAME_COMPRESSED)
                            .setMimeType("application/zip")
                            .setCustomProperty(DRIVE_KEY_APP_ID, mAppId)
                            .setCustomProperty(DRIVE_KEY_DEVICE_NAME, DeviceName.getDeviceName())
                            .build();

                    return getmDriveResourceClient().createFile(appFolderTask.getResult(), metadataChangeSet, driveContents);
                }
            })
            .addOnSuccessListener(new OnSuccessListener<DriveFile>() {
                @Override
                public void onSuccess(DriveFile driveFile) {
                    mDriveId = driveFile.getDriveId().encodeToString();
                    Log.d(TAG, "Drive file created " + mDriveId);

                    finishJob(true);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.e(TAG, "Error while trying to create file.", e);
                    finishJob();
                }
            });
}
项目:FirebaseUI-Android    文件:CredentialSignInHandlerTest.java   
@Test
@Config(shadows = {AuthHelperShadow.class})
public void testSignInSucceeded() {
    AppCompatBase mockActivity = mock(AppCompatBase.class);
    IdpResponse idpResponse =
            new IdpResponse.Builder(
                    new User.Builder(GoogleAuthProvider.PROVIDER_ID, TestConstants.EMAIL)
                            .build())
                    .setToken(TestConstants.TOKEN)
                    .build();
    SaveSmartLock smartLock = mock(SaveSmartLock.class);
    CredentialSignInHandler credentialSignInHandler = new CredentialSignInHandler(
            mockActivity,
            smartLock,
            RC_ACCOUNT_LINK,
            idpResponse);

    when(mockActivity.getFlowParams()).thenReturn(
            TestHelper.getFlowParameters(Collections.<String>emptyList()));
    credentialSignInHandler.onComplete(Tasks.forResult(FakeAuthResult.INSTANCE));

    ArgumentCaptor<SaveSmartLock> smartLockCaptor = ArgumentCaptor.forClass(SaveSmartLock.class);
    ArgumentCaptor<FirebaseUser> firebaseUserCaptor = ArgumentCaptor.forClass(FirebaseUser.class);
    ArgumentCaptor<IdpResponse> idpResponseCaptor = ArgumentCaptor.forClass(IdpResponse.class);

    verify(mockActivity).saveCredentialsOrFinish(
            smartLockCaptor.capture(),
            firebaseUserCaptor.capture(),
            idpResponseCaptor.capture());

    assertEquals(smartLock, smartLockCaptor.getValue());
    assertEquals(TestConstants.EMAIL,
            firebaseUserCaptor.getValue().getEmail());

    IdpResponse response = idpResponseCaptor.getValue();
    assertEquals(idpResponse.getProviderType(), response.getProviderType());
    assertEquals(idpResponse.getEmail(), response.getEmail());
    assertEquals(idpResponse.getIdpToken(), response.getIdpToken());
    assertEquals(idpResponse.getIdpSecret(), response.getIdpSecret());
}
项目:FirebaseUI-Android    文件:AutoCompleteTask.java   
@NonNull
@Override
public <TContinuationResult> Task<TContinuationResult> continueWith(
        @NonNull Continuation<TResult, TContinuationResult> continuation) {
    try {
        return Tasks.forResult(continuation.then(Tasks.forResult(mResult)));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:FirebaseUI-Android    文件:AutoCompleteTask.java   
@NonNull
@Override
public <TContinuationResult> Task<TContinuationResult> continueWithTask(
        @NonNull Continuation<TResult, Task<TContinuationResult>> continuation) {
    try {
        return continuation.then(Tasks.forResult(mResult));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:the-blue-alliance-android    文件:AppConfig.java   
@WorkerThread
public void updateRemoteDataBlocking() throws ExecutionException, InterruptedException {
    updateDataInternal(null);
    if (mActiveTask != null) {
        Tasks.await(mActiveTask);
    }

    // Wait for the onCompleteHandler to finish
    while (mActiveTask != null) {
        Thread.sleep(100);
    }
}
项目:muzei    文件:ArtworkCacheIntentService.java   
@Override
protected void onHandleIntent(Intent intent) {
    boolean foundArtwork = false;
    DataClient dataClient = Wearable.getDataClient(this);
    // Read all DataItems
    try {
        DataItemBuffer dataItemBuffer = Tasks.await(dataClient.getDataItems());
        Iterator<DataItem> dataItemIterator = dataItemBuffer.singleRefIterator();
        while (dataItemIterator.hasNext()) {
            DataItem dataItem = dataItemIterator.next();
            foundArtwork = foundArtwork || processDataItem(dataClient, dataItem);
        }
        dataItemBuffer.release();
    } catch (ExecutionException|InterruptedException e) {
        Log.e(TAG, "Error getting all data items", e);
    }
    if (foundArtwork) {
        // Enable the Full Screen Activity and Artwork Complication Provider Service only if we've found artwork
        enableComponents(FullScreenActivity.class, ArtworkComplicationProviderService.class);
    }
    if (!foundArtwork && intent != null &&
            intent.getBooleanExtra(SHOW_ACTIVATE_NOTIFICATION_EXTRA, false)) {
        ActivateMuzeiIntentService.maybeShowActivateMuzeiNotification(this);
    } else {
        ActivateMuzeiIntentService.clearNotifications(this);
    }
}