1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/mobile/android/base/util/GeckoBackgroundThread.java Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,55 @@ 1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this file, 1.6 + * You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.7 + 1.8 +package org.mozilla.gecko.util; 1.9 + 1.10 +import android.os.Handler; 1.11 +import android.os.Looper; 1.12 + 1.13 +import java.util.concurrent.SynchronousQueue; 1.14 + 1.15 +final class GeckoBackgroundThread extends Thread { 1.16 + private static final String LOOPER_NAME = "GeckoBackgroundThread"; 1.17 + 1.18 + // Guarded by 'this'. 1.19 + private static Handler sHandler = null; 1.20 + private SynchronousQueue<Handler> mHandlerQueue = new SynchronousQueue<Handler>(); 1.21 + 1.22 + // Singleton, so private constructor. 1.23 + private GeckoBackgroundThread() { 1.24 + super(); 1.25 + } 1.26 + 1.27 + @Override 1.28 + public void run() { 1.29 + setName(LOOPER_NAME); 1.30 + Looper.prepare(); 1.31 + try { 1.32 + mHandlerQueue.put(new Handler()); 1.33 + } catch (InterruptedException ie) {} 1.34 + 1.35 + Looper.loop(); 1.36 + } 1.37 + 1.38 + // Get a Handler for a looper thread, or create one if it doesn't yet exist. 1.39 + /*package*/ static synchronized Handler getHandler() { 1.40 + if (sHandler == null) { 1.41 + GeckoBackgroundThread lt = new GeckoBackgroundThread(); 1.42 + ThreadUtils.setBackgroundThread(lt); 1.43 + lt.start(); 1.44 + try { 1.45 + sHandler = lt.mHandlerQueue.take(); 1.46 + } catch (InterruptedException ie) {} 1.47 + } 1.48 + return sHandler; 1.49 + } 1.50 + 1.51 + /*package*/ static void post(Runnable runnable) { 1.52 + Handler handler = getHandler(); 1.53 + if (handler == null) { 1.54 + throw new IllegalStateException("No handler! Must have been interrupted. Not posting."); 1.55 + } 1.56 + handler.post(runnable); 1.57 + } 1.58 +}