Use the Login with Amazon SDK for Android APIs
- Handle the Login Button and Get Profile Data
- Fetch User Profile Data
- Check for User Login at Startup
- Clear Authorization Data and Log Out Users
Handle the Login Button and Get Profile Data
This section explains how to call the authorize
API to login a user. This includes creating an onClick
listener for your Login with Amazon button in the onCreate
method of your app.
- Add Login with Amazon to your Android project.
-
Initialize
RequestContext
.You will need to declare a
RequestContext
variable and create a new instance of the class. The best place to initializeRequestContext
is in theonCreate
method of your Android activity or fragment. For example:private RequestContext requestContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestContext = RequestContext.create(this); }
-
Create an
AuthorizeListener
.AuthorizeListener
will process the result of theauthorize
call. It contains three methods:onSuccess
,onError
, andonCancel
. Create theAuthorizeListener
interface in-line with aregisterListener
call in theonCreate
method of your Android activity or fragment.@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestContext = RequestContext.create(this); requestContext.registerListener(new AuthorizeListener() { /* Authorization was completed successfully. */ @Override public void onSuccess(AuthorizeResult result) { /* Your app is now authorized for the requested scopes */ } /* There was an error during the attempt to authorize the application. */ @Override public void onError(AuthError ae) { /* Inform the user of the error */ } /* Authorization was cancelled before it could be completed. */ @Override public void onCancel(AuthCancellation cancellation) { /* Reset the UI to a ready-to-login state */ } }); }
Tip: If you’re using a fragment and capturing references toView
objects in yourAuthorizeListener
implementation, createAuthorizeListener
in the onCreateView method instead ofonCreate
. This ensures theView
object references are set when the call toauthorize
finishes. -
Implement
onSuccess
,onError
, andonCancel
for yourAuthorizeListener
.Because the authorization process presents a login screen (and possibly a consent screen ) to the user in a web browser (or a WebView), the user will have an opportunity to cancel the login or navigate away. If they explicitly cancel the login process,
onCancel
is called, and you will want to reset your user interface.If the user navigates away from the login screen in the browser or WebView, then switches back to your app, the SDK will not detect that the login was not completed. If you detect user activity in your app before login is completed, you can assume they have navigated away from the browser and react accordingly.
-
Call
RequestContext.onResume
.In order to accommodate the Android application lifecycle, implement the
onResume
method in your activity or fragment. This will trigger all listeners registered withregisterListener
in the event that your app is closed by the operating system before the user completes an authorization flow.@Override protected void onResume() { super.onResume(); requestContext.onResume(); }
-
Call
AuthorizationManager.authorize
.In the
onClick
handler for your Login with Amazon button, callauthorize
to prompt the user to login and authorize your application.This method will enable the user to sign in and consent to the requested information in one of the following ways:
- Switches to the system browser
- Switches to WebView in a secure context (if the Amazon Shopping app is installed to the device)
The secure context for the second option is available when the Amazon Shopping app is installed to the device. Amazon-created devices running Fire OS (for example Fire Tablets and Fire TVs) always use this option even if there is no Amazon Shopping app on the device. Because of this, if the user is already signed in to the Amazon Shopping app, this API will skip the sign in page, leading to a Single Sign-On experience for the user. See Customer Experience for Android/Fire apps apps to learn more.
When your application is authorized, it is authorized for one or more data sets known as scopes. A scope encompasses the user data you are requesting from Login with Amazon. The first time a user logs in to your app, they will be presented with a list of the data you are requesting and asked for approval.
Login with Amazon currently supports the following scopes:
profile
(gives access to the user’s name, email address, and Amazon account ID),profile:user_id
(gives access to the user’s Amazon account ID only), andpostal_code
(gives access to the user’s zip/postal code on file for their Amazon account).AuthorizationManager.authorize
is an asynchronous call, so you do not have to block the UI thread or create a worker thread of your own. To callauthorize
, pass anAuthorizeRequest
object that can be built usingAuthorizeRequest.Builder
:@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* Previous onCreate declarations omitted */ // Find the button with the login_with_amazon ID // and set up a click handler View loginButton = findViewById(R.id.login_with_amazon); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AuthorizationManager.authorize(new AuthorizeRequest .Builder(requestContext) .addScopes(ProfileScope.profile(), ProfileScope.postalCode()) .build()); }); } }
Fetch User Profile Data
This section explains how to use the User
API to retriever a user’s profile data after they’ve been authorized. The profile data you can retrieve is based on the scope indicated in the authorize:withHandler:
call.
-
Call
User.fetch
.User.fetch
returns the user’s profile data to you through theListener<User, AuthError>
callback.Listener<User, AuthError>
contains two methods:onSuccess
andonError
(it does not supportonCancel
because there is no way to cancel aUser.fetch
call).onSuccess
receives aUser
object with profile data, whileonError
receives anAuthError
object with information on the error.updateProfileData
is an example of a function your app could implement to display profile data in the user interface.@Override protected void onStart() { super.onStart(); Scope[] scopes = { ProfileScope.profile(), ProfileScope.postalCode() }; AuthorizationManager.getToken(this, scopes, new Listener < AuthorizeResult, AuthError > () { @Override public void onSuccess(AuthorizeResult result) { if (result.getAccessToken() != null) { /* The user is signed in */ } else { /* The user is not signed in */ } } @Override public void onError(AuthError ae) { /* The user is not signed in */ } }); }
Note:User.getUserPostalCode
is only returned if you request theProfileScope.postalCode()
scope.
Check for User Login at Startup
If a user logs into your app, closes the app, and restarts the app later, the app is still authorized to retrieve data. The user is not logged out automatically. At startup, you can show the user as logged in if your app is still authorized. This section explains how to use getToken
to see if the app is still authorized.
-
Call
getToken
.In the
onStart
method of your activity or fragment, callgetToken
to see if the application is still authorized.getToken
retrieves the raw access token that theAuthorizationManager
uses to access a user profile. If the token value is not null, then the app is still authorized and you can proceed to fetch user profile data.getToken
requires the same scopes you requested in your call toauthorize
.getToken
supports asynchronous calls in the same manner asUser.fetch
, so you do not have to block the UI thread or create a worker thread of your own. To callgetToken
asynchronously, pass an object that supports theListener<AuthorizeRequest, AuthError>
interface as the last parameter. -
Declare a
Listener<AuthorizeResult, AuthError>
.Your implementation of the
Listener<AuthorizeResult, AuthError>
interface processes the result of thegetToken
call. Listener contains two methods:onSuccess
andonError
(it does not supportonCancel
because there is no way to cancel agetToken
call). -
Implement
onSuccess
andonError
for yourListener<AuthorizeResult, AuthError>
.onSuccess
receives anAuthorizeResult
object with an access token, whileonError
receives anAuthError
object with information on the error.@Override protected void onStart() { super.onStart(); Scope[] scopes = { ProfileScope.profile(), ProfileScope.postalCode() }; AuthorizationManager.getToken(this, scopes, new Listener < AuthorizeResult, AuthError > () { @Override public void onSuccess(AuthorizeResult result) { if (result.getAccessToken() != null) { /* The user is signed in */ } else { /* The user is not signed in */ } } @Override public void onError(AuthError ae) { /* The user is not signed in */ } }); }
Clear Authorization Data and Log Out Users
This section explains how to use the signOut
method to clear the user's authorization data from the AuthorizationManager
local data store. The user will have to login again in order for the app to retrieve profile data. Use this method to log out a user, or to troubleshoot login problems in the app.
-
Implement a logout mechanism.
When a user has successfully logged in, you should provide a logout mechanism so they can clear their profile data and previously authorized scopes. Your mechanism might be a hyperlink, button, or a menu item. For this example, we will create an
onClick
method for a button. -
Call
signOut
.Call
signOut
in your logout handler to remove a user's authorization data (access tokens, profile) from the local store.signOut
takes an Android context and aListener<Void, AuthError>
to handle success or failure. -
Declare an anonymous
Listener<Void, AuthError>
.Your implementation of
Listener<Void, AuthError>
processes the result of thesignOut
call. Anonymous classes are useful for capturing variables from the enclosing scope. See Handle the Login Button and Authorize the User for an example that declares listener classes. -
Implement
onSuccess
andonError
for yourListener<Void, AuthError>
.When
signOut
succeeds you should update your UI to remove references to the user, and provide a login mechanism users can use to login again. IfsignOut
returns an error, you can let the user try to log out again.@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* Previous onCreate declarations omitted */ // Find the button with the logout ID and set up a click handler View logoutButton = findViewById(R.id.logout); logoutButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AuthorizationManager.signOut(getApplicationContext(), new Listener < Void, AuthError > () { @Override public void onSuccess(Void response) { // Set logged out state in UI } @Override public void onError(AuthError authError) { // Log the error } }); } }); }
Last updated: Dec 01, 2022