How to Build a Compass App For Android - Hive Programmers

avatar

Greetings to my favorite science community online, StemSocial.

It's @skyehi and I'm glad to be back to continue my series on Android App Development Tutorials For Beginners.

We've made quite a lot of progress and developed a lot of Apps. This series has already run for a month and I'm grateful for the love and support from thr StemSocial community.

We've developed a lot of different Basic Apps for Android including AI Apps, Periodic Table, Instant Messenger and even a recycle bin App yesterday.

Although I already have a tall list of future projects I'll be sharing with everyone on StemSocial, I was still thinking about the way forward with my series.

That moment I spent thinking about "the Way Forward" inspired me to decide to make a tutorial about building an Android Compass App.

Yep, as funny as it may sound, that's exactly how I got the inspiration to create this particular blog today. Compasses are used to determine your location or path.

Polish_20231213_134822146.jpgOriginal Image Source by Antonio Batinić from Pexels

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

The Android Compass App is a really cool and pretty much straightforward application that only leverages the Android device's magnetometer sensor to determine the phone's orientation. This is how we'll be able to build a compass App, by using the Android phone's own Sensor systems.

Before I begin, if you've been improving your Android App Development skills with my series, you already know that we would require requesting some permissions in Android manifest file. But not to get ahead of ourselves, let's take this tutorial step by step guys.

Hope you're ready to write some codes - let's get started

Prerequisites

Before I start any of my tutorials, I always talk about the prerequisites stage for the sake of newcomers that are just getting started with Android Programming.

You would need to ensure that you have the following setups or softwares installed;

  • Android Studio IDE, which is the platform on which we'll be building our Android Compass App and all other Android Apps.

  • Java Development Kit, JDK which is very much needed for your computer to be able to successfully execute Java code. Since it's basic tutorials for beginners, I decided to write the code in Java instead of Kotlin.

As I have promised in previous blogs, we'll soon start writing codes in Kotlin after making great progress with this series

  • An Android device or emulator with a magnetometer sensor. I would recommend that you run the finished App on a physical Android device after confirming that it has magnetometer sensor which I believe most modern smart phones would have.

We'll be using the sensor to make our App work so it's really important guys

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Creating a New Android Project

At this point, I'll assume my readers have all the necessary softwares ready, so let's start by opening Android Studio and creating a New Android Project.

You can choose the App name and package name of your App. Also ensure that Java is the selected programming language and not Kotlin.

Now as usual, please select "Empty Activity" as the Activity template. Click on finish, sit back and wait for Android Studio to create a new project for you.

Requesting Sensor and Internet Permission

As I mentioned earlier, one of the most important steps in this particular project would be to request some very necessary permissions.

Since our Compass App would need to use both the internet service and the Compass sensor of the Android phone, we would need to request permission to access these things.

If you skip this step, the App may not work at all guys
Worse case scenario is that it could crash.

Of course our permission code will be written inside the AndroidManifest.xml file.

Here's how your code should look like.

<uses-feature android:name="android.hardware.sensor.compass" android:required="true" />
<uses-permission android:name="android.permission.INTERNET" />

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Designing The Layout

Alright guys, it's time to work on the frontend end of our Compass App. We wouldn't be playing dress up on this one though because or we need is a simple textview that would display the compass direction.

The simple textview design inside Relative Layout will be created in the activity_main.xml file.

Here's how the code should look like

<?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">

    <TextView
        android:id="@+id/compassTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="N"
        android:textSize="24sp" />

</RelativeLayout>

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Writing the Compass Logic Code

Alright guys, so far we are through with the easy part of our work. It's time to work on the backend code or logic of our App.

In this code, we'll be able to access the sensor of the Android device, retrieve the sensors readings and then finally display it inside the textview.

Our logic code will be written inside the MainActivity.java file. It's going to be a marathon code guys so brace yourselves.

Here's how your code should look like

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.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements SensorEventListener {

    private SensorManager sensorManager;
    private Sensor magnetometer;
    private TextView compassTextView;

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

        compassTextView = findViewById(R.id.compassTextView);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager != null) {
            magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (magnetometer != null) {
            sensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

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

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor == magnetometer) {
            float azimuth = event.values[0]; // Get the azimuth (angle in degrees)
            updateCompass(azimuth);
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // Do nothing for now
    }

    private void updateCompass(float azimuth) {
        compassTextView.setText(String.format("%.2f°", azimuth));
    }
}

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

App Preview and Running

We're pretty much done with our App guys. It was a pretty easy App to build compared to some of our previous Apps.

It's now time to run the App. I would recommend using your physical Android device to test this one. If you want to still use and emulator, just like I mentioned earlier guys, please ensure that the computer on which you're running the Android emulator has magnetometer sensor to enable the App to work.

When the App successfully launches, you should see a simple user interface with a TextView displaying the compass direction.

The needle of the compass will dynamically update as you rotate your phone, providing a real-time indication of its orientation. Now this is the part where I tell all those that used a PC emulator to run the App, I told you so. Good luck moving your monitor around 😂.

Anyways guys, congratulations on creating your very first Android Compass App. You will never be lost at sea as long as your battery doesn't die and you also know how to read the compass.

Thanks for taking the time to read today's blog. I hope you enjoyed it guys. Let me know if you're having trouble writing the code or running the App. Have fun out there guys.

Have a lovely day and catch you next time on StemSocial. Goodbye 👨‍💻


You Can Follow Me @skyehi For More Like This And Others



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary, which gives you stronger support. 
 

0
0
0.000