Introduction
This article explains how we can create our own compass app using the built-in magnetic sensor of our mobile device.
The foremost thing to remember is that a compass app works by using the data provided by the magnetometer sensor on a mobile device. So if our mobile device does not have this sensor, a compass app cannot run on it.
Also magnetometers are very sensitive to magnetic or electrical signals. So be careful that you are holding the device away from any such signals to get accurate direction from the compass app.
I have used the following image from cliparts.co for my compass app:
Background
In this article, I have used a TextView control to display the angle at which the device is oriented. Also, I have used an image of a compass to point to the North-South direction. In order for all this to work, the sensor manager of the device needs to be initialized when the app is initialized.
Also, we need to register the orientation sensor of the device when the app is activated and unregister it when the app is paused, to conserve battery.
Using the code
Following is the main layout file which defines a TextView control and an ImageView control in a relative layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView android:id="@+id/txtDegrees"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView android:id="@+id/imgCompass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/txtDegrees"
android:src="@drawable/compass" />
</RelativeLayout>
The following code is used to initialize the image for our compass.
imgCompass=(ImageView)findViewById(R.id.imgCompass);
The following code is used to initialize the textview to display the degree of rotation.
txtDegrees=(TextView)findViewById(R.id.txtDegrees);
The <font face="Courier New">getSystemService()</font>
method can be used to initialize the sensor manager of our device as follows:
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
Following is the full code of the <font face="Courier New">onCreate()</font>
method which is called once when the app is started:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgCompass=(ImageView)findViewById(R.id.imgCompass);
txtDegrees=(TextView)findViewById(R.id.txtDegrees);
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
}
Following is the code of the onResume() method which is automatically called whenever the activity comes to the foreground:
@Override
protected void onResume()
{
super.onResume();
sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),SensorManager.SENSOR_DELAY_GAME);
}
The above code registers a SensorEventListener for the orientation sensor of our device at the sampling frequency specified by the parameter SensorManager.SENSOR_DELAY_GAME, which represents a rate suitable for games.
The following code unregisters the SensorEventListener when the activity is paused.
@Override
protected void onPause()
{
super.onPause();
sensorManager.unregisterListener(this);
}
The main action occurs in the following onSensorChanged() method. The onSensorChanged() method gets executed whenever sensor values have changed.
@Override
public void onSensorChanged(SensorEvent event)
{
float degree=Math.round(event.values[0]);
txtDegrees.setText("Rotation: "+Float.toString(degree)+" degrees");
RotateAnimation ra=new RotateAnimation(currentDegree,-degree,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
ra.setDuration(120);
ra.setFillAfter(true);
imgCompass.startAnimation(ra);
currentDegree=-degree;
}
In the above code, the SensorEvent is the parameter to the onSensorChanged() method.
The degree of rotation is determined by the code <font face="Courier New">float degree=Math.round(event.values[0]);</font>
and is displayed on the TextView using the <font face="Courier New">setText()</font>
method.
The size and data of the <font face="Courier New">values</font>
array depends on the sensor type.
In case of the orientation sensor, the <font face="Courier New">values</font>
array contains the following values:
- values[0]: Angle between the magnetic north direction and the y-axis around the z-axis (0 to 359), where 0=North, 90=East, 180=South, 270=West.
- values[1]: Rotation around x-axis (-180 to 180), with positive values when the z-axis moves towards the y-axis.
- values[2]: Rotation around x-axis, (-90 to 90), increasing as the device moves clockwise.
After that a RotateAnimation object is used to rotate the compass as the device is rotated. The constructor of the RotateAnimation class takes the following parameters:
- fromDegrees: Rotation offset at the start of the animation.
- toDegrees: Rotation offset at the end of the animation.
- pivotXType: Interpretation of pivotXValue. Can be Animation.ABSOLUTE, Animation.RELATIVE_TO_SELF or Animation.RELATIVE_TO_PARENT.
- pivotXValue: X coordinate of the point about which the object is being rotated.
- pivotYType: Interpretation of pivotYValue. Can be Animation.ABSOLUTE, Animation.RELATIVE_TO_SELF or Animation.RELATIVE_TO_PARENT.
- pivotYValue: Y coordinate of the point about which the object is being rotated.
The <font face="Courier New">setDuration()</font>
method of the Animation class is used to specify the duration in milliseconds for which the animation should last.
The <font face="Courier New">setFillAfter()</font>
method of the Animation class is used to persist the transformation produced by this animation.
The <font face="Courier New">startAnimation()</font>
method of the Animation class is used to start the animation.
Finally, the currentDegree is updated with the value of -degree so that the next animation will start from the new position.
The following function is not used but is required to be specified because our activity class implements the SensorEventListener interface:
@Override
public void onAccuracyChanged(Sensor p1, int p2)
{
}
Following is the output of the execution of the compass app on my Samsung Galaxy Note 3 Neo mobile:
Points of Interest
I hope this article will help readers in understanding how easy it is to create our own compass app.