Android accounts account name

AccountManager

Иногда разработчик хочет отслеживать пользователя. Первый вариант, который приходит в голову — попросить его ввести какие-то данные о себе и сохранить их где-нибудь. Но просить пользователя повторять эту процедуру при покупке нового устройства не самая лучшая идея. Кроме того, вы не можете гарантировать уникальность данных. Второй вариант — запомнить идентификатор телефона. Но пользователи иногда пользуются двумя телефонами, планшетами и т.д. и тут одним идентификатором не обойдёшься. Опять проблема.

Третий вариант – использовать класс AccountManager. С разрешения пользователя, вы можете использовать AccountManager для извлечения имён учетных записей, которые пользователь хранит на устройстве. Имея полученную информацию, вы можете, например, автоматически заполнить форму с адресом электронной почты.

Само устройство может хранить несколько аккаунтов от разных сервисов. Вы можете отфильтровать результат по типам аккаунтов. Например, у Гугла аккаунт имеет тип «com.google», Twitter использует тип «com.twitter.android.auth.login».

Для извлечения информации требуется разрешение:

В приложении вы сначала получаете экземпляр AccountManager через метод get(), а затем можете вызвать список аккаунтов определённого типа через getAccountsByType().

Метод getAccountsByType() возвращает массив учётных записей. Если в массиве более одной учётной записи, то покажите пользователю диалоговое окно с запросом для выбора одного аккаунта.

Объект Account содержит имя учетной записи, для учетных записей Google – это адрес электронной почты, который вы можете использовать для автоматического заполнения полей или в качестве ключа в базе данных и т.д.

В других учётных записях в имени не обязательно может содержаться электронный адрес. Например, это может быть часть электронного адреса или просто имя пользователя.

На эмуляторе скорее всего нет никаких аккаунтов, поэтому лучше проверять на устройстве. В большинстве случаев на телефоне есть аккаунт для Гугла. В логах я проверил количество аккаунтов, а в текстовом поле вывел имя аккаунта, который оказался моим электронным адресом.

Метод getAccounts() выводит все учётные записи, которые есть на устройстве.

На моём устройстве оказалось три учётные записи. Чтобы понять, кому они принадлежат, я заменил account.name на account.toString() и получил следующий результат.

Теперь стало понятно.

Мы рассмотрели только базовый пример работы с AccountManager. На самом деле, у класса много других возможностей. Например, вы можете добавить новую учётную запись и управлять ею.

Источник

Синхронизация в Android приложениях. Часть первая


На дворе 2014 год, доля Android JellyBean перевалила за 60%, появились новые тренды в дизайне. В общем, случилось много всего интересного. Но синхронизация данных с сервером осталось неотъемлемой частью большинства приложений. Существует много способов реализации ее в приложении. Android предоставляет нам SyncAdapter Framework, который позволяет автоматизировать и координировать этот процесс и предоставляет множество плюшек в довесок.

Account

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

Краткое резюме преимуществ:

  • Поддержка фоновых механизмов вроде SyncAdapter
  • Стандартизация способа авторизации
  • Поддержка различных токенов (прав доступа)
  • Шаринг аккаунта с разграничением привилегий (возможность использовать один аккаунт для различных приложений, как это делает Google)
Читайте также:  Циферблат для android часов

Шаги для получения плюшек:
1) Создание Authenticator’а
2) Создание Activity для логина
3) Создание сервиса для общения с нашим аккаунтом

AccountManager — управляет аккаунтами устройства. Приложения запрашивают авторизационные токены именно у него.

AbstractAccountAuthenticator — компонент для работы с определенным типом аккаунта. Вся механика по работе с аккаунтом (авторизация, разграничение прав) осуществляется здесь. Может быть общим для различных приложений. AccountManager работает именно с ним.

AccountAuthenticatorActivity — базовый класс активити для авторизации/создания аккаунта. Вызывается AccountManager’ом в случае необходимости идентифицировать аккаунт (токен отсутствует или протух).

Как это все работает, можно посмотреть на диаграмме из документации

