0

I have to load a font with callbacks and set it as the theme typeface with a reflection method. And this has to be done before the setContentView() in onCreate() is called. I tried to use a CountDownLatch on the main thread as below to make it wait for the font loading process:

loadFont();
try {
            System.out.println("latch awaiting");
            latch.await();
        } catch (InterruptedException e) {
            System.out.println("latch error");
            e.printStackTrace();
        } finally {
            System.out.println("latch error");
            latch.countDown();
        }

But it appears that the callback is initiated, but never returned any result as it normally would(onTypefaceRetrieved() not called). The new thread and callbacksks are initiated as below:

Runnable runnable = new Runnable(){
@Override
    public void run() {
        FontCall.Callback callback = new FontCall.FontCallback(){
             @Override
             public void onFontRetrieved(final Typeface typeface) {
                 //do reflection stuff
                 latch.countDown();
             } 
             @Override
             public void onError(int err) {
                 //handle error
                 latch.countDown();
             }
        };
        FontCall.requestFont(callback);
    }
};
Thread thread = new Thread(runnable);
thread.run();

Can someone tell me what I did wrong? Or am I not supposed to do this kind of thing (make UI thread wait) at all? (For reference, the font is usually retrieved from Android's font cache, which takes about less than 100ms.)

Jack
  • 5,354
  • 2
  • 29
  • 54
  • Try this way. add a SplashActivity, using it to load the font and save in a singleton class. The second Thread way is deprecated, consider about Timer or HandleThread. – xingjiu Oct 09 '18 at 09:04
  • Can you elaborate on how saving the font works and the HandleThread stuff? I'm still pretty new to all these. – Jack Oct 09 '18 at 20:29
  • Nevermind, I have figured out how to use the HandleThread instead, thanks. – Jack Oct 09 '18 at 22:42

1 Answers1

0

Thanks for xingjiu's hint, I switched the new Thread implementation to a HandleThread implementation and now it works flawlessly:

HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
handlerThread.start();
Looper looper = handlerThread.getLooper();
Handler handler = new Handler(looper);

and then run it using the same runnable with handler.post(runnable);

Jack
  • 5,354
  • 2
  • 29
  • 54