Learn to create a Magnetometer Metal Detector on Android

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 :

Image for post
Image for post

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"

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;

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 :

Image for post
Image for post

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 :

Written by

Entrepreneur / Developer / Blogger / Author. In Bitcoin We Trust: https://www.inbitcoinwetrust.net

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store