我正在尝试构建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;
}
}
答案 0 :(得分:4)
您可以将其传递给构造函数:
abstract public class DataPoller extends AsyncTask<Void, Void, Void> {
...
Context mContext;
...
DataPoller(Context context){
super();
this.mContext = context;
}
...
}