Android AsyncTask访问Activity Context的更好方法

时间:2012-08-31 11:26:58

标签: android android-asynctask

我花了很长时间才开始工作,但这显然不是最好的做法。简而言之,我需要在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

有人能告诉我传递上下文的正确方法吗?

由于

3 个答案:

答案 0 :(得分:12)

定义构造函数方法并将参数传递给上下文。会更好。

这就是我的意思:

private class RefreshRefPoints extends AsyncTask<Void, Integer, Integer> {

    private Integer nPoints=0;
    private Context myCtx;
    private ProgressDialog pd;

    public RefreshRefPoints(Context ctx){
        // Now set context
        this.myCtx = ctx;
    }

}

就是这样。

答案 1 :(得分:10)

您也可以使用YourActivityName.this来引用活动Context。因为Activites扩展了Context,所以它有效。

答案 2 :(得分:2)

将构造函数中的上下文传递为

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;
}