在 onTouchEvent 块中休眠 onSensorChanged

发布于 2024-10-02 00:49:29 字数 331 浏览 3 评论 0原文

我正在制作一个将利用触摸事件和传感器事件的应用程序。触摸事件的问题在于它们频繁触发,从而消耗大量的 CPU 时间。常见的解决方案是执行 Thread.sleep 使其冷却。

然而,如果想在同一个 Activity 中同时使用 onTouchEvent 和 onSensorChanged,那么应用 Thread.sleep hack 也会减慢 onSensorChanged 的​​速度。这显然是由同一个 (ui) 线程调用两个方法引起的。

有没有某种方法可以从与 ui 不同的线程调用 onTouchEvent,这样就可以在不减慢 onSensorChanged 速度的情况下执行 Thread.sleep 技巧?

I'm making an application which will utilize both touchevents and sensorevents. The problem with touchevents is that they fire off very often, and thereby consumes massive amounts of CPU time. The common solution is to do a Thread.sleep to make it cool down.

However, if one wants to use both the onTouchEvent and onSensorChanged in the same activity, applying the Thread.sleep hack will also slow down onSensorChanged. This is obviously caused by the two methods being called from the same (ui) thread.

Is there some way to call onTouchEvent from a different thread than the ui, so one could do the Thread.sleep trick without slowing down onSensorChanged as well?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浊酒尽余欢 2024-10-09 00:49:29

“常见的解决方案是执行 Thread.sleep 使其冷却。”

你从哪里听说的?在主线程(也称为 EDT - 事件调度线程)上休眠是不可接受的。 Android 正在重绘屏幕并在此线程上执行各种任务。睡觉会让它失去反应,恕我直言,这是一个不好的做法。

如果 onTouchEvent() 触发得太频繁,那么只需在代码中过滤它们 = 如果自上次事件以来至少还没有过去 X 时间,则不执行任何操作。

long lastTime = 0; // field in you class holding event handler

// inside your onTouchEvent handler
if(System.getCurrentTimeMillis() - lastTime < XXX)
    return;
 lastTime = System.getCurrentTimeMillis();

"The common solution is to do a Thread.sleep to make it cool down."

Where did you hear that? Sleeping on the main thread (also called EDT - event dispatching thread) is not acceptable. Android is redrawing the screen and doing all kinds of tasks on this thread. Sleeping it can make it unresponsive and is IMHO a bad practice.

If onTouchEvent() are firing too often then just filter them in your code = do nothing if at least X amount of time has not passed since last event.

long lastTime = 0; // field in you class holding event handler

// inside your onTouchEvent handler
if(System.getCurrentTimeMillis() - lastTime < XXX)
    return;
 lastTime = System.getCurrentTimeMillis();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文