当前位置: 首页>>代码示例>>Java>>正文


Java Tasks.await方法代码示例

本文整理汇总了Java中com.google.android.gms.tasks.Tasks.await方法的典型用法代码示例。如果您正苦于以下问题:Java Tasks.await方法的具体用法?Java Tasks.await怎么用?Java Tasks.await使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.google.android.gms.tasks.Tasks的用法示例。


在下文中一共展示了Tasks.await方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: importAccount

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
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);

}
 
开发者ID:googlesamples,项目名称:account-transfer-api,代码行数:20,代码来源:AccountTransferService.java

示例2: exportAccount

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
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;
    }
}
 
开发者ID:googlesamples,项目名称:account-transfer-api,代码行数:25,代码来源:AccountTransferService.java

示例3: getDriveFile

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
/**
 * 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;
}
 
开发者ID:ultramega,项目名称:flavordex,代码行数:27,代码来源:PhotoSyncHelper.java

示例4: createNewFile

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
/**
 * 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);
    }
}
 
开发者ID:ultramega,项目名称:flavordex,代码行数:24,代码来源:PhotoSyncHelper.java

示例5: doInBackground

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
/**
 * 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;
}
 
开发者ID:googledrive,项目名称:android-quickeditor,代码行数:30,代码来源:EditDriveFileAsyncTask.java

示例6: deleteQueryBatch

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
/**
 * 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();
}
 
开发者ID:amrro,项目名称:firestore-android-arch-components,代码行数:17,代码来源:RestaurantUtil.java

示例7: deleteQueryBatch

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
/**
 * 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();
}
 
开发者ID:btrautmann,项目名称:RxFirestore,代码行数:17,代码来源:DeleteCollectionOnSubscribe.java

示例8: setupClient

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
/**
 * 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;
}
 
开发者ID:ultramega,项目名称:flavordex,代码行数:43,代码来源:PhotoSyncHelper.java

示例9: deletePhotos

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
/**
 * 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();
        }
    }
}
 
开发者ID:ultramega,项目名称:flavordex,代码行数:42,代码来源:PhotoSyncHelper.java

示例10: loadAuthToken

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
/**
 * 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);
        }
    }
}
 
开发者ID:ultramega,项目名称:flavordex,代码行数:15,代码来源:Endpoint.java

示例11: updateRemoteDataBlocking

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
@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);
    }
}
 
开发者ID:the-blue-alliance,项目名称:the-blue-alliance-android,代码行数:13,代码来源:AppConfig.java

示例12: onHandleIntent

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
@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);
    }
}
 
开发者ID:romannurik,项目名称:muzei,代码行数:28,代码来源:ArtworkCacheIntentService.java

示例13: validateDriveIds

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
/**
 * Ensure that the local Drive IDs exists in the Drive folder.
 */
private void validateDriveIds() {
    if(mResourceClient == null || mDriveFolder == null) {
        return;
    }

    Log.d(TAG, "Validating Drive IDs.");
    final ContentResolver cr = mContext.getContentResolver();
    final String[] projection = new String[] {
            Tables.Photos._ID,
            Tables.Photos.DRIVE_ID
    };
    final String where = Tables.Photos.DRIVE_ID + " NOT NULL";
    final Cursor cursor = cr.query(Tables.Photos.CONTENT_URI, projection, where, null, null);
    if(cursor == null) {
        return;
    }
    try {
        final ArrayList<String> driveIds = new ArrayList<>();
        try {
            final MetadataBuffer buffer =
                    Tasks.await(mResourceClient.listChildren(mDriveFolder));
            for(Metadata metadata : buffer) {
                driveIds.add(metadata.getDriveId().getResourceId());
            }
            buffer.release();
        } catch(ExecutionException | InterruptedException e) {
            return;
        }

        long id;
        String driveId;
        final ContentValues values = new ContentValues();
        values.put(Tables.Photos.DRIVE_ID, (String)null);
        while(cursor.moveToNext()) {
            driveId = cursor.getString(cursor.getColumnIndex(Tables.Photos.DRIVE_ID));
            if(!driveIds.contains(driveId)) {
                id = cursor.getLong(cursor.getColumnIndex(Tables.Photos._ID));
                cr.update(ContentUris.withAppendedId(Tables.Photos.CONTENT_ID_URI_BASE, id),
                        values, null, null);
            }
        }
    } finally {
        cursor.close();
    }
}
 
