content: /*
   * Copyright (C) 2020 - Amir Hossein Aghajari
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *
   */
  
  
  package com.aghajari.emojiview.preset;
  
  import android.os.Handler;
  import android.os.Looper;
  
  import java.util.concurrent.CountDownLatch;
  
  public class DispatchQueue extends Thread {
  
      private volatile Handler handler = null;
      private final CountDownLatch syncLatch = new CountDownLatch(1);
  
      public DispatchQueue(final String threadName) {
          setName(threadName);
          start();
      }
  
      public void cancelRunnable(Runnable runnable) {
          try {
              syncLatch.await();
              handler.removeCallbacks(runnable);
          } catch (Exception ignore) {
          }
      }
  
      public void postRunnable(Runnable runnable) {
          postRunnable(runnable, 0);
      }
  
      public void postRunnable(Runnable runnable, long delay) {
          try {
              syncLatch.await();
          } catch (Exception ignore) {
  
          }
          if (delay <= 0) {
              handler.post(runnable);
          } else {
              handler.postDelayed(runnable, delay);
          }
      }
  
      public void cleanupQueue() {
          try {
              syncLatch.await();
              handler.removeCallbacksAndMessages(null);
          } catch (Exception ignore) {
  
          }
      }
  
      public void recycle() {
          handler.getLooper().quit();
      }
  
      @Override
      public void run() {
          Looper.prepare();
          handler = new Handler();
          syncLatch.countDown();
          Looper.loop();
      }
  }
  