[英]Java android OutOfMemoryError in SensorEventListener
我在其中实现了SensorEventListener的类中有一个OutOfMemoryError。 在这里的日志中,有时会出现OutOfMemoryError
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
gravity = event.values;
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
geomagnetic = event.values;
}
if (gravity != null && geomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, gravity, geomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
float azimuthInRadians = orientation[0];
float azimuthInDegress = (float)Math.toDegrees(azimuthInRadians);
if (azimuthInDegress < 0.0f) {
azimuthInDegress += 360.0f;
}
azimuth = (int) azimuthInDegress;
Hawk.put(HawkConst.AZIMUTH, azimuth);
}
}
}
这是我的日志。 有时我有此错误,但并非总是如此
at com.android.internal.util.FastXmlSerializer.<init>(FastXmlSerializer.java:55)
at com.android.internal.util.XmlUtils.writeMapXml(XmlUtils.java:177)
at android.app.SharedPreferencesImpl.writeToFile(SharedPreferencesImpl.java:596)
at android.app.SharedPreferencesImpl.access$800(SharedPreferencesImpl.java:52)
at android.app.SharedPreferencesImpl$2.run(SharedPreferencesImpl.java:511)
at android.app.SharedPreferencesImpl.enqueueDiskWrite(SharedPreferencesImpl.java:532)
at android.app.SharedPreferencesImpl.access$100(SharedPreferencesImpl.java:52)
at android.app.SharedPreferencesImpl$EditorImpl.commit(SharedPreferencesImpl.java:454)
at com.orhanobut.hawk.SharedPreferencesStorage.put(SharedPreferencesStorage.java:23)
at com.orhanobut.hawk.Hawk.put(Hawk.java:63)
at pl.***.****.worker.Tracker.onSensorChanged(Tracker.java:154)
at android.hardware.SystemSensorManager$SensorEventQueue.dispatchSensorEvent(SystemSensorManager.java:474)
at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
at android.os.MessageQueue.next(MessageQueue.java:138)
at android.os.Looper.loop(Looper.java:131)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(NativeStart.java)
似乎您在onSensorChanged()回调中做了一些繁重的工作。 因此,在回调中,您正在调用SharedPreferences。 不好的原因是,每次传感器有新值时都会调用onSensorChanged(),这取决于您的侦听器配置,可能每秒发生多次。 这意味着您试图每秒多次保存到文件(带有共享首选项)。 这需要在事物的常规方面进行大量分配,并可能导致OutOfMemoryError。
为了解决这个问题,我建议将值存储在变量中,并且仅以一定的固定间隔或基于某些事件(按钮单击,生命周期事件等)执行保存。
我还看到您正在使用.commit()阻止线程直到保存文件,您可以尝试使用.apply()来将提交动作移至其他线程。 无论如何,您都需要限制使用Sharedpreferences的次数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.