|
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file, |
|
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
4 |
|
5 package org.mozilla.gecko.util; |
|
6 |
|
7 import android.os.Handler; |
|
8 import android.os.Looper; |
|
9 |
|
10 import java.util.concurrent.SynchronousQueue; |
|
11 |
|
12 final class GeckoBackgroundThread extends Thread { |
|
13 private static final String LOOPER_NAME = "GeckoBackgroundThread"; |
|
14 |
|
15 // Guarded by 'this'. |
|
16 private static Handler sHandler = null; |
|
17 private SynchronousQueue<Handler> mHandlerQueue = new SynchronousQueue<Handler>(); |
|
18 |
|
19 // Singleton, so private constructor. |
|
20 private GeckoBackgroundThread() { |
|
21 super(); |
|
22 } |
|
23 |
|
24 @Override |
|
25 public void run() { |
|
26 setName(LOOPER_NAME); |
|
27 Looper.prepare(); |
|
28 try { |
|
29 mHandlerQueue.put(new Handler()); |
|
30 } catch (InterruptedException ie) {} |
|
31 |
|
32 Looper.loop(); |
|
33 } |
|
34 |
|
35 // Get a Handler for a looper thread, or create one if it doesn't yet exist. |
|
36 /*package*/ static synchronized Handler getHandler() { |
|
37 if (sHandler == null) { |
|
38 GeckoBackgroundThread lt = new GeckoBackgroundThread(); |
|
39 ThreadUtils.setBackgroundThread(lt); |
|
40 lt.start(); |
|
41 try { |
|
42 sHandler = lt.mHandlerQueue.take(); |
|
43 } catch (InterruptedException ie) {} |
|
44 } |
|
45 return sHandler; |
|
46 } |
|
47 |
|
48 /*package*/ static void post(Runnable runnable) { |
|
49 Handler handler = getHandler(); |
|
50 if (handler == null) { |
|
51 throw new IllegalStateException("No handler! Must have been interrupted. Not posting."); |
|
52 } |
|
53 handler.post(runnable); |
|
54 } |
|
55 } |