As I see, in the third method you are trying to find the cos of the angle between two vectors (the gravity vector and the acceleration vector). And the idea is that the angle is approaching 180 degrees, you have movement, if the angle is close to 0 degrees, you have movement down. Cosine is a function that has a positive meaning when the angle is from -90 to 90 degrees. Therefore, when your cosineVal value cosineVal positive, it means that the phone is going down, and even if cosineVal is closer to 1 movement, it is straight down. So it's true the other way around. When the cosine is negative (from 90 degrees to 270), you have movement.
You can probably get vectors from Sensor.TYPE_ACCELEROMETER from https://developer.android.com/reference/android/hardware/SensorEvent.html#values there you have a gravity vector and an acceleration vector.
I made a code snippet below that you can try.
public class MainActivity extends AppCompatActivity implements SensorEventListener { private float[] gravity = new float[3]; private float[] linear_acceleration = new float[3]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SensorManager mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); Sensor mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); } @Override public void onSensorChanged(SensorEvent event) {
thekekc
source share