Когда нам понадобился токен, мы работаем с методом AccountManager’а — getAuthToken. Стоит заметить, что это асинхронный метод и его можно безопасно вызывать из UI потока. Существует также синхронная версия этого метода — blockingGetAuthToken. К диаграмме еще вернемся.

Создание Authenticator’а

Для создания собственного Authenticator’а, нам необходимо расширить AbstractAccountAuthenticator и реализовать несколько его методов (7 если быть точным). Но для нас, на данный момент, представляют интерес всего два.

Метод, как видно из названия, вызывается при попытке добавить новый аккаунт. Все, что мы должны в нем сделать — это вернуть Intent, который должен запустить наше Activity. Чтобы иметь возможность добавить аккаунт из приложения, нам потребуются соответствующие разрешения.

Что же происходит в момент вызова этого метода: пытаемся получить текущий токен методом peekAuthToken, если токен существует, можем добавить проверку на валидность (напомню, что это асинхронный метод, так что можем ломиться на сервер) и возвращем результат. Если токена нет и/или сервер нам не отдал его, мы возвращаем тот же интент что и в методе addAccount. В этом случае пользователя выбьет на экран авторизации.

Создание Activity авторизации

Наше активити должно наследоваться от AccountAuthenticatorActivity (строго говоря, не должно а может: в AccountAuthenticatorActivity 20 строчек вспомогательного кода, который можно написать руками в любом другом активити). У нас будет самое простое активити с полями логин/пароль и кнопкой войти. В целом, в AccountManager’е можно сохранять произвольную информацию о профиле пользователя. Отвечать за получение токена будет AuthTokenLoader, но можно использовать любой понравившийся механизм. Задача-то простая — получить от сервера токен.

Данный метод вызывается, когда токен от сервера получен (а это говорит о валидности аккаунта) и, соответственно, можно добавить аккаунт на устройство. setAccountAuthenticatorResult — метод для передачи результата обратно в AccountManager.

Сервис для интергации в систему

Все, что он делает, это возвращает IBinder нашего Authenticator’a. Причем метод getIBinder уже реализован в AbstractAccountAuthenticator. Осталось только прописать наш сервис в манифесте приложения.

Осталась совсем маленькая деталь: вы могли заметить такую строчку

Это метафайл, который описывает наш Authenticator. Его необходимо создать в папке res/xml. В нем мы указываем иконку нашего аккаунта, его название и тип. В самом простом случае, он выглядит так:

Вот, в целом, все. После этих хитрых манипуляций мы получили возможность создавать свой аккаунт на устройстве. При всей кажущейся сложности, этот процесс на самом деле сводится к реализации 2-х методов, создания xml метафайла и описания сервиса в манифесте. Остальные методы Authenticator’а необходимы для шаринга нашего аккаунта во внешний мир с разделением привилегий, о чем мы поговорим в следующих статьях.

Источник

Android accounts account name

This post shows how to translate text between languages with an example.

Identify Language of Text with Firebase API Android Example

This post explains how to build a feature in android app that identifies the language of given text.

Читайте также:  Clownfish для скайпа для андроид

Organize Photos by Content Android Example

This post explains how to create in android a feature that lets user organize photos by its content.

Android Barcode Scanning Example

This post explains how to develop barcode scanning feature in android app using Firebase machine learning kit which provides barcode scanning API.

Extracting Text from Images Android

To recognize and extract text from images, Firebase ML kit can be used. Firebase ML kit offers machine learning features and is based on Google ML technologies.

Google Places SDK for Android Tutorial

Using Google places SDK for Android, current places, place details, nearby places and photos associated with a place can be displayed in apps and place search capability can be developed.

Android Widget Example

One of the excellent features of Android is that app’s information and features can be displayed as mini apps on home screens. These mini apps are called widgets.

Android MotionLayout Examples

MotionLayout is a subclass of ConstraintLayout. It allows you to animate property changes of UI elements which are part of a layout.

Android Fragments Transition Animation Example

To minimize the number of un-installations of your app, you need to build it in such way that it performs well, works on all devices and is user friendly.

Model View ViewModel MVVM Android Example

Model View ViewModel (MVVM) is an architectural pattern applied in applications to separate user interface code from data and business logic.

