嗨,我的应用程序中有 AsyncTask,但我无法更改其 setMessage
例如:-
private class ProgressTask1 extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask1(MainActivity mainActivity) {
context = mainActivity;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Checking system...");
this.dialog.setCancelable(false);
this.dialog.setTitle("Please Wait...");
this.dialog.setIcon(R.drawable.ic_launcher);
this.dialog.show();
}
现在我想要更改 setmessage,我尝试将其添加到 doinbackground
protected Boolean doInBackground(final String... args) {
dothis1();
this.dialog.setMessage("one done...");
dothis2();
this.dialog.setMessage("two done...");
但这使应用程序强制关闭,并且不要将其评价为低,因为我尽了最大努力并搜索了论坛,但能够解决此问题,因此在这个不错的社区请求帮助:)
有人可以帮忙吗? :)
错误
05-13 23:36:34.899: E/AndroidRuntime(2454): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
最佳答案
ohmm,您不应该从后台线程更新 UI。要更新 UI,您可以通过两种方式进行:
1) 使用publishProgress (Progress...values)
和onProgressUpdate(...)
。为此,您必须更改 AsynTask
类:
private class ProgressTask1 extends AsyncTask<String, String, Boolean> {
//.......... //your init
@Override
protected Boolean doInBackground(String... params) {
//your background handle
//publish to change UI
String toShow = "your_string_here";
publishProgress(toShow);
//return ...; //your return value
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//detect message and show it.
//this.dialog.setMessage(values[0]);
}
}
2) 使用onPostExecute(....)
:
private class ProgressTask1 extends AsyncTask<String, Void, Boolean> {
//.......... //your init
@Override
protected Boolean doInBackground(String... params) {
//your background handle
//return ...;//your return value
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
String toShow = "your_string_here";
//this.dialog.setMessage(toShow);
}
}
关于java - 一段时间后AsyncTask setMessage android java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30221847/