How to make HandlerThread backward compatible?

HandlerThread is a useful component in Android for managing threads, but it may not be available or fully functional in older versions of Android. To ensure backward compatibility, you can create a custom solution that mimics the behavior of HandlerThread using existing threading classes like Thread and Handler. Below is an example demonstrating how to implement a simple class that behaves similarly to HandlerThread.

class MyHandlerThread { private Handler handler; private final Object lock = new Object(); private Thread thread; private boolean running; public MyHandlerThread(final String name) { thread = new Thread(new Runnable() { @Override public void run() { Looper.prepare(); synchronized (lock) { running = true; lock.notify(); } Looper.loop(); } }, name); } public void start() { thread.start(); synchronized (lock) { while (!running) { try { lock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } handler = new Handler(thread.getLooper()); } public void quit() { if (handler != null) { handler.getLooper().quit(); } } public Handler getHandler() { return handler; } }

HandlerThread Android backward compatibility custom threading thread management