我正在尝试运行以下代码,但我希望在运行我的进程时显示进度对话框:
public boolean isOnline() {
cm = (ConnectivityManager) mContext.getSystemService(mContext.CONNECTIVITY_SERVICE);
netInfo = cm.getActiveNetworkInfo();
progress_thread = new progress_thread();
progress_thread.execute();
isconnected = false;
if (netInfo != null && netInfo.isConnected()) {
try{
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) isconnected = true;
}catch (MalformedURLException e1) {
e1.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
progress_thread.cancel(true);
if (!isconnected) Toast.makeText(mContext,"Internet Connexion Error", Toast.LENGTH_LONG).show();
return isconnected;
private class progress_thread extends AsyncTask<Void, Integer, Boolean>{
protected void onPreExecute() {
dialog = new ProgressDialog(mContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Tracker...");
dialog.setCancelable(false);
dialog.show();
}
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
protected void onCancelled() {
if (dialog.isShowing()) dialog.dismiss();
}
protected void onPostExecute(Boolean result_ex) {
if (dialog.isShowing()) dialog.dismiss();
}
}
我想要做的是在检查是否有互联网连接的同时运行进度对话框。但我遇到的问题是UI没有刷新,进度对话框没有像我想的那样显示。
答案 0 :(得分:0)
你这样做会通过检查互联网连接来占用UI线程。这使得窗口管理器无法处理您的ProgressDialog
。
您应该将此检查以及显示进度对话框移至AsyncTask
,如下所示:
private void startOnlineCheck() {
ProgressThread progress_thread = new ProgressThread();
progress_thread.execute();
}
private class ProgressThread extends AsyncTask<Void, Void, Void>{
ProgressDialog dialog;
protected void onPreExecute() {
dialog = new ProgressDialog(Activity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Tracker...");
dialog.setCancelable(false);
dialog.show();
}
protected Void doInBackground(Void... params) {
ConnectivityManager cm = (ConnectivityManager) Activity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try{
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
// CODE to run when we're online
return null;
}catch (MalformedURLException e1) {
e1.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
Toast.makeText(Activity.this, "Internet Connexion Error", Toast.LENGTH_LONG).show();
// CODE to run when there's no connection
return null;
}
protected void onPostExecute(Void result) {
if (dialog.isShowing()) dialog.dismiss();
}
}
您还可以将构造函数中的Context
传递给ProgressThread
。
请记住,如果ProgressThread
是Activity
的内部类(通常是这种情况),您可以使用ProgressThread
的任何方法调用该活动的任何方法。