系统相关
首页 > 系统相关> > Java-进度对话框android泄漏Windows错误

Java-进度对话框android泄漏Windows错误

作者:互联网

我在显示带有AsyncTask的进度对话框时遇到问题:

Activity has leaked window com.android.internal.policy.PhoneWindow$DecorView{8cee959 V.E...... R......D 0,0-1026,252} that was originally added here

这是我的异步任务:

public class MyClientTask extends AsyncTask<Void, Void, Void> {
    private ProgressDialog progressDialog = null;

    private Context mContext;

    MyClientTask(Context mContext) {
        this.mContext = mContext;

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setMessage("Working ...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        try {
            wait(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }

    }
}

这是我的活动:

public class ConnectionActivity extends Activity {

    final private Context mContext = this;
    private Button buttonConnect;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R .layout.activity_socketconnection);

        buttonConnect = (Button) findViewById(R.id.buttonConnect);

        buttonConnect.setOnClickListener(getConnectOncOnClickListener());
    }

    private OnClickListener getConnectOncOnClickListener() {
        return new OnClickListener() {

            @Override
            public void onClick(View v) {
                MyClientTask myClientTask = new MyClientTask(mContext);
                try {

                        myClientTask.execute();
                        myClientTask.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }

            }
        };
    }

}

我搜索了解决方案,但仍然无法正常工作

解决方法:

一些提示:

>在您的活动中保留对ProgressDialog的引用,并添加公共方法来显示/隐藏它;
>使用WeakReference< Context>在您的AsyncTask中,让垃圾收集器完成工作;
>摆脱阻塞UI线程的myClientTask.get().

标签:progressdialog,android-asynctask,java,android
来源: https://codeday.me/bug/20191118/2027970.html