Manufacturers continuously add more features and sensors to smartphones. Thus, your smartphone has now a magnetic field sensor which can help you to use your smartphone as a Magnetometer Metal Detector. For example, we have published an application of this kind on the Google Play Store : https://play.google.com/store/apps/details?id=com.ssaurel.magnetometer .

magnetometer_icon

Magnetometer Metal Detector lets you to measure magnetic field around you by using the magnetic sensor that is built into your smartphone and tablet. It helps you to detect metal objects (steel, iron) around you. When a metal object is near to you, the magnetic field level will increase. Note that gold, silver an copper coins cannot be detected since they are classified as non-ferrous metal and so, they have no magnetic field.

In this tutorial, you are going to learn how to create a Magnetometer Metal Detector application like this we have published on the Google Play Store. First, you need to create a simple layout with a TextView widget centered on the screen :


<?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:id="@+id/activity_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  android:background="#000000"
  tools:context="com.ssaurel.magnetometerapp.MainActivity">

  <TextView
    android:id="@+id/value"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="45.00"
    android:textColor="#FFFFFF"
    android:textStyle="bold"
    android:textSize="23sp"
    android:layout_centerInParent="true"/>
</RelativeLayout>

Now, it’s time to go on your main Activity to write Java code. First, you need to implement the SensorEventListener interface to register to know Magnetic Field sensor values. You will get values on three axes : X, Y and Z. To determine the magnetic field value, you will need to apply a mathematic formula : Magnetic Value = sqrt(Value_X * Value_X + Value_Y * Value_Y + Value_Z * Value_Z) .

Thus, the magnetic value is equal to the square root of the sum of squared values on each axes. Code for the Activity will have the following form :


package com.ssaurel.magnetometerapp;

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

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements SensorEventListener{

  private TextView value;
  private SensorManager sensorManager;
  public static DecimalFormat DECIMAL_FORMATTER;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    value = (TextView) findViewById(R.id.value);
    // define decimal formatter
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
    symbols.setDecimalSeparator('.');
    DECIMAL_FORMATTER = new DecimalFormat("#.000", symbols);

    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
  }

  @Override
  protected void onResume() {
    super.onResume();
    sensorManager.registerListener(this,
      sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
      SensorManager.SENSOR_DELAY_NORMAL);
  }

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

  @Override
  public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
      // get values for each axes X,Y,Z
      float magX = event.values[0];
      float magY = event.values[1];
      float magZ = event.values[2];

      double magnitude = Math.sqrt((magX * magX) + (magY * magY) + (magZ * magZ));

      // set value on the screen
      value.setText(DECIMAL_FORMATTER.format(magnitude) + " \u00B5Tesla");
  }

}

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

By reading this code, you can note that the Sensor Service is retrieved on the onCreate method. Then, we register our Activity to listen changes of values for the Magnetic Field sensor by calling the registerListener method of the SensorManager instance retrieved previously. We choose also the delay to get update of magnetic field values. When the application is paused, we unregister the listener.

Now, you can launch your application to try your Magnetometer Metal Detector :

main2_en

 

That’s all for this tutorial. You can know make your own Magnetometer Metal Detector and improve it by adding a graph to show recent magnetic field activity or a Gauge View to display the magnetic field value like on the version published on the Google Play Store. You can also go on Youtube and enjoy this tutorial in video :