I have implemented a step counting class that seems to work ok, however I am instantiating it from the main activity and everytime the main activity is loaded another instance of the class is created resulting in duplicate steps being added.
I thought about converting to a singleton to prevent this but then I thought it would be better for it to run as a service so that steps are still counted while the application is not running (I think that is how it works?).
How is best for me to convert the class to a service that I can decalred in the manifest file? I need access to the application context so I'm unsure of how this could be passed via the startup from the manifest file.
public class StepCountingService implements SensorEventListener
{
private SensorManager sensorManager;
public StepCountingService(Context context)
{
//initialise class
}
@Override
public void onSensorChanged(SensorEvent event)
{
//step update logic
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
}
A service is one option, you'd have to make it a foreground service to keep Android from killing your app when the user wasn't using it. I answered a similar question here on how to do that:
But in your case, you might also want to make it a bound service so that your activity can connect to it and get step information out of it.
https://developer.android.com/guide/components/bound-services
Or, you could have your service update a database (or a shared preference file) and then the activity could simply query the database and you would avoid needing to bind to the service.
With regards to accessing the application context, services are context wrappers, so they have access to the application context without needing to pass anything in.