androidpedometer

Grand total of steps taken by user - Android Application Stepometer


I have an application which has an in game stepometer so calculates the user's steps in the background as they play the game. It works fine, my issue is the following

For example, in one session he had 200 steps and in the next 300. I would like to save this total of 500 steps so that I can then display achievements to the user such as. Congrats you walked 1000 steps since beginning the game.

This is my stepometer code which I found online and currently using in my application.

import android.app.Activity;
import android.content.Context;
import android.hardware.*;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class StepCounterActivity extends Activity implements SensorEventListener {

    private SensorManager sensorManager;
    private TextView count;
    boolean activityRunning;
    int totalSteps;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_step_counter);
        count = (TextView) findViewById(R.id.count);

        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        activityRunning = true;
        Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        if (countSensor != null) {
            sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
        } else {
            Toast.makeText(this, "Count sensor not available!", Toast.LENGTH_LONG).show();
        }    
    }

    @Override
    protected void onPause() {
        super.onPause();
        activityRunning = false;
        // if you unregister the last listener, the hardware will stop detecting step events
//        sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (activityRunning) {
            count.setText(String.valueOf(event.values[0]));
            //maybe add to a variable the number of steps somehow?
        }    
    }

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

Solution

  • Since you are not using Service below will work fine for you. Maintain A global variable totalSteps to count the total no of steps taken by user over all sessions.

    private int totalSteps = 0;
    @Override
    public void onSensorChanged(SensorEvent event) {
    
        totalSteps += (int)event.values[0];
    
        if (activityRunning) {
            count.setText(String.valueOf(totalSteps));
        }
    
    }
    

    Keep in mind totalSteps would be lost once app is kill or closed. To overcome this situation you should try using SharedPreferences.