Vielen Dank für deinen Besuch. Diese Seite ist nur in Englisch verfügbar.

Use the Login with Amazon SDK for Android APIs

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.

  1. Add Login with Amazon to your Android project.
  2. Initialize RequestContext.

    You will need to declare a RequestContext variable and create a new instance of the class. The best place to initialize RequestContext is in the onCreate 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);
    }
    
  3. Create an AuthorizeListener.

    AuthorizeListener will process the result of the authorize call. It contains three methods: onSuccess, onError, and onCancel. Create the AuthorizeListener interface in-line with a registerListener call in the onCreate 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 */
            }
        });
    }
    
  4. Implement onSuccess, onError, and onCancel for your AuthorizeListener.

    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.

  5. 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 with registerListener 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();
    }
    
  6. Call AuthorizationManager.authorize.

    In the onClick handler for your Login with Amazon button, call authorize 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:

    1. Switches to the system browser
    2. 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), and postal_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 call authorize, pass an AuthorizeRequest object that can be built using AuthorizeRequest.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.

  1. Call User.fetch.

    User.fetch returns the user’s profile data to you through the Listener<User, AuthError> callback. Listener<User, AuthError> contains two methods: onSuccess and onError (it does not support onCancel because there is no way to cancel a User.fetch call). onSuccess receives a User object with profile data, while onError receives an AuthError 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 */
            }
        });
    }
    

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.

  1. Call getToken.

    In the onStart method of your activity or fragment, call getToken to see if the application is still authorized. getToken retrieves the raw access token that the AuthorizationManager 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 to authorize.

    getToken supports asynchronous calls in the same manner as User.fetch, so you do not have to block the UI thread or create a worker thread of your own. To call getToken asynchronously, pass an object that supports the Listener<AuthorizeRequest, AuthError> interface as the last parameter.

  2. Declare a Listener<AuthorizeResult, AuthError>.

    Your implementation of the Listener<AuthorizeResult, AuthError> interface processes the result of the getToken call. Listener contains two methods: onSuccess and onError (it does not support onCancel because there is no way to cancel a getToken call).

  3. Implement onSuccess and onError for your Listener<AuthorizeResult, AuthError>.

    onSuccess receives an AuthorizeResult object with an access token, while onError receives an AuthError 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.

  1. 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.

  2. 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 a Listener<Void, AuthError> to handle success or failure.

  3. Declare an anonymous Listener<Void, AuthError>.

    Your implementation of Listener<Void, AuthError> processes the result of the signOut 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.

  4. Implement onSuccess and onError for your Listener<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. If signOut 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