Simple compass code with Android Studio

By informerfrk

Share on

Now in this blog post I am going to make a very simple application which show the direction like North, South, East, West. Exactly, I am going to build a simple compass application. I will show you the Java and XML code that will be use to build this simple compass application.

Before going to start I want to inform you that Some of the android devices does not have full support for motions sensors. So this application will not work for those types of android devices.

Let’s start building compass application for android

Compass image

Before you start coding in Android Studio you need a compass image which will rotate and show you the direction when your phone rotate. Here is the image I have use for the compass app:

You can also use the image in your compass app or use a different image.

Let’s coding

Now let’s start with coding. I am going to give you the full Java and XML code of this app.

Here is the main Java code (MainActivity.java):

package com.codespeedy.compassbyeyeswift;

import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.hardware.SensorEvent;
import android.widget.ImageView;
import android.widget.TextView;
import android.hardware.SensorEventListener;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements SensorEventListener {

    // device sensor manager
    private SensorManager SensorManage;

    // define the compass picture that will be use
    private ImageView compassimage;

    // record the angle turned of the compass picture
    private float DegreeStart = 0f;

    TextView DegreeTV;

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

        //
        compassimage = (ImageView) findViewById(R.id.compass_image);

        // TextView that will display the degree
        DegreeTV = (TextView) findViewById(R.id.DegreeTV);

        // initialize your android device sensor capabilities
        SensorManage = (SensorManager) getSystemService(SENSOR_SERVICE);
    }

    @Override
    protected void onPause() {
        super.onPause();

        // to stop the listener and save battery
        SensorManage.unregisterListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // code for system's orientation sensor registered listeners
        SensorManage.registerListener(this, SensorManage.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        // get angle around the z-axis rotated
        float degree = Math.round(event.values[0]);

        DegreeTV.setText("Heading: " + Float.toString(degree) + " degrees");

        // rotation animation - reverse turn degree degrees
        RotateAnimation ra = new RotateAnimation(
                DegreeStart,
                -degree,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);

        // set the compass animation after the end of the reservation status
        ra.setFillAfter(true);

        // set how long the animation for the compass image will take place
        ra.setDuration(210);

        // Start animation of compass image
        compassimage.startAnimation(ra);
        DegreeStart = -degree;

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // not in use
    }
}

You need to replace the package name with your own. On Google play store each of the android application should have a unique package name just like domain names.

And here is the code for main layout XML file (activity_main.xml):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:id="@+id/DegreeTV"
        android:layout_marginBottom="40dp"
        android:layout_marginTop="20dp"
        android:text="Heading: 0.0"
        android:textSize="25sp"
        android:textColor="@color/colorAccent"
        android:textStyle="normal|bold" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/compass_image"
        android:layout_below="@+id/DegreeTV"
        android:layout_centerHorizontal="true"
        android:src="@drawable/compass_icon" />

</RelativeLayout>

That’s all you need to create your compass app for android. The image will show the direction and the TextView will display angle in degree with respect to North.

Now you can test your app. You can run your app or you can also build the apk or signed apk and then test it on your android device. See the picture below how the app will looks:

 

Leave a Reply

Your email address will not be published. Required fields are marked *