AsyncTask内部的Retrofit调用

问题描述 投票:11回答:1

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

i。我已经实现了对我的api的异步调用,该调用在AsyncTask的doInBackground方法内部被调用。 concern:读了this article使我感到困惑。 AsyncTasks不适合此类任务吗?我应该直接从活动中调用API吗?我了解Retrofit的回调方法是在UI线程上执行的,但是通过HTTP的调用又如何呢? Retrofit是否为此创建线程?

ii。我希望将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;
    }
java android android-asynctask retrofit
1个回答
37
投票

I。改造支持发出请求的三种方式:

  • synchronic

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

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

此方法在被调用的线程中完成。因此您无法在主/ UI线程中调用它

  • 异步

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

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

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

  • 使用RxAndroid

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

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

此方法还支持在新线程中发出网络请求。因此,您不必创建新的线程/ AsyncTask。在UI /主线程中调用了来自subscription方法的Action1回调。

II。您可以只在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();
© www.soinside.com 2019 - 2024. All rights reserved.