[英]Leaked windows error with progress dialog android
我在使用AsyncTask
顯示progress dialog
時遇到問題:
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
的引用,並添加公共方法以顯示/隱藏它;
在AsyncTask
使用WeakReference<Context>
讓垃圾收集器完成它的工作;
擺脫阻止UI線程的myClientTask.get()
。
這通常發生在您完成活動而不調用dismiss()或首先隱藏對話框時。 我建議你稍微修改你的代碼,在Activity中創建實際的ProgressDialog,然后存儲對它的引用。 在你的onDestroy()中,作為預防措施檢查它是否為空並顯示,然后解除它()。
問題是在后台調用wait()。 請看這里 。
樣品:
private Object lock = new Object();
@Override
protected Void doInBackground(Void... arg0) {
synchronized(lock) {
try {
lock.wait(5000);
// Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.