我在Android中创建新项目时创建了默认登录活动。默认情况下,创建一个可以正常登录和显示的progressBar。所有这一切都通过AsyncTask实现。
现在我使用Retrofit 2让Async登录。
当我按下按钮登录时启动了一个内容的方法:
....
....
showProgress(true);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, retrofit2.Response<User> response) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
User userdatos = response.body();
if(userdatos != null){
// redirect to Main Activity page
showProgress(false);
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
}
else{
showProgress(false);
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
call.cancel();
showProgress(false);
Toast.makeText(LoginActivity.this, "Please check your network connection and internet permission", Toast.LENGTH_LONG).show();
}
});
我强迫Thread.sleep(3000)检查。没有进度条,调试显示:跳过180帧!应用程序可能在ITS主线程上做了太多工作。
怎么解决这个问题?
我会有很多异步调用,我总是会显示一个进度条,等待响应完成。
谢谢
让我与您分享由Android Studio和我的Retrofit实现创建的默认登录活动的矿代码实现。默认登录活动,包括调用AsyncTask
的UserLoginTask
,在其中,我完成了所有登录逻辑工作。我使用.execute
而不是.enqueue
,因为它同步,我们不需要AsyncTask
内的新线程
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
Retrofit restAdapter = new Retrofit.Builder()
.baseUrl(Constants.ROOT_API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
IConstructSecureAPI service = restAdapter.create(IConstructSecureAPI.class);
Call<JsonElement> result = service.getToken(mEmail, mPassword, "password");
try {
//using sync request and get response
JsonElement element = result.execute().body();
if(element!=null) {
//do whatever you want with your response
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
if(clientType != 2){
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
clientType = 0;
}
else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(intent, 1);
}
// finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
无耻的促销
我已经为此创建了RxLoading library,它可以做到这一点以及更多,
你可以做这样的事情:
networkCall().compose(RxLoading.<>create(loadingLayout)).subscribe(...);
它由2个类组成,一个自定义视图(loadingLayout)和一个将它们粘合在一起的transformer的RxLoading,你可以选择使用它们中的两个或两个。
你需要在RxJava中使用retrofit2。
RxLoading还支持空状态和错误状态(具有内置重试机制,因此请务必检查此选项)
你可以在GitHub page上找到更多信息。