在后台服务中使用TYPE_STEP_COUNTER? [英] Using TYPE_STEP_COUNTER in a background service?

查看:340
本文介绍了在后台服务中使用TYPE_STEP_COUNTER?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑实现Android 4.4中引入的步进传感器API( http://youtu.be/yv9jskPvLUc).但是,对于在后台进行监视的推荐方式是什么,我找不到明确的解释.似乎大多数示例仅显示在应用程序运行时如何通过活动执行此操作.我不需要特别频繁的更新-我基本上想记录用户每小时向后端服务走的步数. 我应该只是启动一个在SensorManager上调用registerListener的后台服务,还是有一种更优雅的方法?

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?

推荐答案

据我所知,SensorManager周围没有办法,但是如果您很少需要数据,则可以手动触发传感器并获取它的值以TriggerEventListener表示,比SensorEventListener干净一点.

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通常是启动小时计时器的最佳选择,即使您的应用未运行,它也可以工作. AlarmManagerIntent发送到扩展BroadcastReceiver的类,该类将启动您的Service.可以根据您的实现在应用程序中的任何位置设置AlarmManager.

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);
  }
} 

这篇关于在后台服务中使用TYPE_STEP_COUNTER?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