E J Chathuranga
E J Chathuranga

Reputation: 925

Timer and TimerTask in android - further understanding

I'm building an app using camera2 API. Now I'm referencing Google samples in github. The problem is I couldn't understand why Timer and TimerTask classes used when stopping currently recording video. Hope help in here. Thank you.

Here The Code :

 private void stopRecordingVideo() {
    // UI
    mIsRecordingVideo = false;
    mButtonVideo.setText(R.string.record);
    // Stop recording
    try {
        mPreviewSession.stopRepeating();
        mPreviewSession.abortCaptures();
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

    Timer timer = new Timer();
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            mMediaRecorder.stop();
            mMediaRecorder.reset();
        }
    };
    timer.schedule(timerTask,30);

    startPreview();
}

I just want to know that
1. How the Timer and TimeTask is working
2. How the above classes combine with each other
3. An additionally what is the major role in this method?

Upvotes: 0

Views: 59

Answers (1)

Quang Nguyen
Quang Nguyen

Reputation: 2660

Firstly, it should be made clear that Timer and TimerTask are parts of java.util, not belong to Android framework.
1. How the Timer and TimerTask is working
TimerTask is an utility class which implements Runnable to override run method to perform your defined task. Meanwhile, Timer helps you to schedule time and execute that task. Besides, your task will be performed in a background thread.
2. How the above classes combine with each other
As described above, TimerTask will define your actual task and Timer will set an alarm to execute it.
3. An additionally what is the major role in this method?
When you call stopRecordingVideo(), Timer is used here to turn off MediaRecorder in background thread after 30 milliseconds. As I thought, the main purpose of using Timer here to execute MediaRecorder.stop() in a background threa rather than UI thread.

Upvotes: 1

Related Questions