加速计传感器导致损失进入服务

时间:2016-04-03 10:23:16

标签: android service accelerometer wear-os

我正在为 Android Wear 开发一个应用程序。它从加速计传感器监听坐标并找到模式。

为此,当用户单击按钮时,服务将启动并开始在List中存储坐标。通常,加速计传感器每秒记录4到5个坐标。

问题是有时onSensorChanged()方法在几秒钟内没有收到数据,导致数据丢失和查找模式的麻烦。

以下是我服务的要点:https://gist.github.com/cpalosrejano/8f0e59e47124275136fc3d5d941faa07

我尝试过的事情:

  • 我使用 android:stopWithTask = false 来阻止服务在活动终止时停止。
  • 我还使用 WakeLock 来防止设备在服务记录坐标时进入睡眠状态。

我做错了什么?还有另一种方法可以从加速计传感器接收回调而不会导致数据丢失吗?

提前致谢。

2 个答案:

答案 0 :(得分:0)

您可以做的是将数据写入设备上的文件并从文件中读取。

// When sensor value has changed
@Override
public void onSensorChanged(SensorEvent event){
    if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){

    //Perform a background task to store the data
    new SensorEventLoggerTask().execute(event);

    // And continue to do whatever you want and grab the data
    // The data will be saved in to a file on the device and read it from themre
    }
}

答案 1 :(得分:0)

有点晚了,但我终于找到了解决方案。

我使用方法startForeground(int, Notification)在前台启动服务,因此服务永远不会停止。使用此修复程序,您永远不会丢失任何SensorEvent。