gpt4 book ai didi

java - 在抽象的非 Activity 类中检索上下文

转载 作者:搜寻专家 更新时间:2023-11-01 08:16:04 24 4
gpt4 key购买 nike

我正在尝试构建 AsyncTask 的抽象实现,我想插入一个自定义 ProgressDialog。如何获取 Activity 类之外的上下文?

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

最佳答案

您可以将它传递给构造函数:

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

关于java - 在抽象的非 Activity 类中检索上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4821849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com