【问题标题】:How would I use a Looper with an asyncTask?我如何将 Looper 与 asyncTask 一起使用?
【发布时间】:2013-08-05 12:41:24
【问题描述】:

如何将 Looper 与 asyncTask 一起使用?

调用 doImBackground 方法以编程方式创建名为 MyResultTable 的 TableLayout。反过来,MyResultTable 有一个处理程序,在MotionEvent.ACTION_MOVE 期间由 onTouch 调用。

在收到有关在 asynchTask 中使用句柄的投诉后,我决定在 UIThread 上运行处理程序。但这导致我的 onTouch 方法响应缓慢。所以我的问题是,如何将循环器与 asyncTask 一起使用?

UIThread 代码:

activity.runOnUiThread(new Runnable() {
  public void run() {
handler.post(mResizeViews);
  }
});

我的 Looper 尝试:(不工作:空白屏幕)

protected MyResultTable doInBackground(Void... params) {
            Looper.prepare();
            MyResultTable table = new MyResultTable(context, other);
            Looper.loop();
            return tabl;
        }

【问题讨论】:

    标签: android android-layout event-handling android-asynctask looper


    【解决方案1】:

    如何将 Looper 与 asyncTask 一起使用?

    你不会的。

    调用 doImBackground 方法以编程方式创建名为 MyResultTable 的 TableLayout。

    这不是doInBackground() 的合适角色。使用doInBackground() 处理缓慢的事情:网络I/O、磁盘I/O 等。使用onPostExecute() 根据doInBackground() 检索到的数据生成UI(“名为MyResultTable 的TableLayout”)。

    反过来,MyResultTable 有一个处理程序,在 MotionEvent.ACTION_MOVE 期间由 onTouch 调用。

    这没有多大意义。您使用Handler 将事件从后台线程转发到主应用程序线程。您的onTouchEvent() 在主应用程序线程上被调用,因此它不需要Handler

    【讨论】:

    • 你确定吗?我知道你通常有很好的答案。但我总是在后台组装我的表格,然后使用onPostExecute 将自定义表格传递给持有它的linearLayout。否则 android 往往会说我的 UI 工作太多。
    • @CoteMounyo:“否则 android 往往会说我的 UI 工作太多了”——使用 Traceview 等工具找出性能问题背后的真正原因。
    • 好的。所以我试试你的建议。它有效(+1)。 android 没有抱怨 UI 工作很努力。但我的滑块仍然不流畅。开始移动然后跳转到用户手指移位的位置需要一段时间。参考stackoverflow.com/questions/17958671/…
    猜你喜欢
    • 2011-09-12
    • 2017-11-17
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多