![](/img/trans.png)
[英]Trying to circumvent NetworkOnMainThreadException on AsyncTask because of ProgressDialog
[英]Trying to display a ProgressDialog in AsyncTask executed in a MapActivity
我有一个MapActivity,在onCreate()中有类似的代码:
if(...) {
...
new FirstAsyncTask(id, this).execute((Object[]) null);
...
} else {
...
myLocationOverlay.runOnFirstFix(new Runnable() {
new SecondAsyncTask(lat, lon, ActivityName.this).execute((Object[]) null);
}
...
}
FirstAsyncTask和SecondAsyncTask都做不同的事情,但它们都显示了ProgressDialog,如下所示:
public FirstAsyncTask(long id, Context context) {
progressDialog = new ProgressDialog(context);
}
protected void onPreExecute() {
...
progressDialog.show();
}
protected String doInBackground(Object... params) {
...
progressDialog.dismiss();
...
}
这与FirstAsyncTask一起使用,但无论我在对SecondAsyncTask的调用中改变了什么,它总是因此错误而失败:无法在未调用Looper.prepare()的线程内创建处理程序。 我已经尝试将context参数设置为“this”,“ActivityName.this”,getApplicationContext()和getBaseContext()。
我对Android仍然很陌生,所以这种“上下文”的想法让我感到困惑。 我对FirstAsyncTask的工作原理更加困惑,但SecondAsyncTask却没有。 我已经看到这个错误在其他问题中提到了很多,但没有一个答案似乎有效。 有任何想法吗?
编辑:在SecondAsyncTask的构造函数中初始化ProgressDialog时抛出异常。
在onPostExecute()
方法中写下你的对话解码代码,它将运行UI线程中的代码
@Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
以这种方式编写AsyncTask类:
private class FirstAsyncTask extends AsyncTask<String, Void, Void> {
ProgressDialog myDialog = null;
@Override
protected void onPreExecute() {
myDialog = ProgressDialog.show(YourActivityClass.this, "",
"Loading Data...");
return;
}
@Override
protected Void doInBackground(String... urls) {
//Your code which you want to run in background
return null;
}
@Override
protected void onPostExecute(Void result) {
myDialog.dismiss();
return;
}
}
如果您已将AsyncTask类定义为Activity的内部类,则上面的代码可以正常工作。 如果您的AsyncTask类被定义为单独的类,那么您必须将活动的上下文传递给它的构造函数
ProgressDialog myDialog = null;
Context context;
public FirstAsyncTask (Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
myDialog = ProgressDialog.show(context, "",
"Loading Data...");
return;
}
问题出在这里
myLocationOverlay.runOnFirstFix(new Runnable() {
new SecondAsyncTask(lat, lon, ActivityName.this).execute((Object[]) null);
}
SecondAsyncTask正在新生成的线程上构建。 不是UI线程。
在活动中创建一个progressDialog。 然后从Asynctasks访问Activity的progressDialog。
public class MyActivity extends Activity {
ProgressDialog mProgressDialog;
onCreate(...){
mProgressDialog = new ProgressDialog();
}
private class MyAsyncTask extends AsyncTask<...> {
...
onPreExecute(...){
mProgressDialog.show();
}
onPostExecute(...){
mProgressDialog.dismiss();
}
}
private class MyAsyncTask2 extends AsyncTask<...> {
...
onPreExecute(...){
mProgressDialog.show();
}
onPostExecute(...){
mProgressDialog.dismiss();
}
}
不要尝试从doInBackground执行progressDialog.dismiss(),而是将其放在UI线程中运行的postExecute中。
一旦所有这些工作正常,您将需要设置标志,这样您只有在两个任务完成后才会关闭progressdialog。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.