本文整理汇总了Java中com.google.android.gms.tasks.Tasks类的典型用法代码示例。如果您正苦于以下问题:Java Tasks类的具体用法?Java Tasks怎么用?Java Tasks使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Tasks类属于com.google.android.gms.tasks包,在下文中一共展示了Tasks类的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);
}
示例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;
}
}
示例3: setUp
import com.google.android.gms.tasks.Tasks; //导入依赖的package包/类
@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);
}
示例4: logout
import com.google.android.gms.tasks.Tasks; //导入依赖的package包/类
/**
* 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();
}
});
}
示例5: createCounter
import com.google.android.gms.tasks.Tasks; //导入依赖的package包/类
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);
}
});
}
示例6: preview
import com.google.android.gms.tasks.Tasks; //导入依赖的package包/类
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());
}
示例7: 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;
}
示例8: 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);
}
}
示例9: initializeFolderView
import com.google.android.gms.tasks.Tasks; //导入依赖的package包/类
/**
* 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);
}
示例10: start
import com.google.android.gms.tasks.Tasks; //导入依赖的package包/类
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);
}
});
}
示例11: fetchTopProvider
import com.google.android.gms.tasks.Tasks; //导入依赖的package包/类
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);
}
});
}
示例12: 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;
}
示例13: deleteCollection
import com.google.android.gms.tasks.Tasks; //导入依赖的package包/类
/**
* 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;
});
}
示例14: 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();
}
示例15: then
import com.google.android.gms.tasks.Tasks; //导入依赖的package包/类
@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);
}
}