我正在编写一个包含Dagger 2
,Retrofit
的Android应用程序,我想使用AccountManager
实用程序。
我需要向OkHttpClient
提供使用Authenticator
调用刷新身份验证令牌的特定AccountManagerFuture
。代码与此非常相似:
@Provides
@Singleton
OkHttpClient provideOkHttpClient() {
return new OkHttpClient.Builder()
.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
// TODO: Refresh the authToken using the AccountManagerFuture call.
// ...
}
});
}
@Provides
注释只允许同步依赖,但我知道@Produces
也管理异步依赖。我可以使用@Produces
提供AccountManagerFuture
来电(前#addAccount
或#getAuthToken
)吗?
我有点困惑,但我会给你我的建议。我没有尝试,但似乎两次做同样的事情......
@Produces
AccountManagerFuture<Bundle> produceRefreshAuthToken(AccountManager accountManager) {
return accountManager.getAuthToken(accountType, authTokenType, null, activity, new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> accountManagerFuture) {
try {
// Get the future result.
Bundle future = accountManagerFuture.getResult();
// Get the authToken.
String authtoken = future.getString(AccountManager.KEY_AUTHTOKEN);
} catch (OperationCanceledException | AuthenticatorException | SecurityException | IOException ex) {
}
}
}, null);
}
@Provides
@Singleton
OkHttpClient provideOkHttpClient(AccountManagerFuture<Bundle> future) {
return new OkHttpClient.Builder()
.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
// Get the result.
Bundle bundle = future.getResult();
// Get the auth-token.
String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
// ...
}
});
}