Click here to Skip to main content
15,113,057 members
Articles / Mobile Apps / Android
Posted 11 Jun 2015

Tagged as


25 bookmarked

Android Compass

Rate me:
Please Sign up or sign in to vote.
4.94/5 (21 votes)
11 Jun 2015CPOL4 min read
This article demonstrates creating a Compass app in Android


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 for my compass app:
Images For > Wind Clipart


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=""
    android:orientation="vertical" >
    <TextView android:id="@+id/txtDegrees"
        android:layout_height="wrap_content" />
    <ImageView android:id="@+id/imgCompass"
	android:src="@drawable/compass" />

The following code is used to initialize the image for our compass.


The following code is used to initialize the textview to display the degree of rotation.


The <font face="Courier New">getSystemService()</font> method can be used to initialize the sensor manager of our device as follows:


Following is the full code of the <font face="Courier New">onCreate()</font> method which is called once when the app is started:

public void onCreate(Bundle savedInstanceState)

Following is the code of the onResume() method which is automatically called whenever the activity comes to the foreground:

protected void onResume()

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.

protected void onPause()

The main action occurs in the following onSensorChanged() method. The onSensorChanged() method gets executed whenever sensor values have changed.

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);

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:

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.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Azim Zahir
Instructor / Trainer NIIT, India
India India
I am a trainer by profession. Currently I am working with iFuture Technologies(India) as a Senior Faculty. I enjoy programming as a hobby. During my career I have seen the growth and decline of many technologies, many of them being my favorites like Flash, WPF, Windows Mobile Development. Few of my current favorites are Android, Xamarin and Python, though I also like traditional and evergreen languages like PHP, C#, Visual Basic and Java.

Apart from computers, my favorite pastime is bicycling.

Comments and Discussions

SuggestionSensor.TYPE_ORIENTATION is deprecated Pin
DrABELL26-Nov-17 9:25
professionalDrABELL26-Nov-17 9:25 
I would recommend re-writing this article. Best regards,
1. Life is 2short 2remove USB safely
2. "Any fool can criticize, condemn and complain - and most fools do." (B. Franklin)

PraiseGood Article Pin
Bhuvanesh Mohankumar13-Aug-16 21:32
MemberBhuvanesh Mohankumar13-Aug-16 21:32 
GeneralRe: Good Article Pin
Azim Zahir18-Jan-17 5:42
MemberAzim Zahir18-Jan-17 5:42 
GeneralMy vote of 5 Pin
Muhammad Shahid Farooq26-Jun-16 23:27
professionalMuhammad Shahid Farooq26-Jun-16 23:27 
GeneralRe: My vote of 5 Pin
Azim Zahir10-Jul-16 8:21
MemberAzim Zahir10-Jul-16 8:21 
GeneralVery Useful App......... Pin
Member 1163597226-Jun-15 2:22
MemberMember 1163597226-Jun-15 2:22 
GeneralRe: Very Useful App......... Pin
Azim Zahir30-Jun-15 23:06
MemberAzim Zahir30-Jun-15 23:06 
GeneralMy vote of 5 Pin
_Vitor Garcia_12-Jun-15 6:46
Member_Vitor Garcia_12-Jun-15 6:46 
GeneralRe: My vote of 5 Pin
Azim Zahir12-Jun-15 20:25
MemberAzim Zahir12-Jun-15 20:25 
QuestionNice one Pin
hari1911311-Jun-15 22:38
Memberhari1911311-Jun-15 22:38 
AnswerRe: Nice one Pin
Azim Zahir12-Jun-15 0:09
MemberAzim Zahir12-Jun-15 0:09 
GeneralMy vote of 5 Pin
newton.saber11-Jun-15 10:15
Membernewton.saber11-Jun-15 10:15 
GeneralRe: My vote of 5 Pin
Azim Zahir11-Jun-15 21:03
MemberAzim Zahir11-Jun-15 21:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.