I am currently developing an app in Android which will record sensor data for a fixed length of time for several cycles. For example, I plan to record the data for 10 seconds, and then stop, let the phone rest for 10 seconds, and start record again, … working in this pattern for 1 hour. My question is, how to let the phone automatically execute this plan? I am currently using code below ( from Android: How to collect sensor values for a fixed period of time?) , but it only works for one cycle, I have to manually start new cycles after I am sure the previous cycle has finished.
public void onResume() {
mSensorManager.registerListener(mListener, mSensorAcceleration, SensorManager.SENSOR_DELAY_GAME);
mSensorManager.registerListener(mListener, mSensorMagnetic, SensorManager.SENSOR_DELAY_GAME);
Handler h = new Handler();
h.postDelayed(new Runnable() {
@Override
public void run() {
// do stuff with sensor values
mSensorManager.unregisterListener(mListener);
}
}, 10000);
…
Any help will be appreciated!!
Step #1: Have your activity implement
Runnable, rather than use an anonymous inner class, moving yourrun()method to be implemented on the activity.Step #2: In your
run()method, schedule yourself (the activity) to run again after a delay usingpostDelayed(). This, plus your existing call topostDelayed(), will effectively set up a periodic call torun().Step #3: Keep track of whether you are in “sensors on” or “sensors off” mode, and, in
run(), either register or unregister the listeners as appropriate.Step #4: In
onPause(), callremoveCallbacks()on yourHandlerto stop the periodic calls torun().You will see an example of this sort of schedule-yourself-to-run-again logic in this sample project. Here is the activity: