Created
February 1, 2017 19:57
-
-
Save jackgu1988/8a0821280df108ea7c9a59091e38ca34 to your computer and use it in GitHub Desktop.
Android code to detect when the user is lowering the device v2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.util.Log; | |
public class MainActivity extends AppCompatActivity implements SensorEventListener { | |
private float[] gravity = new float[0]; | |
private float[] magnetic = new float[0]; | |
private int inclination; | |
private final int SENSITIVITY = -1; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE); | |
sm.registerListener(this, sm.getDefaultSensor | |
(Sensor.TYPE_GRAVITY), SensorManager.SENSOR_DELAY_NORMAL); | |
sm.registerListener(this, sm.getDefaultSensor | |
(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL); | |
} | |
@Override | |
public void onSensorChanged(SensorEvent event) { | |
float[] rotArray = new float[9]; | |
float[] inclArray = new float[9]; | |
switch (event.sensor.getType()) { | |
case Sensor.TYPE_GRAVITY: | |
gravity = new float[]{event.values[0], event.values[1], event.values[2]}; | |
break; | |
case Sensor.TYPE_MAGNETIC_FIELD: | |
magnetic = new float[]{event.values[0], event.values[1], event.values[2]}; | |
break; | |
} | |
if (gravity.length == 3 && magnetic.length == 3) { | |
SensorManager.getRotationMatrix(rotArray, inclArray, gravity, magnetic); | |
float prevInclination = inclination; | |
inclination = (int) Math.round(Math.toDegrees(Math.acos(rotArray[8]))); | |
if (inclination - prevInclination < SENSITIVITY) { | |
Log.d("Movement", "Going Down!"); | |
} | |
} | |
} | |
@Override | |
public void onAccuracyChanged(Sensor sensor, int i) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment