1 /* 2 * Copyright (C) 2019 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.wallpaperbackup.utils; 18 19 import android.content.Context; 20 import android.content.ContextWrapper; 21 import android.content.SharedPreferences; 22 23 import java.util.HashMap; 24 import java.util.Map; 25 26 public class ContextWithServiceOverrides extends ContextWrapper { 27 private static final String TAG = "ContextWithOverrides"; 28 29 private Map<String, Object> mInjectedSystemServices = new HashMap<>(); 30 private SharedPreferences mSharedPreferencesOverride; 31 ContextWithServiceOverrides(Context base)32 public ContextWithServiceOverrides(Context base) { 33 super(base); 34 } 35 injectSystemService(Class<S> cls, S service)36 public <S> void injectSystemService(Class<S> cls, S service) { 37 final String name = getSystemServiceName(cls); 38 mInjectedSystemServices.put(name, service); 39 } 40 41 @Override getApplicationContext()42 public Context getApplicationContext() { 43 return this; 44 } 45 46 @Override getSystemService(String name)47 public Object getSystemService(String name) { 48 if (mInjectedSystemServices.containsKey(name)) { 49 return mInjectedSystemServices.get(name); 50 } 51 return super.getSystemService(name); 52 } 53 setSharedPreferencesOverride(SharedPreferences override)54 public void setSharedPreferencesOverride(SharedPreferences override) { 55 mSharedPreferencesOverride = override; 56 } 57 58 @Override getSharedPreferences(String name, int mode)59 public SharedPreferences getSharedPreferences(String name, int mode) { 60 return mSharedPreferencesOverride == null 61 ? super.getSharedPreferences(name, mode) 62 : mSharedPreferencesOverride; 63 } 64 } 65