Using TYPE_STEP_COUNTER in the background?

I am looking at implementing the step API introduced in Android 4.4 ( http://youtu.be/yv9jskPvLUc ). However, I cannot find a clear explanation of which recommended way to control this in the background? Most of the examples seem to show how to do this while being active while the application is running. I especially do not need a high update rate - I basically want to record the number of steps that the user went to the backend service every hour. Should I just deploy a background service that calls registerListener on the SensorManager, or is there a more elegant way?

+5
source share
3 answers

As far as I know, there is no way around the SensorManager , but if you need data very rarely, you can start the sensor manually and get its values ​​using the TriggerEventListener , which is a little cleaner than a SensorEventListener .

AlarmManager is usually the best option to start an hourly timer, and it works even if your application is down. AlarmManager sends an Intent class that extends BroadcastReceiver , and that class starts your Service . AlarmManager can be installed anywhere in the application, 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); } } 
+5
source

@TheTheKanning's answer is the right way to do this manually. In addition, Google Fit continuously logs this data and has an API that you can use to pull it into your application.

+3
source

This is not a complete solution, but the most energy-efficient way might be to wake your device every hour or so, start a service that quickly reads data, and then returns to sleep mode.

Depending on what target level of the device you are using the WakefulBroadcastReceiver as described in this answer seems to be the way to go.

You need

If any of the points is less clear, let’s say so. See http://code.tutsplus.com/tutorials/android-barometer-logger-acquiring-sensor-data--mobile-10558

+2
source

Source: https://habr.com/ru/post/1239256/


All Articles