在 AsyncTask 中改造调用

Retrofit call inside AsyncTask

我最近开始开发 Android 应用程序并决定使用 Retrofit 作为 REST 服务的客户端,但我不确定我的方法是否合适:

我。我已经实现了对 api 的异步调用,它在 AsyncTask 的 doInBackground 方法中调用。 关注:阅读 this article 让我感到困惑。 AsyncTasks 不适合这种任务吗?我应该直接从 Activity 调用 API 吗?我知道 Retrofit 的回调方法是在 UI 线程上执行的,但是通过 HTTP 调用呢? Retrofit 会为此创建线程吗?

二。我希望将 AuthenticationResponse 保存在 SharedPreferences 对象中,该对象在回调的成功方法中似乎不可用。有什么建议/好的做法吗?

提前谢谢你:)

这是我的 doInBackGroundMethod:

    @Override
    protected String doInBackground(String... params) {
        Log.d(LOCATION_LOGIN_TASK_TAG, params[0]);

        LocationApi.getInstance().auth(new AuthenticationRequest(params[0]), new Callback<AuthenticationResponse>() {

            @Override
            public void success(AuthenticationResponse authenticationResponse, Response response) {
                Log.i("LOCATION_LOGIN_SUCCESS", "Successfully logged user into LocationAPI");
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("LOCATION_LOGIN_ERROR", "Error while authenticating user in the LocationAPI", error);
            }
        });
        return null;
    }

我。 Retrofit支持三种请求方式:

  • 同步

您必须声明将 returns 响应作为值的方法,例如:

  @GET("/your_endpoint")
  AuthenticationResponse auth(@Body AuthenticationRequest authRequest);

该方法在调用的线程中完成。所以你不能在main/UI线程中调用它

  • 异步

您必须声明包含回调的 void 方法作为最后一个参数,例如:

  @GET("/your_endpoint")
  void auth(@Body AuthenticationRequest authRequest, Callback<AuthenticationResponse> callback);

请求的执行在新的后台线程中调用,回调方法在调用方法的线程中完成,因此您可以在 main/UI 线程中调用此方法而无需新的 thread/AsyncTask。

  • 使用 RxAndroid

我知道的最后一种方法是使用 RxAndroid 的方法。您必须将 returns 响应的方法声明为可观察值。例如:

  @GET("/your_endpoint")
  Observable<AuthenticationResponse> auth(@Body AuthenticationRequest authRequest);

该方法还支持在新线程中发起网络请求。所以你不必创建新的 thread/AsyncTask。来自 subscribe 方法的 Action1 回调在 UI/main 线程中被调用。

二.您可以在 Activity 中调用您的方法,您可以将数据写入 SharedPreferences,如下所示:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sharedPreferences.edit()
            .put...//put your data from AuthenticationResponse 
                   //object which is passed as params in callback method.
            .apply();