Issue
I'm looking at implementing the step sensor API introduced in Android 4.4 (http://youtu.be/yv9jskPvLUc). However, I am unable to find a clear explanation on what the recommended way to monitor this in the background is? It seems like most examples only show how to do this with an activity while the app is running. I don't particularly need a high frequency of updates - I basically want to log the amount of steps the user has walked every hour to a backend service. Should I just spin up a background service that calls registerListener on SensorManager, or is there a more elegant way?
Solution
As far as I know, there is no way around the SensorManager
, but if you need the data very infrequently, you could trigger the sensor manually and get its values with a TriggerEventListener
, which is a little cleaner than a SensorEventListener
.
AlarmManager
is typically the best option for starting an hourly timer, and it works even if your app isn't running. AlarmManager
sends an Intent
to a class that extends BroadcastReceiver
, and that class will start your Service
. The AlarmManager
can be set anywhere in your app depending on your implementation.
StepCountService
SensorManager sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Sensor stepCounter = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
sensorManager.requestTriggerSensor(listener, stepCounter);
private TriggerEventListener listener = new TriggerEventListener(){
@Override
public void onTrigger(TriggerEvent event) {
//handle step count here
}
}
MainActivity
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, AlarmReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,AlarmManager.INTERVAL_HOUR,
AlarmManager.INTERVAL_HOUR, alarmIntent);
AlarmReceiver
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, StepCountService.class);
context.startService(service);
}
}
Answered By - TheoKanning
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.