我正在试图找出实现支持OAuth2流的AccountManager.getAuthToken()的Retrofit客户端的最佳方法。 我正在关注U2020
理想情况下,我希望沿着这些线有一个简单的注射器
public class ExampleFragment extends InjectionFragment { @Inject ApiDatabase database; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); subscribe(database.getSomeData(), ...); } }
我正在考虑类似于the example
的RequestInterceptorpublic final class ApiHeaders implements RequestInterceptor { ApiKeyProvider apiKeyProvider; @Inject public ApiHeaders(ApiKeyProvider apiKeyProvider) { this.apiKeyProvider = apiKeyProvider; } @Override public void intercept(RequestFacade request) { // How to handle exceptions from getAuthToken? request.addHeader("Authorization", "Bearer " + apiKeyProvider.getAuthKey()); } }
和
public class ApiKeyProvider { AccountManager accountManager; Activity activity; public ApiKeyProvider(Activity activity, AccountManager accountManager) { this.activity = activity; this.accountManager = accountManager; } public String getAuthKey() throws AccountsException, IOException { AccountManagerFuture accountManagerFuture = accountManager.getAuthTokenByFeatures(ACCOUNT_TYPE, AUTHTOKEN_TYPE, new String[0], activity, null, null, null, null); return accountManagerFuture.getResult().getString(KEY_AUTHTOKEN); } }
我不确定如何将ApiKeyProvider注入ApiHeaders类,因为它依赖于“ActivityModule”(在匕首DAG图下方)。 也不知道如何处理异常。
任何人都可以提供完整的工作示例吗?