我正在尝试为Android应用程序编写一项服务,该服务以固定的采样率连续监控加速度计传感器的值。下面是我用来保持服务运行的代码片段。
public class MyService extends Service {
...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Intent mainIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(mainIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setAutoCancel(true)
.setOngoing(true)
.setContentIntent(pendingIntent)
.setContentText(TAG)
.build();
context.startForeground(1, notification);
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
wakeLock.acquire();
//Register Accelerometer Sensor Listener Here
return START_STICKY;
}
当设备在几分钟后使用电池运行时,它会进入睡眠状态。该服务将偶尔重新启动,但没有一致性。我现在正在考虑的想法是:
- 作为系统服务运行
- 探索 Google Fit API
但我希望没有必要。有谁知道实现此传感器记录功能以始终运行的方法?
--
我还尝试将传感器侦听器更改为普通重复线程,以防只有传感器进入睡眠状态,但效果是相同的。我相信它只与安卓的电源管理有关
我知道这会影响能源效率,但此应用程序必须保证日志记录不间断且采样率高。
已编辑:更改标题以澄清
更新:将其转换为持久系统应用程序无济于事
我能够解决这个问题。实际上这是代码中的错误。我发布的代码片段中的 WakeLock 是一个局部变量,当函数返回时会被垃圾回收,所以实际上没有锁。我通过更改它来修复它:
public class MyService extends Service {
private PowerManager powerManager;
private static PowerManager.WakeLock wakeLock;
...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
wakeLock.acquire();
...
}