【发布时间】:2017-01-29 06:43:48
【问题描述】:
我是 Android 编程的新手,所以希望你能帮助我。我有这个AsyncTask,它通过OnClickListener 事件和doInBackground() 方法执行,是Thread,它不在UI 线程上运行。
AsyncTask通过OnClickListener执行:
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MyAsyncTask().execute();
}
});
AsyncTask 是MainActivity 的子类:
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
ProgressDialog progress;
@Override
protected void onPreExecute() {
// Show ProgressDialog before the task starts.
progress = new ProgressDialog(MainActivity.this);
progress.setMessage("Running...");
progress.setCancelable(false);
progress.show();
}
@Override
protected Void doInBackground(Void... params) {
// Since the thread is not running on the UI thread,
// I have to use the runOnUiThread() method so the
// app won't crash when the thread is complete.
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
new ThreadFromOtherClass(arg1, arg2);
} catch (Exception e) {
Log.e("Exception", "Something happened.", e);
}
}
});
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
// Hide the dialog when the task ends.
progress.dismiss();
}
}
我在运行Thread 时没有遇到任何问题,但ProgressDialog 在任务执行期间没有显示。但是,如果我排除 runOnUiThread() 方法,则会出现对话框,但应用程序会在 Thread 完成时崩溃。知道我做错了什么吗?
【问题讨论】:
-
像这样从
doInBackground()调用runOnUiThread()完全违背了使用AsyncTask的目的。崩溃的可能是 UI 更新,您需要将其移至onPostExecute()。 -
@MikeM。是的,但我不知道如何运行
Thread而不会出现任何崩溃问题...... -
@HumblePotatoII,检查我使用构造函数发布的答案。
-
^ @MikeM。关于你不应该在异步任务中使用 runOnUiThread() 的事实是正确的。如果您需要有关进度对话框的帮助,仍然欢迎在您的应用迷恋时发布日志。
-
@yotamhadas 但是当
Thread完成时,我遇到了应用程序崩溃的问题。还有其他方式/想法吗?
标签: android multithreading android-asynctask