我有 MainActivity.java
Activity 类,它在应用程序启动时加载。我在名为 ServerOperation.java
的单独文件中使用 asyncTask
方法。我需要在 asyncTask 的 onPreExecute
方法中显示进度条。我正在使用以下代码,但它不起作用并且应用程序崩溃:
public class ServerOperation extends AsyncTask<Void, Void, ArrayList<Job>> {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
MainActivity myActivity = new MainActivity();
progressDialog = ProgressDialog.show(myActivity.getApplicationContext(),"PLEASE WAIT","LOADING JOBS...", true);
}
}
我应该如何让 progressDialog 在主要 Activity 上工作?
谢谢。
最佳答案
您应该永远不要创建 Acitvity 类的实例。它不是普通的 java 类。
可以将Activity Context传递给Asynctask的构造函数
调用 Aysnctask 为
new ServerOperation(MainActivity.this).execute(params);
在主 Activity 中
然后
Context mContext;
public ServerOperation (Context context)
{
mContext =context;
}
然后
progressDialog = ProgressDialog.show(mContext,"PLEASE WAIT","LOADING JOBS...", true);
关于android - 异步任务 OnPreExecute 方法 Android 中的进度对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24637799/