I want to point my arrow view to only west direction no matter where the user is facing. Below is the code that I have tried but didn't get the desired result.
// inside onCreate()
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
gsensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
msensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
packageManager = getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_SENSOR_COMPASS)){
sensorManager.registerListener(this, gsensor, SensorManager.SENSOR_DELAY_GAME);
sensorManager.registerListener(this, msensor, SensorManager.SENSOR_DELAY_GAME);
}else {
Toast.makeText(MainActivity.this,"No Compass Sensor !", Toast.LENGTH_SHORT).show();
}
@Override
public void onSensorChanged(SensorEvent event) {
final float alpha = 0.97f;
synchronized (this){
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
mGravity[0] = alpha * mGravity[0] + (1 - alpha)
* event.values[0];
mGravity[1] = alpha * mGravity[1] + (1 - alpha)
* event.values[1];
mGravity[2] = alpha * mGravity[2] + (1 - alpha)
* event.values[2];
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD){
mGeomagnetic[0] = alpha * mGeomagnetic[0] + (1 - alpha)
* event.values[0];
mGeomagnetic[1] = alpha * mGeomagnetic[1] + (1 - alpha)
* event.values[1];
mGeomagnetic[2] = alpha * mGeomagnetic[2] + (1 - alpha)
* event.values[2];
}
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
if (success){
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
azimuth = (float) Math.toDegrees(orientation[0]);
Log.i("DegreeA",""+azimuth);
azimuth = (azimuth + 360) % 270;
Log.i("DegreeA",""+azimuth);
adjustThearrow();
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private void adjustThearrow(){
Matrix matrix = new Matrix();
imageview.setScaleType(ImageView.ScaleType.MATRIX);
matrix.postRotate((float) -azimuth, imageview.getDrawable().getBounds().width()/2,
imageview.getDrawable().getBounds().height()/2);
imageview.setImageMatrix(matrix);
}
In the below line of code, if I set 360 instead of 270, it gives me an arrow pointing to only north direction and it rotates smoothly.
azimuth = (azimuth + 360) % 360;
But if I want my code to face the arrow only to west direction, I have set the code like this:
azimuth = (azimuth + 360) % 270;
but this time the rotation is not smoother.
Kindly help me on how to proceed. It would be better if any alternative solution will be provided.