Use timed metadata at the appropriate time

Use TimedMetadata when the current playback time matches the start time.

Use the saved ArrayList from the previous topic to actually use these saved TimedMetadata objects during playback.

  1. Run a timer and query current playback time repeatedly.
  2. Find all the TimedMetadata objects whose start time values match the current playback time. You can use these objects to perform various actions. When checking whether the current playback time matches any TimedMetadata objects, put this as a condition as well: shouldTriggerSubscribedTagEvent. The timeline might change due to various ad behaviors. For example, one or more ad breaks might be moved from their original positions on the timeline. shouldTriggerSubscribedTagEvent makes sure that the TimeMetadata object's start time matches the current playback time correctly. For example:
    _playbackClockEventListener = new Clock.ClockEventListener() {
        @Override
        public void onTick(String name) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                             
                    /* handle timedmetadata object list  */
                    if (_mediaPlayer != null && _timedMetadataList != null && _timedMetadataList.size() > 0) {
                        if (_lastKnownStatus == MediaPlayer.PlayerState.PLAYING) {
                            long localTime = _mediaPlayer.getLocalTime();
                            Iterator<TimedMetadata> iterator = _timedMetadataList.iterator();
                            while (iterator.hasNext()) {
                                TimedMetadata timedMetadata = iterator.next();
                                long diff = localTime - timedMetadata.getTime();
                                if (diff >= 0 &&
                                    diff <= PLAYBACK_CLOCK_INTERVAL &&
                                    _mediaPlayer.shouldTriggerSubscribedTagEvent()) {
     
                                    // use timed metadata object
                                    PMPDemoApp.logger.i(LOG_TAG + "#METADATA_CLOCK", "Local time: " + localTime
                                                        +" ; timed metadata start time: "
                                                        + timedMetadata + ".");
                                }
                            }
                        }
                    }
                }
            });
        }
    };
     
    _playbackClock.addClockEventListener(_playbackClockEventListener);
  3. Periodically flush stale TimedMetadata instances from the list to prevent memory from growing continuously.