2011-01-27 71 views
2

我想構建AsyncTask的抽象實現,並且想插入自定義的ProgressDialog。我怎樣才能獲得活動類以外的環境?在一個抽象的非活動類中檢索上下文

abstract public class DataPoller extends AsyncTask<Void, Void, Void> { 

Context mContext = getApplicationContext(); 

ProgressDialog dialog = new ProgressDialog(mContext); 

@Override 
protected void onPreExecute() { 



    dialog.setMessage("Polling data..."); 
    dialog.show(); 


} 


@Override 
protected void onPostExecute(Void unused) { 

    if (dialog.isShowing()) { 

    dialog.dismiss(); 

    } 


} 

@Override 
protected Void doInBackground(Void... params) { 

    int tmp=0; 

    for (int ii = 0; ii<1000; ii ++) { 

    for (int jj = 0; jj<1000; jj ++) { 

    tmp = (tmp + 3) % 167;  

    } 

    } 
    return null; 
} 

}

回答

4

你可以把它傳遞到構造函數:

abstract public class DataPoller extends AsyncTask<Void, Void, Void> { 
    ... 
    Context mContext; 
    ... 
    DataPoller(Context context){ 
     super(); 
     this.mContext = context; 
    } 
    ... 
}