Search code examples
androidandroid-youtube-api

Android YouTubePlayer - get event on certain time of playing


I need make some action after video have played 50% of its length.

So I did not see some listener with something like "onCertainMills()", I see onVideoEnded() but I need get event when current time of played video will more then length/2.


Solution

  • At the end of the ends I have made class to make action on certain second of playing video. Here is the code to make some action after half time of the video playing: (+ 1 sec) Hope it will help to someone.

    import android.os.Handler;
    import android.util.Log;
    
    import com.clipclash.android.entities.Clip;
    import com.google.android.youtube.player.YouTubePlayer;
    
    public class YoutubeCounter {
    
        Clip clip;
        long counter;
        long startCut;
        long endCut;
        long durationGoal;
        private YouTubePlayer youTubePlayer;
        boolean goal = false;
        Handler h;
    
    
        Runnable checkGoal = new Runnable() {
            public void run() {
                getProgress();
                if (counter >= durationGoal) {
                    // GOAL !!!
                    //TODO MAKE SOME ACTION
                    goal = true;
                    stopSchedule();
                } else {
                    startSchedule();
                }
            }
        };
    
        public YoutubeCounter(Clip clip) {
            this.clip = clip;
            h = new Handler();
        }
    
    
        public void setYouTubePlayer(YouTubePlayer youTubePlayer) {
            this.youTubePlayer = youTubePlayer;
        }
    
        public void play() {
            if (!goal) {
                if (durationGoal == 0) {
                    durationGoal = this.youTubePlayer.getDurationMillis() / 2;
                }
                startCut = youTubePlayer.getCurrentTimeMillis();
                startSchedule();
            }
        }
    
        public void stop() {
            if (!goal) {
                getProgress();
                stopSchedule();
            }
        }
    
        private void startSchedule() {
            long newSchedule = durationGoal - counter;
            newSchedule = newSchedule + 1000; // just a little bit more - not requires
            h.postDelayed(checkGoal, newSchedule);
        }
    
        public void stopSchedule() {
            h.removeCallbacks(checkGoal);
        }
    
        private void getProgress() {
            try {
                endCut = youTubePlayer.getCurrentTimeMillis();
                long cut = endCut - startCut;
                if (cut < 0) {
                    cut = 0;
                }
                counter += cut;
            } catch (Exception e) {
            }
        }
    
        public long getCounter() {
            return counter;
        }
    }