dimanche 7 mars 2021

Start activity when device is moving

I am new to Java and I am making an app that starts an activity when the device is moving. I have found the script for a step counter but I have no clue about how to start the activity based on the condition. Here's the script I am using for the step counter, I know that the part when the steps are increasing is Magnitude > 6 but i don't know what code to put in the if

public class MainActivity extends AppCompatActivity {

private TextView textView;
private double MagnitudePrevious = 0;
private Integer stepCount = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    textView = findViewById(R.id.textView);

    SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    SensorEventListener stepDetector = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {


            if (sensorEvent!= null){
                float x_acceleration = sensorEvent.values[0];
                float y_acceleration = sensorEvent.values[1];
                float z_acceleration = sensorEvent.values[2];

                double Magnitude = Math.sqrt(x_acceleration*x_acceleration + y_acceleration*y_acceleration + z_acceleration*z_acceleration);
                double MagnitudeDelta = Magnitude - MagnitudePrevious;
                MagnitudePrevious = Magnitude;

                if (MagnitudeDelta > 1.5){
                    stepCount++;
                }
                
                textView.setText(stepCount.toString());
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {
        }
    };


    sensorManager.registerListener(stepDetector, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}

protected void onPause() {
    super.onPause();

    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear();
    editor.putInt("stepCount", stepCount);
    editor.apply();
}

protected void onStop() {
    super.onStop();

    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear();
    editor.putInt("stepCount", stepCount);
    editor.apply();
}

protected void onResume() {
    super.onResume();

    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    stepCount = sharedPreferences.getInt("stepCount", 0);
}

}

Aucun commentaire:

Enregistrer un commentaire