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
RequestContextvariable and create a new instance of the class. The best place to initializeRequestContextis in theonCreatemethod 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.AuthorizeListenerwill process the result of theauthorizecall. It contains three methods:onSuccess,onError, andonCancel. Create theAuthorizeListenerinterface in-line with aregisterListenercall in theonCreatemethod 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 toViewobjects in yourAuthorizeListenerimplementation, createAuthorizeListenerin the onCreateView method instead ofonCreate. This ensures theViewobject references are set when the call toauthorizefinishes. -
Implement
onSuccess,onError, andonCancelfor 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,
onCancelis 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
onResumemethod in your activity or fragment. This will trigger all listeners registered withregisterListenerin 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
onClickhandler for your Login with Amazon button, callauthorizeto 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.authorizeis an asynchronous call, so you do not have to block the UI thread or create a worker thread of your own. To callauthorize, pass anAuthorizeRequestobject 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.fetchreturns the user’s profile data to you through theListener<User, AuthError>callback.Listener<User, AuthError>contains two methods:onSuccessandonError(it does not supportonCancelbecause there is no way to cancel aUser.fetchcall).onSuccessreceives aUserobject with profile data, whileonErrorreceives anAuthErrorobject with information on the error.updateProfileDatais 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.getUserPostalCodeis 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
onStartmethod of your activity or fragment, callgetTokento see if the application is still authorized.getTokenretrieves the raw access token that theAuthorizationManageruses 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.getTokenrequires the same scopes you requested in your call toauthorize.getTokensupports 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 callgetTokenasynchronously, 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 thegetTokencall. Listener contains two methods:onSuccessandonError(it does not supportonCancelbecause there is no way to cancel agetTokencall). -
Implement
onSuccessandonErrorfor yourListener<AuthorizeResult, AuthError>.onSuccessreceives anAuthorizeResultobject with an access token, whileonErrorreceives anAuthErrorobject 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
onClickmethod for a button. -
Call
signOut.Call
signOutin your logout handler to remove a user's authorization data (access tokens, profile) from the local store.signOuttakes 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 thesignOutcall. 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
onSuccessandonErrorfor yourListener<Void, AuthError>.When
signOutsucceeds you should update your UI to remove references to the user, and provide a login mechanism users can use to login again. IfsignOutreturns 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

