use*_*152 10 java android android-asynctask retrofit
我最近开始开发Android应用程序并决定使用Retrofit作为REST服务的客户端,但我不确定我的方法是否良好:
一世.我已经实现了对我的api的异步调用,它在AsyncTask的doInBackground方法中调用.该关注:看了这篇文章让我困惑.AsyncTasks不适合这类任务吗?我应该直接从Activity调用API吗?我知道Retrofit的回调方法是在UI线程上执行的,但是通过HTTP调用呢?Retrofit是否为此创建线程?
II.我希望AuthenticationResponse保存在SharedPreferences对象中,该对象在回调的success方法中似乎不可用.有什么建议/良好做法吗?
先感谢您 :)
这是我的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;
}
Run Code Online (Sandbox Code Playgroud)
Kon*_*iak 36
I. Retrofit支持三种提出请求的方式:
您必须声明将响应返回为值的方法,例如:
@GET("/your_endpoint")
AuthenticationResponse auth(@Body AuthenticationRequest authRequest);
Run Code Online (Sandbox Code Playgroud)
此方法在调用的线程中完成.所以你不能在main/UI线程中调用它.
你必须声明void方法,其中包含带有响应的回调作为最后一个参数,例如:
@GET("/your_endpoint")
voud auth(@Body AuthenticationRequest authRequest, Callback<AuthenticationResponse> callback);
Run Code Online (Sandbox Code Playgroud)
在新的后台线程中调用请求的执行,并且在调用方法的线程中完成回调方法.所以你可以在没有新线程/ AsyncTask的main/UI线程中调用这个方法.
我知道的最后一种方法是使用RxAndroid的方法.你必须声明一个方法,它将响应返回为带有值的observable.例如:
@GET("/your_endpoint")
Observable<AuthenticationResponse> auth(@Body AuthenticationRequest authRequest);
Run Code Online (Sandbox Code Playgroud)
此方法还支持在新线程中发出网络请求.所以你不必创建新的线程/ AsyncTask.在UI /主线程中调用来自subscribe方法的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();
Run Code Online (Sandbox Code Playgroud)