1 // Copyright 2013 The Chromium Authors 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.test.util; 6 7 import android.content.Context; 8 import android.content.SharedPreferences; 9 10 import java.util.HashMap; 11 import java.util.Map; 12 13 /** ContextWrapper that causes SharedPreferences to not persist to disk. */ 14 public class InMemorySharedPreferencesContext extends ApplicationContextWrapper { 15 protected final Map<String, SharedPreferences> mSharedPreferences = 16 new HashMap<String, SharedPreferences>(); 17 InMemorySharedPreferencesContext(Context base)18 public InMemorySharedPreferencesContext(Context base) { 19 super(base); 20 } 21 22 @Override getSharedPreferences(String name, int mode)23 public SharedPreferences getSharedPreferences(String name, int mode) { 24 // Pass through multidex prefs to avoid excessive multidex extraction on KitKat. 25 if (name.endsWith("multidex.version")) { 26 return getBaseContext().getSharedPreferences(name, mode); 27 } 28 synchronized (mSharedPreferences) { 29 if (!mSharedPreferences.containsKey(name)) { 30 mSharedPreferences.put(name, new InMemorySharedPreferences()); 31 } 32 return mSharedPreferences.get(name); 33 } 34 } 35 36 /** Calls .clear() on all SharedPreferences. */ clearSharedPreferences()37 public void clearSharedPreferences() { 38 synchronized (mSharedPreferences) { 39 // Clear each instance rather than the map in case there are any registered listeners 40 // or cached references to them. 41 for (SharedPreferences prefs : mSharedPreferences.values()) { 42 prefs.edit().clear().apply(); 43 } 44 } 45 } 46 } 47