Android – How to create android compass application

In this tutorial we are going to learn how to create android compass application. It is going to be a short tutorial but during tutorial we will make use of android Sensor. If you haven’t worked with android sensor that might be you first opportunity to familiarized yourself with it.

According to Wikipedia – “A compass is an instrument used for navigation and orientation that shows direction relative to the geographic “cardinal directions”, or “points”. Usually, a diagram called a compass rose, shows the directions north, south, east, and west as abbreviated initials marked on the compass”

For the application interface, we are going to use a TextView and ImageView widgets. The TextView will hold the text position our compass is pointing to while the ImageView will hold an image of a compass photo.

If you would like to read about android environment sensor with android light sensor as an example I will suggest you read my post on Android Light Sensor.

Before we dive into more details, it is important for us to understand what we are planning to achieve. Below is the screen-shot of the application we will be creating.

android compass example

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidCompassActivity

Package: com.inducesmile.androidcompassactivity

Select Blank Activity

Name your activity : CompassActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

activity_compass.xml

Lets proceed to the layout file which will hold the UI components users will interface with in the application.

Open the activity_compass.xml file in your development environment, copy and paste the code below inside this file.

android:id="@+id/angle"
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="inducesmile.com.completeandroid.CompassActivity">
    <TextView
        android:id="@+id/angle"
        android:text="@string/compass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textColor="@color/primary_text"
        android:textStyle="bold"
        android:textSize="24dp"
        android:layout_marginTop="32dp"/>
    <ImageView
        android:id="@+id/imageViewCompass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/compass" />
</RelativeLayout>

CompassActivity.java

In the corresponding activity class – CompassActivity.java, we will get the instances of the View widgets.

In other to access compass, we will obtain an instance of the SensorManager through android System Services.

The default sensor for the compass is set as Sensor.TYPE_LIGHT.

The SensorEventListener is implemented and in onSensorChanged(SensorEvent event) method we will implement the movement of the compass image.

Finally, we will register the sensorManager instance.

Now copy and paste this code inside the CompassActivity.java file.

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
public class CompassActivity extends AppCompatActivity implements SensorEventListener {
    private SensorManager sensorManager;
    private Sensor compass;
    private ImageView image;
    private TextView compassAngle;
    private float currentDegree = 0f;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compass);
        image = (ImageView)findViewById(R.id.imageViewCompass);
        compassAngle = (TextView)findViewById(R.id.angle);
        sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        compass = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        if(compass != null){
            sensorManager.registerListener(this, compass, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_compass, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this, compass, SensorManager.SENSOR_DELAY_NORMAL);
    }
    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }
    @Override
    public void onSensorChanged(SensorEvent event) {
        float degree = Math.round(event.values[0]);
        compassAngle.setText("Heading: " + Float.toString(degree) + " degrees");
        // create a rotation animation (reverse turn degree degrees)
        RotateAnimation ra = new RotateAnimation(currentDegree, -degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        // how long the animation will take place
        ra.setDuration(210);
        // set the animation after the end of the reservation status
        ra.setFillAfter(true);
        // Start the animation
        image.startAnimation(ra);
        currentDegree = -degree;
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
}

This brings us to the end of this tutorial. I hope you have learned something new.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email address so that you will be among the first to receive my new post once it is published.

Please if you love this tutorial, kindly download my android app – Complete Mathematics – in Google Play Store and let me know what you think about it.

OTHER INTERESTING POSTS:

Add a Comment