I am developing an Android application and I want to call a function every 40ms. To do so, I implemented a Handler and a Runnable. I chose this two objects thanks to the post How to run a method every X seconds. But I am not sure this is the right way to perform what I am doing :
In my application, I am playing a video, I want to "launch" the Handler when starting the video, "put it on hold" when pausing the video, starting it again when resuming the video and so on.
So far, I am using mHandler.removeCallbacks(mRunnable);
to detain it. But to start it or resume it, I don't know if I should use mHandler.post(mRunnable); mHandler.postDelay(mRunnable, DELAY)
or mRunnable.run();
. I succeed making them all work but the behaviour is never as expected...
Here is the code I use to set up the Handler...
public void setUpdatePositionHandler() {
mHandler = new Handler();
mRunnable = new Runnable() {
@Override
public void run() {
if (mVideoView.getCurrentPosition() > mVideoView.getDuration()) {
if (mVideoView.getCurrentPosition() > 1000) {
mVideoView.seekTo(1); // go back to beginning
mVideoView.pause();
mPlayButton.setVisibility(View.VISIBLE);
mStampIndex = 0;
mLastPosition = 0;
Log.i(TAG, "removeCallbacks() from runnable");
mHandler.removeCallbacks(this);
} else {
//mHandler.postDelayed(this, DELAY);
}
} else {
if (!mStamps.isEmpty()) {
onPositionUpdate(mStamps);
}
mHandler.postDelayed(this, DELAY);
}
}
};
Note that I don't feel really sure of what I implemented so far, and that any ressources that would help me understand better would be welcome :) (I already read the documentations of the 2 classes and read several documents or posts on the subjects, but I think I am missing something.)
Thank you for your help