Account manager android studio

AccountManager

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

Pilanites

Business of Online Products

  • Home
  • /
  • streaks
  • /
  • Android Account Manager: Introduction and Basic Implementation

Android Account Manager: Introduction and Basic Implementation

Recently I had to implement an online sync facility for my habit tracker app. As it goes with every online service, you needed an account to take it’s advantage. Enter the Android Account Manager.

Now, if you are an advanced user of Android phones (and since you’re reading this, you most certainly are), you must have seen an “Accounts” section in phone Settings.

Upon clicking that, you’ll find your accounts related to apps on your phone.

I wanted to utilize this built-in AccountManager functionality to store and authenticate user’s credentials because it works like a charm with the built-in sync mechanism (using the SyncAdapter ).

But we are getting ahead of ourselves here. Let’s start with the authentication system for server.

Authentication system

Our system authenticates users based on email and password combo. If the combo is correct, server returns an auth_token which are valid until the user logs out. This is your normal token based authentication where the token lives forever and has all the permissions as the user itself.

A small overview of implementation

Every device creates a new auth_token for itself because it makes it easy to log the device, limit the number of clients for an account.

This was fairly easy to implement on the server side by adding fields for auth_token in Device model. Simply create a new Device whenever user logs in or registers, populating that auth_token field to a random value.

Читайте также:  Блокировка кнопок для android

Creating account on the phone via the Android Account Manager

Till now, we had discussed the how to create account on server, and how it interacts with the client. Let’s move on to the meat of this post, creating account using AccountManager .

Wait, what’s AccountManager? And why should we use it?

More specifically, why not store the credentials using SharedPreference and have full control without wasting time on this?

The great thing with AccountManager is that it solves the corner cases, and little small details with ease, which you might forget to account for. It really shines well when you’re using OAuth2 and need to fetch a new token when the current one expires.

There are many more benefits to using AccountManager but going through all of them is a little too much. I’ll add the links in comments if you ask for them. 🙂

A more in-depth look at AccountManager can be found here.

We’ll be using it to store the user credentials and auth_token .

Things we need to support

  1. Users can add an account
  2. They can sync their data
  3. They can log out of their account

Pretty simple and straightforward.

Flow and important terms

Before we look at the code, let’s talk about the workflow.

When the app tries to access an account, and it’s auth_token , this is how it goes :-

  • The app asks the AccountManager for an auth_token .
  • The AccountManager asks the AccountAuthenticator whether it has a token
  • If it has none, it shows the user an AccountsActivity through which the user logs in
  • The user logs in after which the app obtains the auth_token from server
  • The auth_token is stored by the AccountManager for any future use which it returns the next time app asks for it

The good thing about using AccountManager is that system will start the correct activities and handle most of the corner cases we as developers get lazy about.

This assures us that we’ll have a valid auth_token while syncing, so we can avoid defensive programming.

Building our Authenticator

Authenticator is the class which AccountManager uses to handle our account related tasks like storing the auth_token or account password.

The first thing you need to do is extend the AbstractAccountAuthenticator and implement its methods to create our Authenticator.

You may decide to implement all the methods, or just leave out some by having them throw an UnsupportedOperationException . You will, however need to implement the addAccount method to allow users to add an account in the system.

Another method you should implement is getAuthToken . This method allows your SyncAdapter , and really your whole app, to acquire the auth_token for making network calls.

This is how I’ve implemented it.

@Override public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle bundle) throws NetworkErrorException < AccountManager am = AccountManager.get(mContext); String authToken = am.peekAuthToken(account, authTokenType); if (TextUtils.isEmpty(authToken)) < authToken = HTTPNetwork.login(account.name, am.getPassword(account)); >if (!TextUtils.isEmpty(authToken)) < final Bundle result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name); result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type); result.putString(AccountManager.KEY_AUTHTOKEN, authToken); return result; >// If you reach here, person needs to login again. or sign up // If we get here, then we couldn’t access the user’s password — so we // need to re-prompt them for their credentials. We do that by creating // an intent to display our AuthenticatorActivity which is the AccountsActivity in my case. final Intent intent = new Intent(mContext, AccountsActivity.class); intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response); intent.putExtra(«YOUR ACCOUNT TYPE», account.type); intent.putExtra(«full_access», authTokenType); Bundle retBundle = new Bundle(); retBundle.putParcelable(AccountManager.KEY_INTENT, intent); return retBundle; >

This kind of completes the Authenticator, at least for our purposes. You can have a look at the entire file by visiting this gist for Authenticator.java.

Building the Authentication Activity

Now, you must have noticed that there is an AccountsActivity here. This is a special activity which is shown to the user whenever they have to login for Authenticator to get token.

Create the activity as you normally would, making network calls, validations and everything else normally. When you wish to add the credentials to Accounts, use a method like the one below.

public void createAccount(String email, String password, String authToken)

This will create the account for you to use.

Building the Authentication Service

At this point, the Activity will be ready but we haven’t registered our Authenticator with the system.

Читайте также:  Возможности samsung galaxy android

To do that, we’ll have to define an AuthenticatorService and register it in the Manifest file with special filter and meta-data.

The service is pretty simple (link) and looks like:-

After making this we need to declare this service in Manifest with appropriate tags.

If you notice the meta-data tag there, you’ll find android:resource ‘s value something which hasn’t been defined before. This xml file is important because it lets the system know how to represent your app in the settings.

Create a folder named xml in the res folder. In that folder, make a new file named authenticator.xml (name can be anything, as long as you specify it in the Manifest file). The contents of that file for my project looks like this:-

Most of these values would have been already defined by you, except the account_type which needs to be the same as the one your provided earlier (we have used «YOUR ACCOUNT TYPE» as placeholder).

This will let you create a very basic version of app supporting the accounts in your system. Look how good our app’s name looks in Account’s screen 😛

Look at Streaks sitting there with other apps

To access your user’s account, all you will need to do is

AccountManager accountManager = AccountManager.get(context); Account[] accounts = accountManager.getAccountsByType(AccountConstants.ACCOUNT_TYPE); // Use accounts[0] (or whatever number of account) after checking that accounts.length > 1

That wraps up our introduction to creating an account in system. If you want a detailed information about what other things are possible, check out udinic’s post which is an excellent but overwhelming resource.

I urge you to leave a comment here if you have any questions or tweet them to me, @shobhitic.

Next week, I’ll be creating a SyncAdapter which uses this Account for communication. If you’d like to hear about that, sign up for my email list.

Источник

Account manager android studio

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.

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.

Читайте также:  Android os looper java

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.

Источник

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