I have a compass application which is using orientation sensor and every time the sensor changes my compass view is being invalidated in order to rotate towards north. My compass is a 444px x 444px bitmap. The problem I’m facing is that whenever the sensor changes and you see the compass rotating it’s lagging, basically poor fps. I’ve tried to use a surface view instead and to change the SENSOR_DELAY, without any change. Would love if someone could help me figure out the answer to this problem.
Registering sensor
orientation = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
sm.registerListener(this, orientation, SensorManager.SENSOR_DELAY_UI);
Whenever sensor changes
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (compass != null) {
float[] v = event.values;
north = v[0];
compass.setNorth(-north);
}
}
Methods in the compass view
public void setNorth(float n) {
north_changed = true;
north = n;
invalidate();
}
private void drawBackground(Canvas canvas) {
canvas.save();
if (north_changed == true) {
canvas.rotate(north);
}
float maxwidth = (float) (backgroundTexture.getWidth() * Math.sqrt(2));
float maxheight = (float) (backgroundTexture.getHeight() * Math.sqrt(2));
float ratio = Math.min(w / maxwidth, h / maxheight);
int width = (int) (backgroundTexture.getWidth() * ratio);
int height = (int) (backgroundTexture.getHeight() * ratio);
canvas.drawBitmap(
backgroundTexture,
new Rect(0, 0, backgroundTexture.getWidth(), backgroundTexture
.getHeight()), new RectF(-width / 1.5f, -height / 1.5f,
width / 1.5f, height / 1.5f), facePaint);
canvas.restore();
}
onDraw
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if (showCompass) {
w = getWidth();
h = getHeight();
cx = w / 2;
cy = h / 2;
canvas.translate(cx, cy);
loadImages();
drawBackground(canvas);
}
}
You can try this
replace:
sm.registerListener(this, orientation, SensorManager.SENSOR_DELAY_UI);
with this:
sm.registerListener(this, orientation, SensorManager.SENSOR_DELAY_FASTEST);
And if you want some extra smoothness
replace:
with this: