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.
5 package org.chromium.base;
7 import android.content.Context;
9 import java.lang.ref.WeakReference;
10 import java.util.concurrent.Callable;
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;
18 public static void initializeWeakContext(final Context context) {
19 sWeakContext = new WeakReference<Context>(context);
22 public static Context getContext() {
23 return sWeakContext.get();
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) {
35 if (ThreadUtils.runningOnUiThread()) {
36 return context.getSystemService(name);
38 return ThreadUtils.runOnUiThreadBlockingNoException(new Callable<Object>() {
40 public Object call() {
41 return context.getSystemService(name);