【问题标题】:Error using Thread.sleep in an Asynctask在 Asynctask 中使用 Thread.sleep 时出错
【发布时间】:2017-02-24 07:36:55
【问题描述】:

我正在尝试在我的 Asynctask 中添加一些睡眠时间,因为现在我的 ProgressDialog 在没有太多数据要加载的情况下太快了。

我试过了:

@Override
protected Boolean doInBackground(Void... params) {
    try {
        progressDialog.setMessage("Loading first thing...");
        firstThing();
        progressDialog.incrementProgressBy(1);
        Thread.sleep(500);
        //...repeat above four lines a few times for second, third, fourth thing, etc
        return true;
    }
    catch (Exception e) {
        Log.e("MyClassName", "There was an error: " + e);
        return false;
    }
}

我收到错误“只有创建视图的原始线程才能接触其视图。”

【问题讨论】:

  • 您正在更新 Android 主线程之外的 UI 视图。 DoInBackground 在其他线程中运行,因此您无法更新视图。所以,如果你想更新你应该使用的视图,onPreExectute、onPostExecture 或 onProgressUpdate。检查developer.android.com/reference/android/os/AsyncTask.html
  • 我也有那些被覆盖的,是的,我只是没有在这里发布这些

标签: android multithreading android-activity android-asynctask sleep


【解决方案1】:

您必须覆盖 onProgressUpdate()doInBackground()

            // do this before asynctask.execute();
            progressDialog.setMessage("Loading first thing...");


@Override
protected Boolean doInBackground(Void... params) {
    try {
        firstThing();
        Thread.sleep(500);
        // this method invokes onProgressUpdate on the UI thread
        publishProgress();
        return true;
    }
    catch (Exception e) {
        Log.e("MyClassName", "There was an error: " + e);
        return false;
    }
}

@Override
protected void onProgressUpdate(Void... params) {
    progressDialog.incrementProgressBy(1);
}

【讨论】:

  • 您也可以考虑将下载的大小显示为这样的百分比。发布进度(百分比);和 pDialog.incrementProgressBy(params[0]);
  • publishProgress() 应该是什么样子?
  • 没关系,显然它是一个内置函数。无论如何,在进行编辑后,我仍然遇到同样的错误。或者可能是因为我在后台线程中设置了消息。如何根据我在加载过程中的位置更改消息?
  • firstThing() 是做什么的?它会更新用户界面吗?您无法更新doInBackground() 中的 UI,因为它是一个非 UI 线程。这就是保持 UI 响应的原因,因为当您的后台任务正在执行操作时,UI 线程仍然可以运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多