Android的 - 如何运行你的传感器(服务,螺纹,活动)? [英] Android - how to run your sensor ( service, thread, activity )?

查看:160
本文介绍了Android的 - 如何运行你的传感器(服务,螺纹,活动)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个简单的倾斜游戏。让球翻身的方向,你倾斜你的手机屏幕上。

I'm writing a simple tilting game. Make a ball roll over the screen in the direction you tilt your phone.

于是我下载了如何获得传感器数据为例,工作正常(我用一个旋转矩阵,以避免欧拉角的问题)。但后来我试图把它变成一个更大的应用程序,我有一些麻烦得到它的工作。

So I downloaded an example on how to get the sensor data and that works fine (I use a rotation matrix to avoid the Euler angle problem). But then I tried to put it into a bigger app and I have some trouble getting it to work.

我的第一个想法是运行在一个单独的线程中的倾斜传感器,但 我班:公共类TiltSensor扩展Thread实现SensorEventListener 不工作很好地。 我得到一个回合的值,然后停止。

My first idea was to run the tilt sensor in a separate thread but my class: public class TiltSensor extends Thread implements SensorEventListener is not working to well. I get one round of values then it stops.

你将如何实现这个程序?

How would you implement this app?

我不想阻止用户界面线程,所以我想我需要一个单独的线程(GameHandler)来运行游戏,然后我打电话runOnUithread并从那里查看无效。我还分隔板重presentation从View所以我会重新present屏幕作为一个矩阵,那么该视图使用矩阵知道屏幕应该是什么样子。 但我不能确定什么是最好的方式来实施TiltSensor。如果在一个单独的线程或同一个线程的GameHandler运行?我如何确保实际的SensorManager调用onSensorChanged在GameHandler线程?

I don't want to block the UI thread so I'm thinking I need a separate thread (GameHandler) to run the game and then I call runOnUithread and from there invalidate the View. I'd also separate the board representation from the View so I'd represent the screen as a matrix and then the view would use that matrix to know how the screen should look. But I am unsure what the best way to implement the TiltSensor. Should it run in a separate thread or the same thread as the GameHandler? How do I make sure the SensorManager actually calls the onSensorChanged in the GameHandler thread?

推荐答案

在我卑微的经验,你应该:

In my humble experience, you should:

A)注册您的SensorListener在你的主线程正常,但要产卵两(或需要)WorkerThreads在它的构造。

A) Register your SensorListener on your main thread normally, but make it spawn two (or as needed) WorkerThreads on its constructor.

B)获取两个线程的尺蠖参考,让他们活着,等待以后的请求。

B) Get the looper reference of both threads, to keep them alive waiting for future requests.

B)听你onSensorChanged在你的主线程正常,但什么都不做其他(这很重要),那么值的副本委托给将处理你的游戏逻辑的一个新的Runnable对象。

B) Listen to your onSensorChanged on your main thread normally, but do NOTHING OTHER (this is important) then delegate a copy of the values to a new runnable object that will process your game logic.

C)入队新的Runnable对象对你的WorkerThread尺蠖参考相应。

C) Enqueue your new runnable object on your WorkerThread looper reference accordingly.

D)使可运行(即已经把你的主线程)做他们必须做的更改同步到可由谁是有兴趣在更新你的意见征询单身。

D) Make the runnables (that are already off your main thread) do what they have to do and synchronize changes to a singleton that may be consulted by who is interested in updating your views.

这篇关于Android的 - 如何运行你的传感器(服务,螺纹,活动)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