picasso为单例实例更新令牌

时间:2016-03-04 12:17:25

标签: android picasso

我在我的应用程序中使用Picasso“the below code”进行图像加载  并且它的工作正常,直到令牌到期,

当我获取新令牌时,我试图再次呼叫ConfigurePicasso以更新令牌

但我得到异常Singleton instance already exists还有另一种更新单例实例令牌的方法吗?

 public class MyApplication extends Application {

@Override
public void onCreate() {
    super.onCreate();
    ConfigurePicasso(this);
}

    public static void ConfigurePicasso(Context context){
        try {
            if (!TextUtils.isEmpty(ConfigurationRow.getInstance(context.getApplicationContext()).getAuthToken())) {
                OkHttpClient picassoClient = new OkHttpClient();
                picassoClient.interceptors().add(new TokenInterceptor(ConfigurationRow.getInstance(context.getApplicationContext()).getAuthToken()));
                File Cachefile = CacheUtils.CacheDir(context.getApplicationContext());
                picassoClient.setCache(new com.squareup.okhttp.Cache(Cachefile, CacheUtils.CacheSize(Cachefile)));
                Picasso picasso = new Picasso.Builder(context.getApplicationContext()).listener(new Picasso.Listener() {
                    @Override
                    public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {

                    }
                }).downloader(new OkHttpDownloader(picassoClient)).build();
                Picasso.setSingletonInstance(picasso);
            }
        }catch (Exception e){
            e.getMessage();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

让您的TokenInterceptor变为可变,并在您想要的位置保留对它的引用。必要时在其上设置令牌。

类似的东西:

final class TokenInterceptor implements Interceptor {
  private volatile String someAuthToken = null;

  void setSomeAuthToken(String someAuthToken) {
    this.someAuthToken = someAuthToken;
  }

  @Override
  public Response intercept(Chain chain) throws IOException {
    Request request = chain.request().newBuilder().addHeader("some-auth-header", someAuthToken).build();
    return chain.proceed(request);
  }
}