我花了相當長的一段時間纔得到這個工作,但這顯然不是最佳實踐。簡而言之,當我的AsyncTask完成時,我需要顯示一個對話框,但getApplicationContext()不起作用,在創建AsyncTask時也不會將其作爲參數傳遞。所以,我宣佈了上下文中的公共變量在我的AsyncTask類並將它之前,我執行:Android 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
任何人可以只顯示我傳遞上下文的正確方法?在構造函數
private OnClickListener clickLoadRefs = new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("H","Clicked Load Refs");
RefreshRefPoints refreshRefPoints = new RefreshRefPoints(Your_ActivityName.this);
refreshRefPoints.myCtx=v.getContext();
refreshRefPoints.execute(v.getContext());
}
};
private class RefreshRefPoints extends AsyncTask<Void, Integer, Integer> {
private Integer nPoints=0;
public Context myCtx;
private ProgressDialog pd;
public RefreshRefPoints (Context ctx) {
myCtx = ctx;
}
但它給內存泄漏 –