我尝试了很多方法在后台获取传感器数据,并将值存储到共享首选项或sqlite中,但都不起作用。我认为这是因为android oreo的背景限制。
我试过了
带广播接收器的报警管理器
带服务的报警管理器
现在我用的是workmanager。也不太管用。我做错什么了?现在不可能在后台获取传感器数据吗?还有别的办法吗?
主活动.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
localDatabaseHelper = new LocalDatabaseHelper(getApplicationContext());
sharedPreferences = getSharedPreferences("TEST STORAGE", MODE_PRIVATE);
sensorManager = (SensorManager) getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
stepSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
WorkManager.getInstance(getApplicationContext()).cancelAllWorkByTag("Update-Shared-Preference");
WorkRequest updateSharedPreference = new OneTimeWorkRequest.Builder(UpdateStepWork.class)
.addTag("Update-Shared-Preference")
.build();
WorkManager.getInstance(getApplicationContext()).enqueue(updateSharedPreference);
}
工作
public class UpdateStepWork extends Worker implements SensorEventListener {
private SharedPreferences sharedPreferences;
private SensorManager sensorManager;
private Sensor stepSensor;
private LocalDatabaseHelper localDatabase;
public UpdateStepWork(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
Log.i("WORK", "STARTED");
sharedPreferences = getApplicationContext().getSharedPreferences("TEST STORAGE", Context.MODE_PRIVATE);
sensorManager = (SensorManager) getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
stepSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
localDatabase = new LocalDatabaseHelper(getApplicationContext());
WorkManager.getInstance(getApplicationContext()).cancelAllWorkByTag("Update-Shared-Preference");
WorkRequest updateSharedPreference = new OneTimeWorkRequest.Builder(UpdateStepWork.class)
.setInitialDelay(5, TimeUnit.SECONDS)
.addTag("Update-Shared-Preference")
.build();
WorkManager.getInstance(getApplicationContext()).enqueue(updateSharedPreference);
sensorManager.unregisterListener(this, stepSensor);
if(sensorManager.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_NORMAL)){
return Worker.Result.success();
}else
return Worker.Result.failure();
}
@Override
public void onSensorChanged(SensorEvent event) {
int steps = (int) event.values[0];
Log.i("Steps from sensor", steps + "");
if(sharedPreferences.edit().putInt("steps", steps).commit()){
Log.i("Shared Preference", "SUCCESS STORED: " + steps);
if(localDatabase.updateDailyData(steps)){
Log.i("LOCAL DATABASE", "SUCCESS AT " + getCurrentTimeStamp());
Cursor data = localDatabase.getData();
while (data.moveToNext()) {
Log.i("DATA", data.getString(0) + " " + data.getInt(1));
}
}
}else{
Log.i("Shared Preference", "FAILED STORED: " + steps);
}
sensorManager.unregisterListener(this, stepSensor);
sensorManager = null;
}
1条答案
按热度按时间7fhtutme1#
在后台收集传感器数据的典型方法是使用前台服务。
共享引用不是存储传感器数据的理想方式。我建议您将传感器数据存储在.csv文件或数据库中。