Alexa授权

    xiaoxiao2021-03-25  90

    按照下面的步骤进行Android应用授权

    到Amazon获取一个apiKey文件你需要声明一个RequestContext的成员变量和创建一个新的类实例。若要创建实例,请将当前应用程序上下文传递到静态工厂方法。初始化最好的地方是在你的Activity的onCreate方法。例如: private RequestContext mRequestContext; @Override protected void onCreate(Bundle savedInstance) { super.onCreate(savedInstance); mRequestContext = RequestContext.create(this); }

    3.创建一个authorizelistenerimpl类 AuthorizeListenerImpl继承AuthorizeListener这个抽象类, 实现它的3个抽象方法。授权成功、失败、取消时会调用对应方法。如下:

    private class AuthorizeListenerImpl extends AuthorizeListener { /* Authorization was completed successfully. */ @Override public void onSuccess(final AuthorizeResult authorizeResult) { } /* There was an error during the attempt to authorize the application. */ @Override public void onError(final AuthError authError) { } /* Authorization was cancelled before it could be completed. */ @Override public void onCancel(final AuthCancellation authCancellation) { } }

    4.创建一个authorizelistenerimpl实例并注册它

    @Override protected void onCreate(Bundle savedInstance) { super.onCreate(savedInstance); mRequestContext = RequestContext.create(this); mRequestContext.registerListener(new AuthorizeListenerImpl()); }

    5.重写resume方法

    @Override protected void onResume() { super.onResume(); mRequestContext.onResume(); }

    6.登录Amazon账号代码如下:

    final JSONObject scopeData = new JSONObject(); final JSONObject productInstanceAttributes = new JSONObject(); try { productInstanceAttributes.put("deviceSerialNumber", PRODUCT_DSN); scopeData.put("productInstanceAttributes", productInstanceAttributes); scopeData.put("productID", PRODUCT_ID); AuthorizationManager.authorize(new AuthorizeRequest.Builder(mRequestContext) .addScope(ScopeFactory.scopeNamed("alexa:all", scopeData)) .forGrantType(AuthorizeRequest.GrantType.ACCESS_TOKEN) .shouldReturnUserData(false) .build()); } catch (JSONException e) { // handle exception here }

    7.创建token获取监听者

    public class TokenListener implements Listener<AuthorizeResult, AuthError> { /* getToken completed successfully. */ @Override public void onSuccess(AuthorizeResult authorizeResult) { } /* There was an error during the attempt to get the token. */ @Override public void onError(AuthError authError) { } }

    8.登录成功时获取token

    AuthorizationManager.getToken(this, new Scope[] { ScopeFactory.scopeNamed("alexa:all") }, new TokenListener());

    9.在tokenListener的onSuccess事件中获取token

    /* getToken completed successfully. */ @Override public void onSuccess(AuthorizeResult authorizeResult) { String accessToken = authorizeResult.getAccessToken(); }

    10.在activity的onstart事件调用AuthorizationManager.getToken来判断是否已经授权

    private static final Scope ALEXA_ALL_SCOPE = ScopeFactory.scopeNamed("alexa:all"); @Override protected void onStart(){ super.onStart(); AuthorizationManager.getToken(this, new Scope[] { ALEXA_ALL_SCOPE }, new TokenListener()); }

    得到token就可以使用它去访问AVS

    转载请注明原文地址: https://ju.6miu.com/read-24263.html

    最新回复(0)