我在用安卓。我使用SharedPreferences存储身份验证令牌。
为了刷新身份验证令牌,我使用Authenticator类。
现在,我需要能够在SharedPreferences中设置新的auth令牌,但是,为了做到这一点,SharedPreferences需要一个上下文。
当我没有上下文时,如何从Authenticator类设置新的(刷新的)身份验证令牌?
这是我的身份验证类:

public class TokenAuthenticator implements Authenticator {
    private String authToken;

    public TokenAuthenticator(String authToken) {
        this.authToken = authToken;
    }

    @Override
    public Request authenticate(Route route, Response response) throws IOException {
        if (responseCount(response) >= 3) {
            return null;
        }

        ApiInterface apiService = ApiClient.createService(ApiInterface.class, authToken);
        Call<BasicResponse> call = apiService.refreshAuthToken();
        BasicResponse apiResponse = call.execute().body();

        String newToken = apiResponse.getData().getToken();

        // Set the new token in shared preferences (how to get context?)
        SharedPreferences sp = getSharedPreferences(context);
        sp.edit().putString("AUTH_TOKEN", token).apply();

        return response.request().newBuilder()
                .header("Authorization", "Bearer " + newToken)
                .build();
    }

    private int responseCount(Response response) {
        int result = 1;
        while ((response = response.priorResponse()) != null) {
            result++;
        }
        return result;
    }

}

下面是从中调用authenticator类的位置:
public class ApiClient {

    public static final String API_URL = "http://www.user324211.com/";

    private static OkHttpClient.Builder httpClient =
            new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    private static Retrofit retrofit = builder.build();

    public static Retrofit getRetrofit() {
        return retrofit;
    }

    public static <S> S createService(Class<S> serviceClass) {
        return createService(serviceClass, null);
    }

    public static <S> S createService(Class<S> serviceClass, final String authToken) {
        if (authToken != null) {
            TokenAuthenticator tokenAuthenticator = new TokenAuthenticator(authToken);
            httpClient.authenticator(tokenAuthenticator);
        }

        builder.client(httpClient.build());
        retrofit = builder.build();

        return retrofit.create(serviceClass);
    }

}

最佳答案

有几种方法可以做到这一点
我建议您创建一个应用程序类并在应用程序中创建一个方法
调用它getContext(),然后可以从任何地方访问该方法
你可以得到类似app.getContext()的上下文
例子

package YOUR_PACKAGE_NAME;

import android.app.Application;
import android.content.Context;

public class App extends Application
{
    private static Context context;

    @Override
    public void onCreate()
    {
        super.onCreate();

        context = getApplicationContext();
    }

    public static Context GetContext()
    {
        return context;
    }
}

你可以这样做一个单独的共享引用
https://github.com/BioGram/Android/blob/master/app/src/main/java/co/biogram/main/handler/SharedHandler.java

关于android - 在Authenticator中设置SharedPreference?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43794994/

10-09 10:07