我有这段代码可以在后台进行异步调用,显示进度条并在单击按钮时启动另一个活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
// ....
actionButton.setOnClickListener(this);
// call action here
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.actionButton) {
setProgressVisibility(VISIBLE);
new MyActivity.ActionTask().execute(action);
}
}
private void getAction(Action action) {
try {
Call<Action> getAction = api.callAction(model, action);
Response<Action> response = getAction.execute();
setProgressVisibility(INVISIBLE);
if (response.isSuccessful() && response.body() != null) {
startAction(response.body());
} else {
runOnUiThread(() -> showToast(R.string.error, this));
logger.error(getResources().getString(R.string.error));
}
} catch (IOException e) {
runOnUiThread(() -> showToast(e.getMessage(), this));
logger.error(e.getMessage());
setProgressVisibility(INVISIBLE);
}
}
private void startAction(Action action) {
Intent intent = new Intent(this, ActionActivity.class);
intent.putExtra("action", action);
startActivity(intent);
}
private class ActionTask extends AsyncTask<Action, Void, Action> {
@Override
protected Action doInBackground(Action... action) {
getAction(action[0]);
return action[0];
}
}
我想在 OnCreate 中显示第一个活动时立即启动异步调用,以便用户单击按钮时看起来更快。因此,异步调用在活动创建后立即开始,然后当用户单击按钮时,如果结果已经可用,则下一个活动启动,否则显示进度条,直到结果可用,一旦结果准备好第二个活动开始。最好的方法是什么?
aluckdog
相关分类