Android google task service

The Tasks API

Starting with Google Play services version 9.0.0, you can use a Task API and a number of methods that return Task or its subclasses. Task is an API that represents asynchronous method calls, similar to PendingResult in previous versions of Google Play services.

Handling task results

To be notified when the task succeeds, attach an OnSuccessListener :

To be notified when the task fails, attach an OnFailureListener :

To handle success and failure in the same listener, attach an OnCompleteListener :

Threading

Listeners attached to a thread are run on the application main (UI) thread by default. When attaching a listener, you can also specify an Executor that is used to schedule listeners.

Activity-scoped listeners

If you are listening for task results in an Activity , you may want to add activity-scoped listeners to the task. These listeners are removed during the onStop method of your Activity so that your listeners are not called when the Activity is no longer visible.

Chaining

If you use multiple APIs that return Task , you can chain them together using a continuation. This helps avoid deeply nested callbacks and consolidates error handling for chains of tasks.

For example, the method doSomething returns a Task but requires an AuthResult , which we will get asynchronously from a task:

Using the Task.continueWithTask method, we can chain these two tasks:

Blocking

If your program is already executing in a background thread you can block a task to get the result synchronously and avoid callbacks:

You can also specify a timeout when blocking a task so that your application does not hang:

Interoperability

A Task aligns conceptually to several popular Android approaches to managing asynchronous code, and a Task can be straightforwardly converted to other primitives, including the ListenableFuture and Kotlin coroutines, which are recommended by AndroidX.

Here’s an example using a Task :

Kotlin Coroutine

Usage

Add the following dependency to your project and use the code below to convert from a Task .

Gradle (module-level build.gradle , usually app/build.gradle )
Snippet

Guava ListenableFuture

Add the following dependency to your project and use the code below to convert from a Task .

Gradle (module-level build.gradle , usually app/build.gradle )
Snippet

RxJava2 Observable

Add the following dependency, in addition to the relative async library of choice, to your project and use the code below to convert from a Task .

Gradle (module-level build.gradle , usually app/build.gradle )
Snippet

Next steps

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Читайте также:  Что значит com android incallui

Источник

Google Задачи 2021.10.25

Google Задачи — поможет вам держать все дела под контролем. Создавайте и редактируйте списки дел на компьютере или мобильном устройстве. Все ваши задачи синхронизируются и остаются доступными всегда и везде, где бы вы ни находились. Интеграция с Gmail и Google Календарем ещё больше упрощает создание и отслеживание задач.

Быстрое создание задач

  • Создавайте списки задач и следите за их выполнением.
  • Работайте со списками задач с любого устройства.
  • Управляйте задачами, созданными в Gmail и Календаре, на мобильном устройстве.

Заметки к задачам и подзадачи

  • Создавайте подзадачи, чтобы список был более детальным.
  • Добавляйте заметки к задачам, чтобы ничего не забыть.
  • Редактируйте заметки по мере выполнения задач.

Задачи из писем

  • Создавайте задачи прямо из писем в Gmail.
  • Просматривайте задачи на боковой панели в Gmail.
  • Находите письма, на основе которых созданы задачи.

Сроки и напоминания

  • Задавайте срок выполнения каждой задачи.
  • Систематизируйте задачи по дате или приоритету, перетаскивая их в списке.
  • Получайте напоминания о задачах, когда подходит их срок.

Часть пакета G Suite

  • Полный набор мощных инструментов от Google для вашего бизнеса.
  • Технологии Google на базе искусственного интеллекта для сбора статистики и анализа данных, доступные вашему персоналу.
  • Инструменты для организации командной работы: Gmail, Задачи, Календарь и многое другое.

Установите приложение «Google Задачи», чтобы взять все под контроль. Работайте со списками дел в специальном инструменте от Google.

Источник

Use Tasks API on Android

Warning: This document is deprecated. For information about authorizing Android apps using OAuth 2.0 please have a look at the Android Play Services Authorization documentation.

This document explains how to use the Tasks API with OAuth 2.0 on Android. It describes the authorization mechanisms to gain access to a user’s Google Tasks and how you can have a ready to use Tasks API service Object in your Android application.

Importing Google’s client library

The samples you will find in this document use the Google APIs client library for Java. You will need to add the following jars to your Android application, to do that, place the jars listed below in the /assets folder at the root of your android application. Also check for new versions as this document gets older.

Import the Google APIs client library jars and its Android extensions (all part of google-api-java-client-1.4.1-beta.zip):

  • google-api-client-1.4.1-beta.jar
  • google-api-client-extensions-android2-1.4.1-beta.jar
  • google-api-client-googleapis-1.4.1-beta.jar
  • google-api-client-googleapis-extensions-android2-1.4.1-beta.jar

