| 1 | // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | package org.chromium.base; |
| 6 | |
| 7 | import android.content.Context; |
| 8 | |
| 9 | import java.lang.ref.WeakReference; |
| 10 | import java.util.concurrent.Callable; |
| 11 | |
| 12 | // Holds a WeakReference to Context to allow it to be GC'd. |
| 13 | // Also provides utility functions to getSystemService from the UI or any |
| 14 | // other thread (may return null, if the Context has been nullified). |
| 15 | public class WeakContext { |
| 16 | private static WeakReference<Context> sWeakContext; |
| 17 | |
| 18 | public static void initializeWeakContext(final Context context) { |
| 19 | sWeakContext = new WeakReference<Context>(context); |
| 20 | } |
| 21 | |
| 22 | public static Context getContext() { |
| 23 | return sWeakContext.get(); |
| 24 | } |
| 25 | |
| 26 | // Returns a system service. May be called from any thread. |
| 27 | // If necessary, it will send a message to the main thread to acquire the |
| 28 | // service, and block waiting for it to complete. |
| 29 | // May return null if context is no longer available. |
| 30 | public static Object getSystemService(final String name) { |
| 31 | final Context context = sWeakContext.get(); |
| 32 | if (context == null) { |
| 33 | return null; |
| 34 | } |
| 35 | if (ThreadUtils.runningOnUiThread()) { |
| 36 | return context.getSystemService(name); |
| 37 | } |
| 38 | return ThreadUtils.runOnUiThreadBlockingNoException(new Callable<Object>() { |
| 39 | @Override |
| 40 | public Object call() { |
| 41 | return context.getSystemService(name); |
| 42 | } |
| 43 | }); |
| 44 | } |
| 45 | } |