To detect metal, you must check the intensity of the magnetic field, i.e. magnitude of the magnetic field vector.
float mag = Math.sqrt(x^2 + y^2 + z^2);
Then you need to compare this value with the expected value of the magnetic field at your location on Earth. Fortunately, Android provides features for this. Take a look at GeomagneticField , the link is here https://developer.android.com/reference/android/hardware/GeomagneticField.html
Then, if the value that you read from the sensors is quite far from the expected value, there is “something” (you guessed it, metal), which interferes with the Earth’s magnetic field near your sensor. For example, a test that you can implement is as follows:
if (mag > 1.4*expectedMag || mag < 0.6*expectedMag) { //there is a high probability that some metal is close to the sensor } else { //everything is normal }
You should experiment with a bit with values of 1.4 and 0.6 so that it matches your application. Please note that this will never work in 100% of cases, because the magnetic sensors on the smartphone are quite cheap and nasty.
source share