我有一个简单的Android应用程序,当我按下“激活”按钮时应显示进度对话框。基本上,当我按下“激活”时,应用程序将在检测附近的传感器时显示进度对话框。我想在检测传感器时更新进度对话框消息。以下代码在片段内实现。
但是我的代码没有显示进度对话框。当我按下“按钮”时,我什么都没看到。它似乎冻僵了。
@Override
public void onClick( View v) {
v.setEnabled(false);
activateButton.setEnabled(true);
final Activity activity = getActivity();
final ProgressDialog pd = new ProgressDialog(activity);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
pd.setTitle("Activating...");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(false);
pd.show();
int count = 1;
pd.setMessage("Detecting sensors...\n");
while (true) {
if (count >= 10) {
break;
}
count++;
try {
pd.setMessage("Detected " + count + "=" + " sensor. \n");
Thread.sleep(1000 * 1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
pd.dismiss();
}
});
根据评论,我改为此。
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
ProgressDialog pd;
@Override
protected void onPreExecute() {
pd = new ProgressDialog(getActivity());
pd.setTitle("Activating...");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(false);
pd.show();
}
@Override
protected Void doInBackground(Void... arg0) {
int count = 1;
pd.setMessage("Detecting sensors...\n");
try {
Thread.sleep(1000 * 1);
} catch (InterruptedException e1) {
//
}
StringBuffer txt = new StringBuffer();
txt.append(".....");
while (true) {
if (count >= 10) {
break;
}
count++;
pd.setMessage("Detected " + count + "=" + " sensor. \n");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (pd != null) {
pd.dismiss();
activateButton.setEnabled(true);
}
}
};
task.execute((Void[]) null);
但是当这段代码运行时,我在这一行中得到了这个错误(pd.setMessage(“Detected”+ count +“=”+“sensor。\ n”);)。
引起:android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。
如果有人可以指出它出错的地方会很有帮助。
感谢。
答案 0 :(得分:2)
您正在从后台线程更新视图。从方法&#39; doInBackground&#39;你应该打电话给'publishProgress&#39; mehtod然后更新进度对话框&#39; onProgressUpdate&#39; (将在UI线程中执行)。检查以下代码:
new AsyncTask<Void, String, Void>() {
public ProgressDialog mProgress;
@Override
protected void onPreExecute() {
mProgress = ProgressDialog.show(getContext(), "Progress", "Please Wait", true);
}
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(1000);
publishProgress("progress 1");
Thread.sleep(2000);
publishProgress("progress 2");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
mProgress.dismiss();
}
@Override
protected void onProgressUpdate(String... values) {
mProgress.setMessage(values[0]);
}
};