Android Model View Presenter MVP Pattern Example

If you want to build android apps which can be tested and modified easily, you need to implement user interface architectural pattern in your app.

Android Kotlin ListView Example

It is very common in most of the applications that a list of data items is displayed in UI. In android applications, list of data items can be shown to users using ListView.

About

Android app development tutorials and web app development tutorials with programming examples and code samples.

Источник

AccountManager

Class Overview

This class provides access to a centralized registry of the user’s online accounts. The user enters credentials (username and password) once per account, granting applications access to online resources with «one-click» approval.

Different online services have different ways of handling accounts and authentication, so the account manager uses pluggable authenticator modules for different account types. Authenticators (which may be written by third parties) handle the actual details of validating account credentials and storing account information. For example, Google, Facebook, and Microsoft Exchange each have their own authenticator.

Many servers support some notion of an authentication token, which can be used to authenticate a request to the server without sending the user’s actual password. (Auth tokens are normally created with a separate request which does include the user’s credentials.) AccountManager can generate auth tokens for applications, so the application doesn’t need to handle passwords directly. Auth tokens are normally reusable and cached by AccountManager, but must be refreshed periodically. It’s the responsibility of applications to invalidate auth tokens when they stop working so the AccountManager knows it needs to regenerate them.

Applications accessing a server normally go through these steps:

  • Get an instance of AccountManager using get(Context) .
  • List the available accounts using getAccountsByType(String) or , android.os.Handler)»>getAccountsByTypeAndFeatures(String, String[], AccountManagerCallback, Handler) . Normally applications will only be interested in accounts with one particular type, which identifies the authenticator. Account features are used to identify particular account subtypes and capabilities. Both the account type and features are authenticator-specific strings, and must be known by the application in coordination with its preferred authenticators.
  • Select one or more of the available accounts, possibly by asking the user for their preference. If no suitable accounts are available, , android.os.Handler)»>addAccount(String, String, String[], Bundle, Activity, AccountManagerCallback , Handler) may be called to prompt the user to create an account of the appropriate type.
  • Important: If the application is using a previously remembered account selection, it must make sure the account is still in the list of accounts returned by getAccountsByType(String) . Requesting an auth token for an account no longer on the device results in an undefined failure.
  • Request an auth token for the selected account(s) using one of the , android.os.Handler)»>getAuthToken(Account, String, Bundle, Activity, AccountManagerCallback , Handler) methods or related helpers. Refer to the description of each method for exact usage and error handling details.
  • Make the request using the auth token. The form of the auth token, the format of the request, and the protocol used are all specific to the service you are accessing. The application may use whatever network and protocol libraries are useful.
  • Important: If the request fails with an authentication error, it could be that a cached auth token is stale and no longer honored by the server. The application must call invalidateAuthToken(String, String) to remove the token from the cache, otherwise requests will continue failing! After invalidating the auth token, immediately go back to the «Request an auth token» step above. If the process fails the second time, then it can be treated as a «genuine» authentication failure and the user notified or other appropriate actions taken.
Читайте также:  Андроид с большим разрешением

Some AccountManager methods may need to interact with the user to prompt for credentials, present options, or ask the user to add an account. The caller may choose whether to allow AccountManager to directly launch the necessary user interface and wait for the user, or to return an Intent which the caller may use to launch the interface, or (in some cases) to install a notification which the user can select at any time to launch the interface. To have AccountManager launch the interface directly, the caller must supply the current foreground Activity context.

Many AccountManager methods take AccountManagerCallback and Handler as parameters. These methods return immediately and run asynchronously. If a callback is provided then )»>run(AccountManagerFuture ) will be invoked on the Handler’s thread when the request completes, successfully or not. The result is retrieved by calling getResult() on the AccountManagerFuture returned by the method (and also passed to the callback). This method waits for the operation to complete (if necessary) and either returns the result or throws an exception if an error occurred during the operation. To make the request synchronously, call getResult() immediately on receiving the future from the method; no callback need be supplied.

Requests which may block, including getResult() , must never be called on the application’s main event thread. These operations throw IllegalStateException if they are used on the main thread.

Источник

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