如何确保代码在 Android MapActivity 项目中的 UI 线程上执行或不执行?
我正在开发一个基于 Android 地图的应用程序,但我遇到了一些稳定性问题,我的研究使我相信我需要确保屏幕更新是在 UI 线程上进行的。
我的应用程序有来自 GPS 侦听器(我想将其配置为单独的线程)和 UDP 侦听器(它已经是单独的线程)的数据,并且它具有一组常用的 Android 软件生命周期方法,但我 地图叠加层 (a) 的代码
一定是缺乏经验什么的,因为我不知道在哪里放置更新UI 线程上的 ,
(b) 以重复的方式。
我对轮询或事件驱动的过程(可能基于计时器,或传入数据的到达)没有偏好,因此任何类型的建议都将被感激地接受。
有人有什么想法吗?
谢谢,
R。
How do I ensure code is or is not executed on the UI thread in an Android MapActivity project?
I am developing an Android map-based application, but I have experienced some stability issues and my research has led me to believe I need to ensure that screen updates are carried out on the UI thread.
My app has data coming in from a GPS listener (which I would like to configure as a separate thread) and a UDP listener (which is already a separate thread), and it has the usual set of android software life cycle methods, but I must be inexperienced or something, because I have no idea where to put code that updates the map overlays
(a) on the UI thread,
(b) in a recurring manner.
I have no preference between a polling or an event-driven process (timer-based perhaps, or the arrival of incoming data), so suggestions of either type will be gratefully accepted.
Anyone got any ideas??
Thanks,
R.
发布评论
评论(3)
阅读这篇关于无痛线程的文章,特别是Activity.runOnUIThread
Read this post on painless threading, particularly the Activity.runOnUIThread
您还可以查看处理 UI 线程中的昂贵操作。在您的情况下,您可以执行以下操作:
public class MyActivity extends Activity {
}
You can also look at this Handling Expensive Operations in UI Thread. In your case you can do the following:
public class MyActivity extends Activity {
}
android 位置服务是一个在后台运行的模块,因此您不需要将其分离到另一个线程中。
但是,我根本不建议您使用 java 线程类或可运行接口,而是使用异步任务来为您执行所有线程管理。请查看 Android 开发人员博客,Painless Threading。
要在位置更新时更新 UI 线程,您可以使用更新处理程序。每次有可用的 GPS 数据时,都会将一条消息传输到主 ui 线程中的更新处理程序。
例如
,在您的主要活动类别中:
The android location service is a module that runs in the background so you do not need to seperate it in another thread.
However I would not recommend you to use java thread class or runnable interface at all, use async task instead which performs all the thread management for you. Have a look at the android developers blog, Painless Threading.
To update your UI thread on location updates you can use update handlers. Everytime there is GPS data avialable a message is transmitted to the update handler in you main ui thread.
E.g.
And in your main activity class: