我做了一个Android应用程序,最初是针对较低版本(2.3)的。在我的概念验证工作后,我试图让它在 Android 4 上工作。那时我遇到了 NetworkOnMainThread 异常。
经过一些研究,我很快找到了 AsyncTask,它听起来很棒。问题是,我很难全神贯注。例如,这是我的原始代码:
public void Refresh(Context c)
{
SummaryModel model = MobileController.FetchSummary(c);
TextView txtCurrentWeight = (TextView)findViewById(R.id.txtCurrentWeight);
TextView txtWeightChange = (TextView)findViewById(R.id.txtWeightChange);
TextView txtAvgPerWeek = (TextView)findViewById(R.id.txtAvgPerWeek);
if(model.ErrorMessage == "")
{
txtCurrentWeight.setText(model.CurrentWeight);
txtWeightChange.setText(model.WeightChange);
txtAvgPerWeek.setText(model.Average);
}
else
{
Toast.makeText(c, model.ErrorMessage, Toast.LENGTH_LONG).show();
txtCurrentWeight.setText("");
txtWeightChange.setText("");
txtAvgPerWeek.setText("");
}
}
我像这样创建了一个 AsychTask:
public class WebMethodTask extends AsyncTask<Object, Integer, Object> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
SummaryModel model = (SummaryModel)result;
// Can't seem to access UI items here??
}
@Override
protected Object doInBackground(Object... params) {
Context c = (Context)params[0];
return MobileController.FetchSummary(c);
}
}
如何从 onPostExecute 方法访问 UI 项目?或者,我对如何使用 AsyncTask 有错误的想法吗?
谢谢!
最佳答案
您应该能够在放置评论的地方访问 UI(在 postExecute
方法中)
此外,我建议为 AsyncTask 使用更专业的类,这样您的代码看起来会更好:
public class WebMethodTask extends AsyncTask<Object, Integer, SummaryModel> {
private Activity source;
public WebMethodTask(Activity activity) {
this.source=activity;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(SummaryModel model) {
super.onPostExecute(model );
TextView txtCurrentWeight = (TextView)source.findViewById(R.id.txtCurrentWeight);
TextView txtWeightChange = (TextView)source.findViewById(R.id.txtWeightChange);
TextView txtAvgPerWeek = (TextView)source.findViewById(R.id.txtAvgPerWeek);
if(model.ErrorMessage.length()==0)
{
txtCurrentWeight.setText(model.CurrentWeight);
txtWeightChange.setText(model.WeightChange);
txtAvgPerWeek.setText(model.Average);
}
else
{
Toast.makeText(c, model.ErrorMessage, Toast.LENGTH_LONG).show();
txtCurrentWeight.setText("");
txtWeightChange.setText("");
txtAvgPerWeek.setText("");
}
}
@Override
protected SummaryModel doInBackground(Context ... params) {
Context c = params[0];
return MobileController.FetchSummary(c);
}
}
编辑:添加对您的 Activity 的引用,以考虑您的最后评论。
但是,如果您的 acynctask 可能很长,那么保留对 Activity 的引用可能不是一个好主意。
创建一个接受一些 displayModel(CummaryModel)
方法的监听器类将是一个更好的设计,如果 Activity 没有在同时……
关于android - 如何重构我的代码以使用 AsyncTask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14564955/