Android: reading accelerometer without memory allocation?

不羁岁月 提交于 2019-12-09 06:52:42

问题


I am developing a game for Android (2.1+), using the accelerometer as user input. I use a sensor listener that I register at the beginning of the activity with the sensor manager, as follows:

mSensorManager.registerListener(SystemRegistry.inputSystem.mSensorListener,
                                accSensor, SensorManager.SENSOR_DELAY_UI);  

That works well and I just read the accelerometer values in onSensorChanged(SensorEvent event) in order to use it in my game loop:

public void onSensorChanged(SensorEvent event){
     accX = event.values[0];
     accY = event.values[1];
     accY = event.values[2];
 }

I am writing a real-time game so I am trying to avoid any memory allocation in my code, since I want to minimize the garbage collection. The problem is that every time there is a SensorEvent, the sensor manager actually allocates memory. Here is for example the output of the ddms allocation tracker:

51  28  android.hardware.SensorEvent    9   android.hardware.SensorManager$ListenerDelegate createSensorEvent   
50  28  float[] 9   android.hardware.SensorEvent    <init>  

which shows 28*2=56 bytes allocated at every event. This seems to have the effect of triggering the garbage collector quite often, which induces some lags... So here is my question: is there a way to achieve the same thing (getting the current acceleration vector), without allocating any memory? Is there a way to actually read on demand the values of this vector without waiting for an event?


回答1:


Sounds like something we need to fix on our side, I'll file a bug internally.




回答2:


I believe this problem only occurs when there is more than one Sensor registered to a SensorEventListener. I think a workaround would be to use a different SensorEventListener per Sensor.

Also make sure to NOT register the SAME Sensor with two different SensorEventListener -- there was a bug in that case that got fixed in Gingerbread.

Another, less attractive, option would be to use the Gingerbread NDK, which doesn't have this issue.

I hope this helps.



来源:https://stackoverflow.com/questions/4979256/android-reading-accelerometer-without-memory-allocation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!