Colour changing using accelerometer sensor(x,y,z)
public class MainActivity extends AppCompatActivity implements SensorEventListener { private TextView xText, yText, zText; private SensorManager sensorManager; private Sensor mySensor; private boolean color = false; private View view; private long lastUpdate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); mySensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); sensorManager.registerListener(this,mySensor,SensorManager.SENSOR_DELAY_NORMAL); xText = (TextView) findViewById(R.id.textViewX); yText = (TextView) findViewById(R.id.textViewY); zText = (TextView) findViewById(R.id.textViewZ); view = findViewById(R.id.change); view.setBackgroundColor(Color.GREEN); lastUpdate = System.currentTimeMillis(); } @Override public void onSensorChanged(SensorEvent sensorEvent) { xText.setText("X: "+ sensorEvent.values[0]); yText.setText("Y: "+ sensorEvent.values[1]); zText.setText("Z: "+ sensorEvent.values[2]); if(sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { getAccelerometer(sensorEvent); } } private void getAccelerometer(SensorEvent sensorEvent) { float[] values = sensorEvent.values; float x = values[0]; float y = values[1]; float z = values[2]; float accelerationSquareRoot= (x * x + y * y + z * z) / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH); long actualTime = sensorEvent.timestamp; if(accelerationSquareRoot >= 2) { if(actualTime - lastUpdate < 200) { return; } lastUpdate = actualTime; Toast.makeText(this, "Device was shuffled", Toast.LENGTH_SHORT).show(); if(color) { view.setBackgroundColor(Color.GREEN); }else { view.setBackgroundColor(Color.RED); } color = !color; } } @Override public void onAccuracyChanged(Sensor sensor, int i) { } @Override protected void onPause() { super.onPause(); sensorManager.unregisterListener(this); } }
Comments
Post a Comment