Import dependencies (all part of google-api-java-client-1.4.1-beta.zip):

  • commons-codec-1.3.jar
  • gson-1.6.jar
  • guava-r09.jar
  • httpclient-4.0.3.jar
  • httpcore-4.0.1.jar
  • jackson-core-asl-1.6.7.jar
  • jsr305-1.3.9.jar

Google accounts in Android

Since Android 2.0, the AccountManager manages the accounts that you have registered in your environment, the ones that are listed under Settings > Accounts & sync. Specifically, it handles the authorization flow and can generate authorization tokens that are required to access data using APIs.

Читайте также:  Пиксельные стрелялки для андроид

In order to be able to use the AccountManager to get accounts and to request authorization tokens you need to add the following permissions in your Android application manifest:

You can use the AccountManager to get the Google account which you want to access the Tasks for. The AccountManager not only manages Google accounts but also accounts from other vendors. Therefore you will need to specifically ask for Google accounts by using the code below:

Alternatively the Google APIs client library for Java comes with a GoogleAccountManager which only handles Google accounts:

If more than one Google accounts are available on the Android device you should prompt the user for the account he wishes to use with a dialog that could look like this:

You could build such a dialog by using the following switch/case code in the onCreateDialog method of your activity:

Calling showDialog(DIALOG_ACCOUNTS) will display the account chooser dialog.

The Google APIs authorization flow on Android

Now that the user has chosen an account we can ask the AccountManager to issue an OAuth 2.0 access token for the Task API. This is done by calling the AccountManager.getAuthToken() method. During the AccountManager.getAuthToken() call the AccountManager will take care of contacting the Google APIs authorization endpoint. When the AccountManager has retrieved the authorization token it will run the AccountManagerCallback that you have defined in the method call:

As you may already know the Android AccountManager has experimental support for OAuth 2.0. You just need to prefix the scope of the API you want to access with oauth2: when setting the AUTH_TOKEN_TYPE . So for the Tasks API you can use:

The problem when using the value above as the AUTH_TOKEN_TYPE is that the string oauth2:https://www.googleapis.com/auth/tasks will be displayed in the authorization dialog as the name of the Google product you want to access. To work around this, special — human-readable — AUTH_TOKEN_TYPE aliases exists for the Tasks API. They are equivalent to using the OAuth 2.0 scope. For example you can use:

You can also use the AUTH_TOKEN_TYPE alias View your tasks which is equivalent to the Tasks API read-only scope: oauth2:https://www.googleapis.com/auth/tasks.readonly .

During the AccountManager.getAuthToken() call the AccountManager will check if your application has been authorized to access the Tasks API. If your application has not yet been authorized an Activity is started by the AccountManager which displays an authorization dialog to the user so that they can Allow or Deny your application to use the Tasks API on their account.

If the user denies your application access to the Tasks API, an OperationCanceledException will be thrown during the future.getResult() call. You should handle that gracefully for example by asking to choose the account again or displaying a message with a button to authorize access again.

Читайте также:  Sky gamblers storm raiders для андроид

Identifying your application and setting up the Tasks API service Object

Now that your application has authorization to access the Tasks API and that it have been given an access token you also need an API Key that you need to get from a project in the Google APIs Console as it is mandatory for making Tasks API calls. To do that follow these steps:

  1. Create a project or use an existing one
  2. Enable the Tasks API on your project by toggling the Tasks API switch to ON
  3. The API Key can be found at API Access > Simple API Access > API Key

The API Key is mandatory as it identifies your application and therefore allows the API to deduct quota and use the quota rules defined for your project. You need to specify the API Key on your Tasks service Object:

The accessToken is only valid for a certain amount of time, so you will have to get a new one when it expires. There are 2 ways of handling this:

  • Request an accessToken to the AccountManager every time you make requests through the API. Since the AccountManager caches the token this solution is acceptable.
  • Keep using your accessToken until you get a 403 error at which point you ask for a new token to the AccountManager .

Manipulating Tasks through the API

At this point you should have a fully set up Tasks API service Object which you can use to query the API as per the Tasks API developer’s Guide, for example:

Don’t forget to add the permission to access the Internet to your Android application manifest otherwise the above requests to the Tasks API endpoints will fail:

Sample application

We recently added a new sample to the Google APIs Client Library for Java sample repository to help you getting started with the Tasks API and OAuth 2.0 on Android. The sample is a simple but fully working Android application which requests authorization to use the Tasks API and display the default task list’s tasks in a ListView.

Follow these instructions to get the sample running, and don’t hesitate to post your feedback or questions to the Google Tasks API Forum.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Оцените статью