我花了很长时间才使它起作用,但这显然不是最佳实践。简而言之,当我的 AsyncTask 完成时,我需要显示一个对话框,但是 getApplicationContext() 不起作用,在创建 AsyncTask 时也没有将它作为参数传递。因此,我在 AsyncTask 类中为上下文声明了一个公共变量,并在执行之前对其进行了设置:
private OnClickListener clickLoadRefs = new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("H","Clicked Load Refs");
RefreshRefPoints refreshRefPoints = new RefreshRefPoints();
refreshRefPoints.myCtx=v.getContext();
refreshRefPoints.execute(v.getContext());
}
};
private class RefreshRefPoints extends AsyncTask<Context, Integer, Integer> {
private Integer nPoints=0;
public Context myCtx;
private ProgressDialog pd;
protected Integer doInBackground(Context... ctx) {
Log.d("H","doInBackground()");
dbHelper.clearRefPoints();
requestRefPoints();
nPoints = parseRefPointsCSV();
return nPoints;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPreExecute()
{
pd = ProgressDialog.show(myCtx, "Refreshing Reference Points", "Loading...", true,false);
Log.d( "H", "onPreExecute()" );
}
protected void onPostExecute(Integer result) {
pd.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(myCtx);
builder.setTitle("Reference points refresh complete");
builder.setMessage(result+" records loaded");
builder.setPositiveButton("OK",null);
builder.show();
Log.d("H","onPostExecute()");
}...etc
任何人都可以告诉我传递上下文的正确方法吗?
谢谢