开发者ID:ultramega,项目名称:flavordex,代码行数:49,代码来源:PhotoSyncHelper.java

示例14: uploadFile

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
/**
 * Upload a file to Drive if it does not already exist.
 *
 * @param uri  The Uri to the image file
 * @param hash The file hash
 * @return The DriveFile
 */
@Nullable
private DriveFile uploadFile(@NonNull Uri uri, @NonNull String hash) {
    DriveFile driveFile = getDriveFile(hash);
    if(driveFile != null) {
        return driveFile;
    }

    if(mResourceClient == null || !mShouldSync || !mMediaMounted) {
        return null;
    }

    final ContentResolver cr = mContext.getContentResolver();

    final String name = PhotoUtils.getName(cr, uri);
    if(name == null) {
        return null;
    }

    DriveContents driveContents = null;
    try {
        driveContents = Tasks.await(mResourceClient.createContents());
        final InputStream inputStream = cr.openInputStream(uri);
        if(inputStream == null) {
            return null;
        }
        final OutputStream outputStream = driveContents.getOutputStream();
        try {
            final byte[] buffer = new byte[8192];
            int read;
            while((read = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, read);
            }
        } finally {
            inputStream.close();
            outputStream.close();
        }

        createNewFile(name, hash, driveContents);

        return null;
    } catch(ExecutionException | InterruptedException | IOException e) {
        Log.w(TAG, "Upload failed", e);
    }

    if(driveContents != null) {
        mResourceClient.discardContents(driveContents);
    }
    return null;
}
 
开发者ID:ultramega,项目名称:flavordex,代码行数:57,代码来源:PhotoSyncHelper.java

示例15: downloadPhoto

import com.google.android.gms.tasks.Tasks; //导入方法依赖的package包/类
/**
 * Download a file from Drive.
 *
 * @param resourceId The Drive resource ID
 * @return The downloaded file
 */
@Nullable
private File downloadPhoto(@NonNull String resourceId) {
    if(mClient == null || mResourceClient == null || !mMediaMounted) {
        return null;
    }

    try {
        final DriveFile driveFile = Tasks.await(mClient.getDriveId(resourceId)).asDriveFile();
        final DriveContents driveContents =
                Tasks.await(mResourceClient.openFile(driveFile, DriveFile.MODE_READ_ONLY));

        final Metadata metadata = Tasks.await(mResourceClient.getMetadata(driveFile));
        final String fileName = metadata.getOriginalFilename();
        File outputFile = new File(PhotoUtils.getMediaStorageDir(), fileName);
        if(outputFile.exists()) {
            final String hash = metadata.getCustomProperties().get(sHashKey);
            if(hash != null && hash.equals(PhotoUtils.getMD5Hash(mContext.getContentResolver(),
                    Uri.fromFile(outputFile)))) {
                return outputFile;
            }
            if(!mShouldSync) {
                return null;
            }
            outputFile = getUniqueFile(outputFile);
        }
        if(!mShouldSync) {
            return null;
        }
        final OutputStream outputStream = new FileOutputStream(outputFile);
        final InputStream inputStream = driveContents.getInputStream();
        try {
            final byte[] buffer = new byte[8192];
            int read;
            while((read = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, read);
            }
        } finally {
            inputStream.close();
            outputStream.close();
        }
        return outputFile;
    } catch(ExecutionException | InterruptedException | IOException e) {
        Log.w(TAG, "Download failed", e);
    }

    return null;
}
 
开发者ID:ultramega,项目名称:flavordex,代码行数:54,代码来源:PhotoSyncHelper.java


注:本文中的com.google.android.gms.tasks.Tasks.await方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。