可以在Android设备的后台运行一个服务来收集加速度计数据,即使屏幕关闭也不影响。下面是代码示例:
public class AccelerometerService extends Service implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometer;
private PowerManager.WakeLock wakeLock; // 保持设备唤醒以在屏幕关闭时收集数据
@Override
public void onCreate() {
super.onCreate();
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"AccelerometerServiceWakeLock");
wakeLock.acquire(); // 获取唤醒锁
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// 处理加速度计数据
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
sensorManager.unregisterListener(this);
wakeLock.release(); // 释放唤醒锁
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Intent intent = new Intent(this, AccelerometerService.class); startService(intent);
注意:由于长时间运行服务可能会耗费设备的电量,建议在收集完数据后尽快停止服务。在服务的代码中还可以添加自定义逻辑来实现数据存储、处理等功能。