问题就像标题中一样。如何使onSensorChanged和onAccuracyChanged在后台工作?感谢您的帮助。
public class MainActivity extends Activity implements SensorEventListener {
SensorManager sensorManager;
boolean running;
TextView tv_steps;
int mSteps;
TextView baza;
StepDatabase db;
@Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_steps = (TextView) findViewById(R.id.tv_steps);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
baza = (TextView) findViewById(R.id.baza);
db = new StepDatabase(this);
final Button button = findViewById(R.id.zeruj);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// mSteps=0;
printDatabase();
}
});
}
public void printDatabase ()
{
String dbString = db.readData();
baza.setText(dbString);
}
@Override
protected void onResume () {
super.onResume();
running = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
if (countSensor != null) {
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
Toast.makeText(this, "Nie znaleziono sensora", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPause ()
{
super.onPause();
running = false;
}
@Override
public void onSensorChanged(SensorEvent event) {
if (running) {
db.createStepsEntry();
mSteps += event.values.length;
tv_steps.setText((String.valueOf(mSteps)));
//tv_steps.setText(String.valueOf(event.values[0]));
printDatabase();
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
,我还有一个附加类StepDatabase,它将数据保存到数据库中。如何使它在后台运行?我试图将其放在线程中,但没有用。请给我一些建议。