java - 异步任务的进度对话框

标签 java android android-asynctask progressdialog

我创建了三个类,即 Mainactivity,它将上下文传递给扩展至 Asynctask 的服务器类。有一个名为setting的类,它调用服务器类来更新服务器中的数据。

用于传递上下文的 Mainactivity 代码:

Server.setActivityContext(getApplicationContext());

服务器类代码:

public class Server extends AsyncTask<Void, Void, Void> {


static Context mycontext;

public static void setActivityContext(Context receivingcontext) {
    mycontext = receivingcontext;
}

Dialog dialog;

@Override
protected void onPreExecute() {
    super.onPreExecute();
    dialog = ProgressDialog.show(mycontext, "Updating ..", "Please wait......");
}

@Override
protected Void doInBackground(Void... params) {
//Background task       
        return null;

}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    dialog.dismiss();
}
}

调用此服务器类时,我在 progressdialog 上收到错误。尽管上下文已传递,但您可以建议任何修复。

错误:

 FATAL EXCEPTION: main

    Process: jss.smartapp, PID: 22915 android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

最佳答案

不要使用静态方法。使用正确的构造函数。

public class ServerTask extends AsyncTask<Void, Void, Void> {

    private Context mycontext;

    public ServerTask(Context c) {
        this.mycontext = c;
    } 

调用它

new ServerTask(MainActivity.this).execute();

关于java - 异步任务的进度对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41321725/

相关文章:

Android Facebook-SDK

android - 零数量忽略复数定义

Android 我可以运行多少个线程?

Android 变量在 AsyncTask 中交换值

android - 带有 RecyclerView 的 SwipeRefreshLayout 在 Fragment 中不起作用

JavaCV Canvas 保持空白

java - 使用Jinput弹出JFrame WIndow警报

android - ViewGroup{TextView,...}.getMeasuredHeight 给出的错误值小于实际高度

java - IDEA 插件 : PersistentStateComponent not persisting xml

java - jackson 序列化 : ignore empty values (or null)