Home | History | Annotate | Download | only in util
      1 /*
      2  * Copyright (C) 2015 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.camera.util;
     18 
     19 import android.content.Context;
     20 import android.support.annotation.NonNull;
     21 
     22 /**
     23  * Initializable singleton for providing the application level context
     24  * object instead of initializing each singleton separately.
     25  */
     26 public class AndroidContext {
     27     private static AndroidContext sInstance;
     28 
     29     /**
     30      * The android context object cannot be created until the android
     31      * has created the application object. The AndroidContext object
     32      * must be initialized before other singletons can use it.
     33      */
     34     public static void initialize(@NonNull Context context) {
     35         if (sInstance == null) {
     36             sInstance = new AndroidContext(context);
     37         }
     38     }
     39 
     40     /**
     41      * Return a previously initialized instance, throw if it has not been
     42      * initialized yet.
     43      */
     44     public static AndroidContext instance() {
     45         if (sInstance == null) {
     46             throw new IllegalStateException("Android context was not initialized.");
     47         }
     48         return sInstance;
     49     }
     50 
     51     private final Context mContext;
     52     private AndroidContext(Context context) {
     53         mContext = context;
     54     }
     55 
     56     public Context get() {
     57         return mContext;
     58     }
     59 }