How to Make a Simple Compass App for Android OS? Easy Step by Step Guide with Sample Code
Tags: beginners, programming, android, java
Published: 2023-04-10 12:16:11

Have you ever been lost in a new city and wished you had a compass to help you find your way? With the power of technology in our hands, we can now create our compass app! In this blog post, we'll show you how to create a simple compass app for [Android ](https://www.android.com/) OS using just a few easy steps.

First, let's dive into how a [compass ](https://en.wikipedia.org/wiki/Compass)app actually works. The app uses the phone's built-in [magnetometer](https://en.wikipedia.org/wiki/Magnetometer) and [accelerometer ](https://en.wikipedia.org/wiki/Accelerometer)sensors to detect the magnetic field and orientation of the phone. By combining these two readings, the app can determine the direction the phone is facing and display it on the screen. It's like having a digital compass right in your pocket!

Now, let's get started with the tutorial. I'll guide you through the steps to create your own compass app with a sample code you can follow. Don't worry if you're not a programming expert – I'll explain everything in simple terms so anyone can understand.

By the end of this tutorial, you'll have your very own compass app to use whenever you need to find your way. Plus, if you're a developer, you can use this as a starting point to create even more advanced apps that utilize the phone's sensors.

**Wait, Wait, wait! If you are a startup, entrepreneur, or enterprise interested in similar app development, don't wait and reach out to the [best Android app development services](https://quokkalabs.com/mobile-app-development) for sleek apps with unique features!!**

So, let's get started on this exciting journey to create your compass app!

Let's move onto the steps to create a simple compass app for Android OS:

## Step 1: Create a New Project

To create a new project, open [Android Studio](https://developer.android.com/studio) and click on "Start a new Android Studio project" or go to File > New > New Project. Enter the name of the project and choose the minimum SDK level. Then click on "Next".

## Step 2: Add Permissions to the Manifest File

To access the phone's sensors, we need to add permissions to the manifest file. Open the manifest file located in app > manifests > AndroidManifest.xml and add the following code snippet inside the <manifest> tag:

```
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.sensor.accelerometer" />
<uses-feature android:name="android.hardware.sensor.compass" />

```

## Step 3: Design the User Interface

Now it's time to design the user interface of our compass app. Open the activity_main.xml file located in app > res > layout and add the following code snippet:

```
<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">

    <ImageView
        android:id="@+id/compass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/compass" />

</RelativeLayout>

```

In this code snippet, we have added an ImageView to display the compass image. The image is centered in the parent RelativeLayout.

## Step 4: Add Code to MainActivity.java File

Now let's add the code to MainActivity.java file. Open the MainActivity.java file located in app > java > com.example.yourappname and add the following code snippet:

```
package com.example.yourappname;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity implements SensorEventListener {

    private ImageView compassImage;
    private SensorManager sensorManager;
    private Sensor magnetometer;
    private Sensor accelerometer;
    private float[] lastAccelerometer = new float[3];
    private float[] lastMagnetometer = new float[3];
    private boolean lastAccelerometerSet = false;
    private boolean lastMagnetometerSet = false;
    private float[] rotationMatrix = new float[9];
    private float[] orientation = new float[3];

    @Override
    protected void onCreate(Bundle

```

```
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    compassImage = findViewById(R.id.compass);
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}

@Override
protected void onResume() {
    super.onResume();
    sensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_GAME);
    sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
}

@Override
protected void onPause() {
    super.onPause();
    sensorManager.unregisterListener(this, magnetometer);
    sensorManager.unregisterListener(this, accelerometer);
}

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor == magnetometer) {
        System.arraycopy(event.values, 0, lastMagnetometer, 0, event.values.length);
        lastMagnetometerSet = true;
    } else if (event.sensor == accelerometer) {
        System.arraycopy(event.values, 0, lastAccelerometer, 0, event.values.length);
        lastAccelerometerSet = true;
    }

    if (lastAccelerometerSet && lastMagnetometerSet) {
        SensorManager.getRotationMatrix(rotationMatrix, null, lastAccelerometer, lastMagnetometer);
        SensorManager.getOrientation(rotationMatrix, orientation);

        float azimuthInRadians = orientation[0];
        float azimuthInDegrees = (float) (Math.toDegrees(azimuthInRadians) + 360) % 360;

        Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.compass);
        Matrix matrix = new Matrix();
        matrix.postRotate(-azimuthInDegrees);
        Bitmap rotatedBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth(), originalBitmap.getHeight(), matrix, true);

        compassImage.setImageBitmap(rotatedBitmap);
    }
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

 }
}

```

In this code snippet, we have defined the variables we will use to access the sensors, and we have also defined the methods that will be called when the sensor values change. 

In the onCreate() method, i have initialized the compassImage ImageView and the sensorManager and sensor objects. 

In the onResume() and onPause() methods, i have registered and unregistered the sensor listeners. 

In the onSensorChanged() method, i have retrieved the magnetometer and accelerometer readings and calculated the rotation matrix and orientation. I have then calculated the azimuth angle and rotated the compass image using a matrix. Finally, i have set the rotated bitmap to the compassImage ImageView.

In the onAccuracyChanged() method, i have not added any code as we don't need to handle any changes in sensor accuracy.

## Step 5: Run the App

Now it's time to run the app. Connect your Android device to your computer, select your device from the dropdown list in Android Studio, and click on the "Run" button. The app will be installed on your device and you can use it to find the direction you are facing.


## Conclusion

In this blog post, we have learned how to make a simple compass app for Android OS using easy step-by-step guide with sample code. We have covered the basic steps of creating a new project, adding permissions to the manifest file, designing the user interface, and adding the code to MainActivity.java file. By following these steps, you can create your own compass app and customize it according to your needs.

Well, this is just a compass app! There are unlimited possibilities for Android app development! If you are a startup or enterprise or company, or an entrepreneur who wants to develop similar apps or wants any help, reach a good [mobile app development](https://quokkalabs.com/android-app-development) company!

Happy Coding!