blob: e1a5b52510f7326891b95d1d6fb4fb2d64668731 [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2007 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
17package com.android.providers.settings;
18
-b master501eec92009-07-06 13:53:11 -070019import java.io.FileNotFoundException;
Doug Zongker4f8ff392010-02-03 10:36:40 -080020import java.security.SecureRandom;
Christopher Tate06efb532012-08-24 15:29:27 -070021import java.util.HashSet;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070022import java.util.concurrent.atomic.AtomicBoolean;
23import java.util.concurrent.atomic.AtomicInteger;
-b master501eec92009-07-06 13:53:11 -070024
Christopher Tated5fe1472012-09-10 15:48:38 -070025import android.app.ActivityManager;
Christopher Tate06efb532012-08-24 15:29:27 -070026import android.app.ActivityManagerNative;
Christopher Tate45281862010-03-05 15:46:30 -080027import android.app.backup.BackupManager;
Christopher Tate06efb532012-08-24 15:29:27 -070028import android.content.BroadcastReceiver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070029import android.content.ContentProvider;
30import android.content.ContentUris;
31import android.content.ContentValues;
32import android.content.Context;
Christopher Tate06efb532012-08-24 15:29:27 -070033import android.content.Intent;
34import android.content.IntentFilter;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070035import android.content.pm.PackageManager;
Christopher Tate06efb532012-08-24 15:29:27 -070036import android.content.pm.UserInfo;
Marco Nelissen69f593c2009-07-28 09:55:04 -070037import android.content.res.AssetFileDescriptor;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070038import android.database.Cursor;
39import android.database.sqlite.SQLiteDatabase;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080040import android.database.sqlite.SQLiteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070041import android.database.sqlite.SQLiteQueryBuilder;
Christopher Tate06efb532012-08-24 15:29:27 -070042import android.database.sqlite.SQLiteStatement;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070043import android.media.RingtoneManager;
44import android.net.Uri;
Christopher Tate06efb532012-08-24 15:29:27 -070045import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080046import android.os.Bundle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070047import android.os.FileObserver;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070048import android.os.ParcelFileDescriptor;
Christopher Tate06efb532012-08-24 15:29:27 -070049import android.os.RemoteException;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070050import android.os.SystemProperties;
Christopher Tate06efb532012-08-24 15:29:27 -070051import android.os.UserHandle;
52import android.os.UserManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070053import android.provider.DrmStore;
54import android.provider.MediaStore;
55import android.provider.Settings;
56import android.text.TextUtils;
57import android.util.Log;
Jesse Wilson0c7faee2011-02-10 11:33:19 -080058import android.util.LruCache;
Christopher Tate06efb532012-08-24 15:29:27 -070059import android.util.Slog;
60import android.util.SparseArray;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070061
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070062public class SettingsProvider extends ContentProvider {
63 private static final String TAG = "SettingsProvider";
Christopher Tate4dc7a682012-09-11 12:15:49 -070064 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070065
Christopher Tate06efb532012-08-24 15:29:27 -070066 private static final String TABLE_SYSTEM = "system";
67 private static final String TABLE_SECURE = "secure";
68 private static final String TABLE_GLOBAL = "global";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 private static final String TABLE_FAVORITES = "favorites";
70 private static final String TABLE_OLD_FAVORITES = "old_favorites";
71
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080072 private static final String[] COLUMN_VALUE = new String[] { "value" };
73
Christopher Tate06efb532012-08-24 15:29:27 -070074 // Caches for each user's settings, access-ordered for acting as LRU.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080075 // Guarded by themselves.
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070076 private static final int MAX_CACHE_ENTRIES = 200;
Christopher Tate06efb532012-08-24 15:29:27 -070077 private static final SparseArray<SettingsCache> sSystemCaches
78 = new SparseArray<SettingsCache>();
79 private static final SparseArray<SettingsCache> sSecureCaches
80 = new SparseArray<SettingsCache>();
81 private static final SettingsCache sGlobalCache = new SettingsCache(TABLE_GLOBAL);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070082
83 // The count of how many known (handled by SettingsProvider)
Christopher Tate06efb532012-08-24 15:29:27 -070084 // database mutations are currently being handled for this user.
85 // Used by file observers to not reload the database when it's ourselves
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070086 // modifying it.
Christopher Tate06efb532012-08-24 15:29:27 -070087 private static final SparseArray<AtomicInteger> sKnownMutationsInFlight
88 = new SparseArray<AtomicInteger>();
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080089
Brad Fitzpatrick342984a2010-03-09 16:59:30 -080090 // Over this size we don't reject loading or saving settings but
91 // we do consider them broken/malicious and don't keep them in
92 // memory at least:
93 private static final int MAX_CACHE_ENTRY_SIZE = 500;
94
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -080095 private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
96
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -070097 // Used as a sentinel value in an instance equality test when we
98 // want to cache the existence of a key, but not store its value.
99 private static final Bundle TOO_LARGE_TO_CACHE_MARKER = Bundle.forPair("_dummy", null);
100
Christopher Tate06efb532012-08-24 15:29:27 -0700101 // Each defined user has their own settings
102 protected final SparseArray<DatabaseHelper> mOpenHelpers = new SparseArray<DatabaseHelper>();
103 //protected DatabaseHelper mOpenHelper;
104 private UserManager mUserManager;
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700105 private BackupManager mBackupManager;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700106
107 /**
Christopher Tate06efb532012-08-24 15:29:27 -0700108 * Settings which need to be treated as global/shared in multi-user environments.
109 */
110 static final HashSet<String> sSecureGlobalKeys;
111 static final HashSet<String> sSystemGlobalKeys;
112 static {
113 // Keys (name column) from the 'secure' table that are now in the owner user's 'global'
114 // table, shared across all users
115 // These must match Settings.Secure.MOVED_TO_GLOBAL
116 sSecureGlobalKeys = new HashSet<String>();
Christopher Tate92198742012-09-07 12:00:13 -0700117 sSecureGlobalKeys.add(Settings.Secure.ADB_ENABLED);
Christopher Tate06efb532012-08-24 15:29:27 -0700118 sSecureGlobalKeys.add(Settings.Secure.ASSISTED_GPS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700119 sSecureGlobalKeys.add(Settings.Secure.BLUETOOTH_ON);
Christopher Tate06efb532012-08-24 15:29:27 -0700120 sSecureGlobalKeys.add(Settings.Secure.CDMA_CELL_BROADCAST_SMS);
121 sSecureGlobalKeys.add(Settings.Secure.CDMA_ROAMING_MODE);
122 sSecureGlobalKeys.add(Settings.Secure.CDMA_SUBSCRIPTION_MODE);
123 sSecureGlobalKeys.add(Settings.Secure.DATA_ACTIVITY_TIMEOUT_MOBILE);
124 sSecureGlobalKeys.add(Settings.Secure.DATA_ACTIVITY_TIMEOUT_WIFI);
Christopher Tate92198742012-09-07 12:00:13 -0700125 sSecureGlobalKeys.add(Settings.Secure.DATA_ROAMING);
Christopher Tate06efb532012-08-24 15:29:27 -0700126 sSecureGlobalKeys.add(Settings.Secure.DEVELOPMENT_SETTINGS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700127 sSecureGlobalKeys.add(Settings.Secure.DEVICE_PROVISIONED);
Christopher Tate06efb532012-08-24 15:29:27 -0700128 sSecureGlobalKeys.add(Settings.Secure.DISPLAY_DENSITY_FORCED);
129 sSecureGlobalKeys.add(Settings.Secure.DISPLAY_SIZE_FORCED);
130 sSecureGlobalKeys.add(Settings.Secure.DOWNLOAD_MAX_BYTES_OVER_MOBILE);
131 sSecureGlobalKeys.add(Settings.Secure.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE);
Christopher Tate92198742012-09-07 12:00:13 -0700132 sSecureGlobalKeys.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
Christopher Tate06efb532012-08-24 15:29:27 -0700133 sSecureGlobalKeys.add(Settings.Secure.MOBILE_DATA);
134 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_BUCKET_DURATION);
135 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_DELETE_AGE);
136 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_PERSIST_BYTES);
137 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_DEV_ROTATE_AGE);
138 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_ENABLED);
139 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_GLOBAL_ALERT_BYTES);
140 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_POLL_INTERVAL);
141 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_REPORT_XT_OVER_DEV);
142 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_SAMPLE_ENABLED);
143 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_TIME_CACHE_MAX_AGE);
144 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_BUCKET_DURATION);
145 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_DELETE_AGE);
146 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_PERSIST_BYTES);
147 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_ROTATE_AGE);
148 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_BUCKET_DURATION);
149 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_DELETE_AGE);
150 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_PERSIST_BYTES);
151 sSecureGlobalKeys.add(Settings.Secure.NETSTATS_UID_TAG_ROTATE_AGE);
152 sSecureGlobalKeys.add(Settings.Secure.NETWORK_PREFERENCE);
153 sSecureGlobalKeys.add(Settings.Secure.NITZ_UPDATE_DIFF);
154 sSecureGlobalKeys.add(Settings.Secure.NITZ_UPDATE_SPACING);
155 sSecureGlobalKeys.add(Settings.Secure.NTP_SERVER);
156 sSecureGlobalKeys.add(Settings.Secure.NTP_TIMEOUT);
157 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_ERROR_POLL_COUNT);
158 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_LONG_POLL_INTERVAL_MS);
159 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_MAX_PDP_RESET_FAIL_COUNT);
160 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_POLL_INTERVAL_MS);
161 sSecureGlobalKeys.add(Settings.Secure.PDP_WATCHDOG_TRIGGER_PACKET_COUNT);
162 sSecureGlobalKeys.add(Settings.Secure.SAMPLING_PROFILER_MS);
163 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DATA_SERVICE_URL);
164 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DETECTION_REDIR_HOST);
165 sSecureGlobalKeys.add(Settings.Secure.SETUP_PREPAID_DETECTION_TARGET_URL);
166 sSecureGlobalKeys.add(Settings.Secure.TETHER_DUN_APN);
167 sSecureGlobalKeys.add(Settings.Secure.TETHER_DUN_REQUIRED);
168 sSecureGlobalKeys.add(Settings.Secure.TETHER_SUPPORTED);
169 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_HELP_URI);
170 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_MAX_NTP_CACHE_AGE_SEC);
171 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_NOTIFICATION_TYPE);
172 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_POLLING_SEC);
173 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_RESET_DAY);
174 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_THRESHOLD_BYTES);
175 sSecureGlobalKeys.add(Settings.Secure.THROTTLE_VALUE_KBITSPS);
Christopher Tate92198742012-09-07 12:00:13 -0700176 sSecureGlobalKeys.add(Settings.Secure.USB_MASS_STORAGE_ENABLED);
Christopher Tate06efb532012-08-24 15:29:27 -0700177 sSecureGlobalKeys.add(Settings.Secure.USE_GOOGLE_MAIL);
178 sSecureGlobalKeys.add(Settings.Secure.WEB_AUTOFILL_QUERY_URL);
179 sSecureGlobalKeys.add(Settings.Secure.WIFI_COUNTRY_CODE);
180 sSecureGlobalKeys.add(Settings.Secure.WIFI_FRAMEWORK_SCAN_INTERVAL_MS);
181 sSecureGlobalKeys.add(Settings.Secure.WIFI_FREQUENCY_BAND);
182 sSecureGlobalKeys.add(Settings.Secure.WIFI_IDLE_MS);
183 sSecureGlobalKeys.add(Settings.Secure.WIFI_MAX_DHCP_RETRY_COUNT);
184 sSecureGlobalKeys.add(Settings.Secure.WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS);
185 sSecureGlobalKeys.add(Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON);
186 sSecureGlobalKeys.add(Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY);
187 sSecureGlobalKeys.add(Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT);
188 sSecureGlobalKeys.add(Settings.Secure.WIFI_ON);
189 sSecureGlobalKeys.add(Settings.Secure.WIFI_P2P_DEVICE_NAME);
190 sSecureGlobalKeys.add(Settings.Secure.WIFI_SAVED_STATE);
191 sSecureGlobalKeys.add(Settings.Secure.WIFI_SUPPLICANT_SCAN_INTERVAL_MS);
192 sSecureGlobalKeys.add(Settings.Secure.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED);
193 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_NUM_ARP_PINGS);
194 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_ON);
195 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED);
196 sSecureGlobalKeys.add(Settings.Secure.WIFI_WATCHDOG_RSSI_FETCH_INTERVAL_MS);
197 sSecureGlobalKeys.add(Settings.Secure.WIMAX_NETWORKS_AVAILABLE_NOTIFICATION_ON);
Christopher Tatec868b642012-09-12 17:41:04 -0700198 sSecureGlobalKeys.add(Settings.Secure.PACKAGE_VERIFIER_ENABLE);
199 sSecureGlobalKeys.add(Settings.Secure.PACKAGE_VERIFIER_TIMEOUT);
200 sSecureGlobalKeys.add(Settings.Secure.PACKAGE_VERIFIER_DEFAULT_RESPONSE);
201 sSecureGlobalKeys.add(Settings.Secure.DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS);
202 sSecureGlobalKeys.add(Settings.Secure.DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS);
203 sSecureGlobalKeys.add(Settings.Secure.GPRS_REGISTER_CHECK_PERIOD_MS);
Christopher Tate06efb532012-08-24 15:29:27 -0700204 sSecureGlobalKeys.add(Settings.Secure.WTF_IS_FATAL);
205
206 // Keys from the 'system' table now moved to 'global'
207 // These must match Settings.System.MOVED_TO_GLOBAL
208 sSystemGlobalKeys = new HashSet<String>();
Christopher Tate06efb532012-08-24 15:29:27 -0700209
210 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_ON);
211 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_RADIOS);
212 sSystemGlobalKeys.add(Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
213 sSystemGlobalKeys.add(Settings.System.AUTO_TIME);
214 sSystemGlobalKeys.add(Settings.System.AUTO_TIME_ZONE);
215 sSystemGlobalKeys.add(Settings.System.CAR_DOCK_SOUND);
216 sSystemGlobalKeys.add(Settings.System.CAR_UNDOCK_SOUND);
217 sSystemGlobalKeys.add(Settings.System.DESK_DOCK_SOUND);
218 sSystemGlobalKeys.add(Settings.System.DESK_UNDOCK_SOUND);
219 sSystemGlobalKeys.add(Settings.System.DOCK_SOUNDS_ENABLED);
220 sSystemGlobalKeys.add(Settings.System.LOCK_SOUND);
221 sSystemGlobalKeys.add(Settings.System.UNLOCK_SOUND);
222 sSystemGlobalKeys.add(Settings.System.LOW_BATTERY_SOUND);
223 sSystemGlobalKeys.add(Settings.System.POWER_SOUNDS_ENABLED);
Christopher Tate92198742012-09-07 12:00:13 -0700224 sSystemGlobalKeys.add(Settings.System.STAY_ON_WHILE_PLUGGED_IN);
Christopher Tate06efb532012-08-24 15:29:27 -0700225 sSystemGlobalKeys.add(Settings.System.WIFI_SLEEP_POLICY);
226 }
227
228 private boolean settingMovedToGlobal(final String name) {
229 return sSecureGlobalKeys.contains(name) || sSystemGlobalKeys.contains(name);
230 }
231
232 /**
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700233 * Decode a content URL into the table, projection, and arguments
234 * used to access the corresponding database rows.
235 */
236 private static class SqlArguments {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 public String table;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700238 public final String where;
239 public final String[] args;
240
241 /** Operate on existing rows. */
242 SqlArguments(Uri url, String where, String[] args) {
243 if (url.getPathSegments().size() == 1) {
244 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700245 if (!DatabaseHelper.isValidTable(this.table)) {
246 throw new IllegalArgumentException("Bad root path: " + this.table);
247 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700248 this.where = where;
249 this.args = args;
250 } else if (url.getPathSegments().size() != 2) {
251 throw new IllegalArgumentException("Invalid URI: " + url);
252 } else if (!TextUtils.isEmpty(where)) {
253 throw new UnsupportedOperationException("WHERE clause not supported: " + url);
254 } else {
255 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700256 if (!DatabaseHelper.isValidTable(this.table)) {
257 throw new IllegalArgumentException("Bad root path: " + this.table);
258 }
Christopher Tate06efb532012-08-24 15:29:27 -0700259 if (TABLE_SYSTEM.equals(this.table) || TABLE_SECURE.equals(this.table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700260 this.where = Settings.NameValueTable.NAME + "=?";
261 this.args = new String[] { url.getPathSegments().get(1) };
262 } else {
263 this.where = "_id=" + ContentUris.parseId(url);
264 this.args = null;
265 }
266 }
267 }
268
269 /** Insert new rows (no where clause allowed). */
270 SqlArguments(Uri url) {
271 if (url.getPathSegments().size() == 1) {
272 this.table = url.getPathSegments().get(0);
Dianne Hackborn24117ce2010-07-12 15:54:38 -0700273 if (!DatabaseHelper.isValidTable(this.table)) {
274 throw new IllegalArgumentException("Bad root path: " + this.table);
275 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700276 this.where = null;
277 this.args = null;
278 } else {
279 throw new IllegalArgumentException("Invalid URI: " + url);
280 }
281 }
282 }
283
284 /**
285 * Get the content URI of a row added to a table.
286 * @param tableUri of the entire table
287 * @param values found in the row
288 * @param rowId of the row
289 * @return the content URI for this particular row
290 */
291 private Uri getUriFor(Uri tableUri, ContentValues values, long rowId) {
292 if (tableUri.getPathSegments().size() != 1) {
293 throw new IllegalArgumentException("Invalid URI: " + tableUri);
294 }
295 String table = tableUri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700296 if (TABLE_SYSTEM.equals(table) ||
297 TABLE_SECURE.equals(table) ||
298 TABLE_GLOBAL.equals(table)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700299 String name = values.getAsString(Settings.NameValueTable.NAME);
300 return Uri.withAppendedPath(tableUri, name);
301 } else {
302 return ContentUris.withAppendedId(tableUri, rowId);
303 }
304 }
305
306 /**
307 * Send a notification when a particular content URI changes.
308 * Modify the system property used to communicate the version of
309 * this table, for tables which have such a property. (The Settings
310 * contract class uses these to provide client-side caches.)
311 * @param uri to send notifications for
312 */
Christopher Tate06efb532012-08-24 15:29:27 -0700313 private void sendNotify(Uri uri, int userHandle) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700314 // Update the system property *first*, so if someone is listening for
315 // a notification and then using the contract class to get their data,
316 // the system property will be updated and they'll get the new data.
317
Amith Yamasanid1582142009-07-08 20:04:55 -0700318 boolean backedUpDataChanged = false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700319 String property = null, table = uri.getPathSegments().get(0);
Christopher Tate06efb532012-08-24 15:29:27 -0700320 if (table.equals(TABLE_SYSTEM)) {
321 property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
Amith Yamasanid1582142009-07-08 20:04:55 -0700322 backedUpDataChanged = true;
Christopher Tate06efb532012-08-24 15:29:27 -0700323 } else if (table.equals(TABLE_SECURE)) {
324 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
325 backedUpDataChanged = true;
326 } else if (table.equals(TABLE_GLOBAL)) {
327 property = Settings.Global.SYS_PROP_SETTING_VERSION; // this one is global
Amith Yamasanid1582142009-07-08 20:04:55 -0700328 backedUpDataChanged = true;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700329 }
330
331 if (property != null) {
332 long version = SystemProperties.getLong(property, 0) + 1;
333 if (LOCAL_LOGV) Log.v(TAG, "property: " + property + "=" + version);
334 SystemProperties.set(property, Long.toString(version));
335 }
336
-b master501eec92009-07-06 13:53:11 -0700337 // Inform the backup manager about a data change
Amith Yamasanid1582142009-07-08 20:04:55 -0700338 if (backedUpDataChanged) {
339 mBackupManager.dataChanged();
340 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700341 // Now send the notification through the content framework.
342
343 String notify = uri.getQueryParameter("notify");
344 if (notify == null || "true".equals(notify)) {
345 getContext().getContentResolver().notifyChange(uri, null);
346 if (LOCAL_LOGV) Log.v(TAG, "notifying: " + uri);
347 } else {
348 if (LOCAL_LOGV) Log.v(TAG, "notification suppressed: " + uri);
349 }
350 }
351
352 /**
353 * Make sure the caller has permission to write this data.
354 * @param args supplied by the caller
355 * @throws SecurityException if the caller is forbidden to write.
356 */
357 private void checkWritePermissions(SqlArguments args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700358 if ((TABLE_SECURE.equals(args.table) || TABLE_GLOBAL.equals(args.table)) &&
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800359 getContext().checkCallingOrSelfPermission(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800360 android.Manifest.permission.WRITE_SECURE_SETTINGS) !=
361 PackageManager.PERMISSION_GRANTED) {
Brett Chabot16dd82c2009-06-18 17:00:48 -0700362 throw new SecurityException(
Doug Zongkeraed8f8e2010-01-07 18:07:50 -0800363 String.format("Permission denial: writing to secure settings requires %1$s",
364 android.Manifest.permission.WRITE_SECURE_SETTINGS));
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700365 }
366 }
367
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700368 // FileObserver for external modifications to the database file.
369 // Note that this is for platform developers only with
370 // userdebug/eng builds who should be able to tinker with the
371 // sqlite database out from under the SettingsProvider, which is
372 // normally the exclusive owner of the database. But we keep this
373 // enabled all the time to minimize development-vs-user
374 // differences in testing.
Christopher Tate06efb532012-08-24 15:29:27 -0700375 private static SparseArray<SettingsFileObserver> sObserverInstances
376 = new SparseArray<SettingsFileObserver>();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700377 private class SettingsFileObserver extends FileObserver {
378 private final AtomicBoolean mIsDirty = new AtomicBoolean(false);
Christopher Tate06efb532012-08-24 15:29:27 -0700379 private final int mUserHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700380 private final String mPath;
381
Christopher Tate06efb532012-08-24 15:29:27 -0700382 public SettingsFileObserver(int userHandle, String path) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700383 super(path, FileObserver.CLOSE_WRITE |
384 FileObserver.CREATE | FileObserver.DELETE |
385 FileObserver.MOVED_TO | FileObserver.MODIFY);
Christopher Tate06efb532012-08-24 15:29:27 -0700386 mUserHandle = userHandle;
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700387 mPath = path;
388 }
389
390 public void onEvent(int event, String path) {
Christopher Tate06efb532012-08-24 15:29:27 -0700391 int modsInFlight = sKnownMutationsInFlight.get(mUserHandle).get();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700392 if (modsInFlight > 0) {
393 // our own modification.
394 return;
395 }
Christopher Tate06efb532012-08-24 15:29:27 -0700396 Log.d(TAG, "User " + mUserHandle + " external modification to " + mPath
397 + "; event=" + event);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700398 if (!mIsDirty.compareAndSet(false, true)) {
399 // already handled. (we get a few update events
400 // during an sqlite write)
401 return;
402 }
Christopher Tate06efb532012-08-24 15:29:27 -0700403 Log.d(TAG, "User " + mUserHandle + " updating our caches for " + mPath);
404 fullyPopulateCaches(mUserHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700405 mIsDirty.set(false);
406 }
407 }
408
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700409 @Override
410 public boolean onCreate() {
Amith Yamasani8823c0a82009-07-07 14:30:17 -0700411 mBackupManager = new BackupManager(getContext());
Christopher Tate06efb532012-08-24 15:29:27 -0700412 mUserManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Fred Quintanac70239e2009-12-17 10:28:33 -0800413
Christopher Tate06efb532012-08-24 15:29:27 -0700414 synchronized (this) {
415 establishDbTrackingLocked(UserHandle.USER_OWNER);
416
417 IntentFilter userFilter = new IntentFilter();
418 userFilter.addAction(Intent.ACTION_USER_REMOVED);
419 getContext().registerReceiver(new BroadcastReceiver() {
420 @Override
421 public void onReceive(Context context, Intent intent) {
422 if (intent.getAction().equals(Intent.ACTION_USER_REMOVED)) {
423 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
424 UserHandle.USER_OWNER);
425 if (userHandle != UserHandle.USER_OWNER) {
426 onUserRemoved(userHandle);
427 }
428 }
429 }
430 }, userFilter);
Fred Quintanac70239e2009-12-17 10:28:33 -0800431 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700432 return true;
433 }
434
Christopher Tate06efb532012-08-24 15:29:27 -0700435 void onUserRemoved(int userHandle) {
436 // the db file itself will be deleted automatically, but we need to tear down
437 // our caches and other internal bookkeeping. Creation/deletion of a user's
438 // settings db infrastructure is synchronized on 'this'
439 synchronized (this) {
440 FileObserver observer = sObserverInstances.get(userHandle);
441 if (observer != null) {
442 observer.stopWatching();
443 sObserverInstances.delete(userHandle);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700444 }
Christopher Tate06efb532012-08-24 15:29:27 -0700445
446 mOpenHelpers.delete(userHandle);
447 sSystemCaches.delete(userHandle);
448 sSecureCaches.delete(userHandle);
449 sKnownMutationsInFlight.delete(userHandle);
450
451 String property = Settings.System.SYS_PROP_SETTING_VERSION + '_' + userHandle;
452 SystemProperties.set(property, "");
453 property = Settings.Secure.SYS_PROP_SETTING_VERSION + '_' + userHandle;
454 SystemProperties.set(property, "");
455 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700456 }
457
Christopher Tate06efb532012-08-24 15:29:27 -0700458 private void establishDbTrackingLocked(int userHandle) {
459 if (LOCAL_LOGV) {
460 Slog.i(TAG, "Installing settings db helper and caches for user " + userHandle);
461 }
462
463 DatabaseHelper dbhelper = new DatabaseHelper(getContext(), userHandle);
464 mOpenHelpers.append(userHandle, dbhelper);
465
466 // Watch for external modifications to the database files,
467 // keeping our caches in sync.
468 sSystemCaches.append(userHandle, new SettingsCache(TABLE_SYSTEM));
469 sSecureCaches.append(userHandle, new SettingsCache(TABLE_SECURE));
470 sKnownMutationsInFlight.append(userHandle, new AtomicInteger(0));
471 SQLiteDatabase db = dbhelper.getWritableDatabase();
472
473 // Now we can start observing it for changes
474 SettingsFileObserver observer = new SettingsFileObserver(userHandle, db.getPath());
475 sObserverInstances.append(userHandle, observer);
476 observer.startWatching();
477
Christopher Tate4dc7a682012-09-11 12:15:49 -0700478 ensureAndroidIdIsSet(userHandle);
479
Christopher Tate06efb532012-08-24 15:29:27 -0700480 startAsyncCachePopulation(userHandle);
481 }
482
483 class CachePrefetchThread extends Thread {
484 private int mUserHandle;
485
486 CachePrefetchThread(int userHandle) {
487 super("populate-settings-caches");
488 mUserHandle = userHandle;
489 }
490
491 @Override
492 public void run() {
493 fullyPopulateCaches(mUserHandle);
494 }
495 }
496
497 private void startAsyncCachePopulation(int userHandle) {
498 new CachePrefetchThread(userHandle).start();
499 }
500
501 private void fullyPopulateCaches(final int userHandle) {
502 DatabaseHelper dbHelper = mOpenHelpers.get(userHandle);
503 // Only populate the globals cache once, for the owning user
504 if (userHandle == UserHandle.USER_OWNER) {
505 fullyPopulateCache(dbHelper, TABLE_GLOBAL, sGlobalCache);
506 }
507 fullyPopulateCache(dbHelper, TABLE_SECURE, sSecureCaches.get(userHandle));
508 fullyPopulateCache(dbHelper, TABLE_SYSTEM, sSystemCaches.get(userHandle));
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700509 }
510
511 // Slurp all values (if sane in number & size) into cache.
Christopher Tate06efb532012-08-24 15:29:27 -0700512 private void fullyPopulateCache(DatabaseHelper dbHelper, String table, SettingsCache cache) {
513 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700514 Cursor c = db.query(
515 table,
516 new String[] { Settings.NameValueTable.NAME, Settings.NameValueTable.VALUE },
517 null, null, null, null, null,
518 "" + (MAX_CACHE_ENTRIES + 1) /* limit */);
519 try {
520 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800521 cache.evictAll();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700522 cache.setFullyMatchesDisk(true); // optimistic
523 int rows = 0;
524 while (c.moveToNext()) {
525 rows++;
526 String name = c.getString(0);
527 String value = c.getString(1);
528 cache.populate(name, value);
529 }
530 if (rows > MAX_CACHE_ENTRIES) {
531 // Somewhat redundant, as removeEldestEntry() will
532 // have already done this, but to be explicit:
533 cache.setFullyMatchesDisk(false);
534 Log.d(TAG, "row count exceeds max cache entries for table " + table);
535 }
Brad Fitzpatrick3a2952b2010-08-26 17:16:14 -0700536 Log.d(TAG, "cache for settings table '" + table + "' rows=" + rows + "; fullycached=" +
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700537 cache.fullyMatchesDisk());
538 }
539 } finally {
540 c.close();
541 }
542 }
543
Christopher Tate4dc7a682012-09-11 12:15:49 -0700544 private boolean ensureAndroidIdIsSet(int userHandle) {
545 final Cursor c = queryForUser(Settings.Secure.CONTENT_URI,
Fred Quintanac70239e2009-12-17 10:28:33 -0800546 new String[] { Settings.NameValueTable.VALUE },
547 Settings.NameValueTable.NAME + "=?",
Christopher Tate4dc7a682012-09-11 12:15:49 -0700548 new String[] { Settings.Secure.ANDROID_ID }, null,
549 userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800550 try {
551 final String value = c.moveToNext() ? c.getString(0) : null;
552 if (value == null) {
Nick Kralevich9bb4ec42010-09-24 11:48:37 -0700553 final SecureRandom random = new SecureRandom();
Fred Quintanac70239e2009-12-17 10:28:33 -0800554 final String newAndroidIdValue = Long.toHexString(random.nextLong());
Fred Quintanac70239e2009-12-17 10:28:33 -0800555 final ContentValues values = new ContentValues();
556 values.put(Settings.NameValueTable.NAME, Settings.Secure.ANDROID_ID);
557 values.put(Settings.NameValueTable.VALUE, newAndroidIdValue);
Christopher Tate4dc7a682012-09-11 12:15:49 -0700558 final Uri uri = insertForUser(Settings.Secure.CONTENT_URI, values, userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800559 if (uri == null) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700560 Slog.e(TAG, "Unable to generate new ANDROID_ID for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800561 return false;
562 }
Christopher Tate4dc7a682012-09-11 12:15:49 -0700563 Slog.d(TAG, "Generated and saved new ANDROID_ID [" + newAndroidIdValue
564 + "] for user " + userHandle);
Fred Quintanac70239e2009-12-17 10:28:33 -0800565 }
566 return true;
Fred Quintanac70239e2009-12-17 10:28:33 -0800567 } finally {
568 c.close();
569 }
570 }
571
Christopher Tate06efb532012-08-24 15:29:27 -0700572 // Lazy-initialize the settings caches for non-primary users
573 private SettingsCache getOrConstructCache(int callingUser, SparseArray<SettingsCache> which) {
574 synchronized (this) {
575 getOrEstablishDatabaseLocked(callingUser); // ignore return value; we don't need it
576 return which.get(callingUser);
577 }
578 }
579
580 // Lazy initialize the database helper and caches for this user, if necessary
581 private DatabaseHelper getOrEstablishDatabaseLocked(int callingUser) {
582 long oldId = Binder.clearCallingIdentity();
583 try {
584 DatabaseHelper dbHelper = mOpenHelpers.get(callingUser);
585 if (null == dbHelper) {
586 establishDbTrackingLocked(callingUser);
587 dbHelper = mOpenHelpers.get(callingUser);
588 }
589 return dbHelper;
590 } finally {
591 Binder.restoreCallingIdentity(oldId);
592 }
593 }
594
595 public SettingsCache cacheForTable(final int callingUser, String tableName) {
596 if (TABLE_SYSTEM.equals(tableName)) {
597 return getOrConstructCache(callingUser, sSystemCaches);
598 }
599 if (TABLE_SECURE.equals(tableName)) {
600 return getOrConstructCache(callingUser, sSecureCaches);
601 }
602 if (TABLE_GLOBAL.equals(tableName)) {
603 return sGlobalCache;
604 }
605 return null;
606 }
607
608 /**
609 * Used for wiping a whole cache on deletes when we're not
610 * sure what exactly was deleted or changed.
611 */
612 public void invalidateCache(final int callingUser, String tableName) {
613 SettingsCache cache = cacheForTable(callingUser, tableName);
614 if (cache == null) {
615 return;
616 }
617 synchronized (cache) {
618 cache.evictAll();
619 cache.mCacheFullyMatchesDisk = false;
620 }
621 }
622
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800623 /**
624 * Fast path that avoids the use of chatty remoted Cursors.
625 */
626 @Override
627 public Bundle call(String method, String request, Bundle args) {
Christopher Tate06efb532012-08-24 15:29:27 -0700628 int callingUser = UserHandle.getCallingUserId();
629 if (args != null) {
630 int reqUser = args.getInt(Settings.CALL_METHOD_USER_KEY, callingUser);
631 if (reqUser != callingUser) {
Christopher Tated5fe1472012-09-10 15:48:38 -0700632 callingUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
633 Binder.getCallingUid(), reqUser, false, true,
634 "get/set setting for user", null);
635 if (LOCAL_LOGV) Slog.v(TAG, " access setting for user " + callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700636 }
637 }
638
639 // Note: we assume that get/put operations for moved-to-global names have already
640 // been directed to the new location on the caller side (otherwise we'd fix them
641 // up here).
642
643 DatabaseHelper dbHelper;
644 SettingsCache cache;
645
646 // Get methods
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800647 if (Settings.CALL_METHOD_GET_SYSTEM.equals(method)) {
Christopher Tate06efb532012-08-24 15:29:27 -0700648 if (LOCAL_LOGV) Slog.v(TAG, "call(system:" + request + ") for " + callingUser);
649 synchronized (this) {
650 dbHelper = getOrEstablishDatabaseLocked(callingUser);
651 cache = sSystemCaches.get(callingUser);
652 }
653 return lookupValue(dbHelper, TABLE_SYSTEM, cache, request);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800654 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800655 if (Settings.CALL_METHOD_GET_SECURE.equals(method)) {
Christopher Tate06efb532012-08-24 15:29:27 -0700656 if (LOCAL_LOGV) Slog.v(TAG, "call(secure:" + request + ") for " + callingUser);
657 synchronized (this) {
658 dbHelper = getOrEstablishDatabaseLocked(callingUser);
659 cache = sSecureCaches.get(callingUser);
660 }
661 return lookupValue(dbHelper, TABLE_SECURE, cache, request);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800662 }
Christopher Tate06efb532012-08-24 15:29:27 -0700663 if (Settings.CALL_METHOD_GET_GLOBAL.equals(method)) {
664 if (LOCAL_LOGV) Slog.v(TAG, "call(global:" + request + ") for " + callingUser);
665 // fast path: owner db & cache are immutable after onCreate() so we need not
666 // guard on the attempt to look them up
667 return lookupValue(getOrEstablishDatabaseLocked(UserHandle.USER_OWNER), TABLE_GLOBAL,
668 sGlobalCache, request);
669 }
670
671 // Put methods - new value is in the args bundle under the key named by
672 // the Settings.NameValueTable.VALUE static.
673 final String newValue = (args == null)
674 ? null : args.getString(Settings.NameValueTable.VALUE);
Christopher Tate06efb532012-08-24 15:29:27 -0700675
676 final ContentValues values = new ContentValues();
677 values.put(Settings.NameValueTable.NAME, request);
678 values.put(Settings.NameValueTable.VALUE, newValue);
679 if (Settings.CALL_METHOD_PUT_SYSTEM.equals(method)) {
680 if (LOCAL_LOGV) Slog.v(TAG, "call_put(system:" + request + "=" + newValue + ") for " + callingUser);
681 insert(Settings.System.CONTENT_URI, values);
682 } else if (Settings.CALL_METHOD_PUT_SECURE.equals(method)) {
683 if (LOCAL_LOGV) Slog.v(TAG, "call_put(secure:" + request + "=" + newValue + ") for " + callingUser);
684 insert(Settings.Secure.CONTENT_URI, values);
685 } else if (Settings.CALL_METHOD_PUT_GLOBAL.equals(method)) {
686 if (LOCAL_LOGV) Slog.v(TAG, "call_put(global:" + request + "=" + newValue + ") for " + callingUser);
687 insert(Settings.Global.CONTENT_URI, values);
688 } else {
689 Slog.w(TAG, "call() with invalid method: " + method);
690 }
691
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800692 return null;
693 }
694
695 // Looks up value 'key' in 'table' and returns either a single-pair Bundle,
696 // possibly with a null value, or null on failure.
Christopher Tate06efb532012-08-24 15:29:27 -0700697 private Bundle lookupValue(DatabaseHelper dbHelper, String table,
698 final SettingsCache cache, String key) {
699 if (cache == null) {
700 Slog.e(TAG, "cache is null for user " + UserHandle.getCallingUserId() + " : key=" + key);
701 return null;
702 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800703 synchronized (cache) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -0800704 Bundle value = cache.get(key);
705 if (value != null) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -0700706 if (value != TOO_LARGE_TO_CACHE_MARKER) {
707 return value;
708 }
709 // else we fall through and read the value from disk
710 } else if (cache.fullyMatchesDisk()) {
711 // Fast path (very common). Don't even try touch disk
712 // if we know we've slurped it all in. Trying to
713 // touch the disk would mean waiting for yaffs2 to
714 // give us access, which could takes hundreds of
715 // milliseconds. And we're very likely being called
716 // from somebody's UI thread...
717 return NULL_SETTING;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800718 }
719 }
720
Christopher Tate06efb532012-08-24 15:29:27 -0700721 SQLiteDatabase db = dbHelper.getReadableDatabase();
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800722 Cursor cursor = null;
723 try {
724 cursor = db.query(table, COLUMN_VALUE, "name=?", new String[]{key},
725 null, null, null, null);
726 if (cursor != null && cursor.getCount() == 1) {
727 cursor.moveToFirst();
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800728 return cache.putIfAbsent(key, cursor.getString(0));
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800729 }
730 } catch (SQLiteException e) {
731 Log.w(TAG, "settings lookup error", e);
732 return null;
733 } finally {
734 if (cursor != null) cursor.close();
735 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -0800736 cache.putIfAbsent(key, null);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800737 return NULL_SETTING;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800738 }
739
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700740 @Override
741 public Cursor query(Uri url, String[] select, String where, String[] whereArgs, String sort) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700742 return queryForUser(url, select, where, whereArgs, sort, UserHandle.getCallingUserId());
743 }
744
745 public Cursor queryForUser(Uri url, String[] select, String where, String[] whereArgs,
746 String sort, int forUser) {
747 if (LOCAL_LOGV) Slog.v(TAG, "query(" + url + ") for user " + forUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700748 SqlArguments args = new SqlArguments(url, where, whereArgs);
Christopher Tate06efb532012-08-24 15:29:27 -0700749 DatabaseHelper dbH;
750 synchronized (this) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700751 dbH = getOrEstablishDatabaseLocked(
752 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : forUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700753 }
754 SQLiteDatabase db = dbH.getReadableDatabase();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800756 // The favorites table was moved from this provider to a provider inside Home
757 // Home still need to query this table to upgrade from pre-cupcake builds
758 // However, a cupcake+ build with no data does not contain this table which will
759 // cause an exception in the SQL stack. The following line is a special case to
760 // let the caller of the query have a chance to recover and avoid the exception
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 if (TABLE_FAVORITES.equals(args.table)) {
762 return null;
763 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
764 args.table = TABLE_FAVORITES;
765 Cursor cursor = db.rawQuery("PRAGMA table_info(favorites);", null);
766 if (cursor != null) {
767 boolean exists = cursor.getCount() > 0;
768 cursor.close();
769 if (!exists) return null;
770 } else {
771 return null;
772 }
773 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800774
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700775 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
776 qb.setTables(args.table);
777
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700778 Cursor ret = qb.query(db, select, args.where, args.args, null, null, sort);
779 ret.setNotificationUri(getContext().getContentResolver(), url);
780 return ret;
781 }
782
783 @Override
784 public String getType(Uri url) {
785 // If SqlArguments supplies a where clause, then it must be an item
786 // (because we aren't supplying our own where clause).
787 SqlArguments args = new SqlArguments(url, null, null);
788 if (TextUtils.isEmpty(args.where)) {
789 return "vnd.android.cursor.dir/" + args.table;
790 } else {
791 return "vnd.android.cursor.item/" + args.table;
792 }
793 }
794
795 @Override
796 public int bulkInsert(Uri uri, ContentValues[] values) {
Christopher Tate06efb532012-08-24 15:29:27 -0700797 final int callingUser = UserHandle.getCallingUserId();
798 if (LOCAL_LOGV) Slog.v(TAG, "bulkInsert() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700799 SqlArguments args = new SqlArguments(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 if (TABLE_FAVORITES.equals(args.table)) {
801 return 0;
802 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700803 checkWritePermissions(args);
Christopher Tate06efb532012-08-24 15:29:27 -0700804 SettingsCache cache = cacheForTable(callingUser, args.table);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700805
Christopher Tate06efb532012-08-24 15:29:27 -0700806 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
807 mutationCount.incrementAndGet();
808 DatabaseHelper dbH;
809 synchronized (this) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700810 dbH = getOrEstablishDatabaseLocked(
811 TABLE_GLOBAL.equals(args.table) ? UserHandle.USER_OWNER : callingUser);
Christopher Tate06efb532012-08-24 15:29:27 -0700812 }
813 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700814 db.beginTransaction();
815 try {
816 int numValues = values.length;
817 for (int i = 0; i < numValues; i++) {
818 if (db.insert(args.table, null, values[i]) < 0) return 0;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800819 SettingsCache.populate(cache, values[i]);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700820 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + values[i]);
821 }
822 db.setTransactionSuccessful();
823 } finally {
824 db.endTransaction();
Christopher Tate06efb532012-08-24 15:29:27 -0700825 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700826 }
827
Christopher Tate06efb532012-08-24 15:29:27 -0700828 sendNotify(uri, callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700829 return values.length;
830 }
831
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700832 /*
833 * Used to parse changes to the value of Settings.Secure.LOCATION_PROVIDERS_ALLOWED.
834 * This setting contains a list of the currently enabled location providers.
835 * But helper functions in android.providers.Settings can enable or disable
836 * a single provider by using a "+" or "-" prefix before the provider name.
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800837 *
838 * @returns whether the database needs to be updated or not, also modifying
839 * 'initialValues' if needed.
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700840 */
841 private boolean parseProviderList(Uri url, ContentValues initialValues) {
842 String value = initialValues.getAsString(Settings.Secure.VALUE);
843 String newProviders = null;
844 if (value != null && value.length() > 1) {
845 char prefix = value.charAt(0);
846 if (prefix == '+' || prefix == '-') {
847 // skip prefix
848 value = value.substring(1);
849
850 // read list of enabled providers into "providers"
851 String providers = "";
852 String[] columns = {Settings.Secure.VALUE};
853 String where = Settings.Secure.NAME + "=\'" + Settings.Secure.LOCATION_PROVIDERS_ALLOWED + "\'";
854 Cursor cursor = query(url, columns, where, null, null);
855 if (cursor != null && cursor.getCount() == 1) {
856 try {
857 cursor.moveToFirst();
858 providers = cursor.getString(0);
859 } finally {
860 cursor.close();
861 }
862 }
863
864 int index = providers.indexOf(value);
865 int end = index + value.length();
866 // check for commas to avoid matching on partial string
867 if (index > 0 && providers.charAt(index - 1) != ',') index = -1;
868 if (end < providers.length() && providers.charAt(end) != ',') index = -1;
869
870 if (prefix == '+' && index < 0) {
871 // append the provider to the list if not present
872 if (providers.length() == 0) {
873 newProviders = value;
874 } else {
875 newProviders = providers + ',' + value;
876 }
877 } else if (prefix == '-' && index >= 0) {
878 // remove the provider from the list if present
Mike Lockwoodbdc7f892010-04-21 18:24:57 -0400879 // remove leading or trailing comma
880 if (index > 0) {
881 index--;
882 } else if (end < providers.length()) {
883 end++;
884 }
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700885
886 newProviders = providers.substring(0, index);
887 if (end < providers.length()) {
888 newProviders += providers.substring(end);
889 }
890 } else {
891 // nothing changed, so no need to update the database
892 return false;
893 }
894
895 if (newProviders != null) {
896 initialValues.put(Settings.Secure.VALUE, newProviders);
897 }
898 }
899 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800900
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700901 return true;
902 }
903
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700904 @Override
905 public Uri insert(Uri url, ContentValues initialValues) {
Christopher Tate06efb532012-08-24 15:29:27 -0700906 return insertForUser(url, initialValues, UserHandle.getCallingUserId());
907 }
908
909 // Settings.put*ForUser() always winds up here, so this is where we apply
910 // policy around permission to write settings for other users.
911 private Uri insertForUser(Uri url, ContentValues initialValues, int desiredUserHandle) {
912 final int callingUser = UserHandle.getCallingUserId();
913 if (callingUser != desiredUserHandle) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700914 getContext().enforceCallingOrSelfPermission(
Christopher Tate06efb532012-08-24 15:29:27 -0700915 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
916 "Not permitted to access settings for other users");
917 }
918
919 if (LOCAL_LOGV) Slog.v(TAG, "insert(" + url + ") for user " + desiredUserHandle
920 + " by " + callingUser);
921
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700922 SqlArguments args = new SqlArguments(url);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 if (TABLE_FAVORITES.equals(args.table)) {
924 return null;
925 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700926 checkWritePermissions(args);
927
Mike Lockwoodbd2a7122009-04-02 23:41:33 -0700928 // Special case LOCATION_PROVIDERS_ALLOWED.
929 // Support enabling/disabling a single provider (using "+" or "-" prefix)
930 String name = initialValues.getAsString(Settings.Secure.NAME);
931 if (Settings.Secure.LOCATION_PROVIDERS_ALLOWED.equals(name)) {
932 if (!parseProviderList(url, initialValues)) return null;
933 }
934
Christopher Tate06efb532012-08-24 15:29:27 -0700935 // The global table is stored under the owner, always
936 if (TABLE_GLOBAL.equals(args.table)) {
937 desiredUserHandle = UserHandle.USER_OWNER;
938 }
939
940 SettingsCache cache = cacheForTable(desiredUserHandle, args.table);
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -0800941 String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
942 if (SettingsCache.isRedundantSetValue(cache, name, value)) {
943 return Uri.withAppendedPath(url, name);
944 }
945
Christopher Tate06efb532012-08-24 15:29:27 -0700946 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(desiredUserHandle);
947 mutationCount.incrementAndGet();
948 DatabaseHelper dbH;
949 synchronized (this) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700950 dbH = getOrEstablishDatabaseLocked(desiredUserHandle);
Christopher Tate06efb532012-08-24 15:29:27 -0700951 }
952 SQLiteDatabase db = dbH.getWritableDatabase();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700953 final long rowId = db.insert(args.table, null, initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700954 mutationCount.decrementAndGet();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700955 if (rowId <= 0) return null;
956
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800957 SettingsCache.populate(cache, initialValues); // before we notify
958
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700959 if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues);
Christopher Tate06efb532012-08-24 15:29:27 -0700960 // Note that we use the original url here, not the potentially-rewritten table name
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700961 url = getUriFor(url, initialValues, rowId);
Christopher Tate06efb532012-08-24 15:29:27 -0700962 sendNotify(url, desiredUserHandle);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700963 return url;
964 }
965
966 @Override
967 public int delete(Uri url, String where, String[] whereArgs) {
Christopher Tate4dc7a682012-09-11 12:15:49 -0700968 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -0700969 if (LOCAL_LOGV) Slog.v(TAG, "delete() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700970 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 if (TABLE_FAVORITES.equals(args.table)) {
972 return 0;
973 } else if (TABLE_OLD_FAVORITES.equals(args.table)) {
974 args.table = TABLE_FAVORITES;
Christopher Tate4dc7a682012-09-11 12:15:49 -0700975 } else if (TABLE_GLOBAL.equals(args.table)) {
976 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700978 checkWritePermissions(args);
979
Christopher Tate06efb532012-08-24 15:29:27 -0700980 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
981 mutationCount.incrementAndGet();
982 DatabaseHelper dbH;
983 synchronized (this) {
984 dbH = getOrEstablishDatabaseLocked(callingUser);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -0800985 }
Christopher Tate06efb532012-08-24 15:29:27 -0700986 SQLiteDatabase db = dbH.getWritableDatabase();
987 int count = db.delete(args.table, args.where, args.args);
988 mutationCount.decrementAndGet();
989 if (count > 0) {
990 invalidateCache(callingUser, args.table); // before we notify
991 sendNotify(url, callingUser);
992 }
993 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700994 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) deleted");
995 return count;
996 }
997
998 @Override
999 public int update(Uri url, ContentValues initialValues, String where, String[] whereArgs) {
Christopher Tate06efb532012-08-24 15:29:27 -07001000 // NOTE: update() is never called by the front-end Settings API, and updates that
1001 // wind up affecting rows in Secure that are globally shared will not have the
1002 // intended effect (the update will be invisible to the rest of the system).
1003 // This should have no practical effect, since writes to the Secure db can only
1004 // be done by system code, and that code should be using the correct API up front.
Christopher Tate4dc7a682012-09-11 12:15:49 -07001005 int callingUser = UserHandle.getCallingUserId();
Christopher Tate06efb532012-08-24 15:29:27 -07001006 if (LOCAL_LOGV) Slog.v(TAG, "update() for user " + callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001007 SqlArguments args = new SqlArguments(url, where, whereArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 if (TABLE_FAVORITES.equals(args.table)) {
1009 return 0;
Christopher Tate4dc7a682012-09-11 12:15:49 -07001010 } else if (TABLE_GLOBAL.equals(args.table)) {
1011 callingUser = UserHandle.USER_OWNER;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001013 checkWritePermissions(args);
1014
Christopher Tate06efb532012-08-24 15:29:27 -07001015 final AtomicInteger mutationCount = sKnownMutationsInFlight.get(callingUser);
1016 mutationCount.incrementAndGet();
1017 DatabaseHelper dbH;
1018 synchronized (this) {
1019 dbH = getOrEstablishDatabaseLocked(callingUser);
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001020 }
Christopher Tate06efb532012-08-24 15:29:27 -07001021 SQLiteDatabase db = dbH.getWritableDatabase();
1022 int count = db.update(args.table, initialValues, args.where, args.args);
1023 mutationCount.decrementAndGet();
1024 if (count > 0) {
1025 invalidateCache(callingUser, args.table); // before we notify
1026 sendNotify(url, callingUser);
1027 }
1028 startAsyncCachePopulation(callingUser);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001029 if (LOCAL_LOGV) Log.v(TAG, args.table + ": " + count + " row(s) <- " + initialValues);
1030 return count;
1031 }
1032
1033 @Override
1034 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
1035
1036 /*
1037 * When a client attempts to openFile the default ringtone or
1038 * notification setting Uri, we will proxy the call to the current
1039 * default ringtone's Uri (if it is in the DRM or media provider).
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001040 */
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001041 int ringtoneType = RingtoneManager.getDefaultType(uri);
1042 // Above call returns -1 if the Uri doesn't match a default type
1043 if (ringtoneType != -1) {
1044 Context context = getContext();
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001045
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001046 // Get the current value for the default sound
1047 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001048
Marco Nelissen69f593c2009-07-28 09:55:04 -07001049 if (soundUri != null) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001050 // Only proxy the openFile call to drm or media providers
1051 String authority = soundUri.getAuthority();
1052 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1053 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1054
1055 if (isDrmAuthority) {
1056 try {
1057 // Check DRM access permission here, since once we
1058 // do the below call the DRM will be checking our
1059 // permission, not our caller's permission
1060 DrmStore.enforceAccessDrmPermission(context);
1061 } catch (SecurityException e) {
1062 throw new FileNotFoundException(e.getMessage());
1063 }
1064 }
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001065
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001066 return context.getContentResolver().openFileDescriptor(soundUri, mode);
1067 }
1068 }
1069 }
1070
1071 return super.openFile(uri, mode);
1072 }
Marco Nelissen69f593c2009-07-28 09:55:04 -07001073
1074 @Override
1075 public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
1076
1077 /*
1078 * When a client attempts to openFile the default ringtone or
1079 * notification setting Uri, we will proxy the call to the current
1080 * default ringtone's Uri (if it is in the DRM or media provider).
1081 */
1082 int ringtoneType = RingtoneManager.getDefaultType(uri);
1083 // Above call returns -1 if the Uri doesn't match a default type
1084 if (ringtoneType != -1) {
1085 Context context = getContext();
1086
1087 // Get the current value for the default sound
1088 Uri soundUri = RingtoneManager.getActualDefaultRingtoneUri(context, ringtoneType);
1089
1090 if (soundUri != null) {
1091 // Only proxy the openFile call to drm or media providers
1092 String authority = soundUri.getAuthority();
1093 boolean isDrmAuthority = authority.equals(DrmStore.AUTHORITY);
1094 if (isDrmAuthority || authority.equals(MediaStore.AUTHORITY)) {
1095
1096 if (isDrmAuthority) {
1097 try {
1098 // Check DRM access permission here, since once we
1099 // do the below call the DRM will be checking our
1100 // permission, not our caller's permission
1101 DrmStore.enforceAccessDrmPermission(context);
1102 } catch (SecurityException e) {
1103 throw new FileNotFoundException(e.getMessage());
1104 }
1105 }
1106
1107 ParcelFileDescriptor pfd = null;
1108 try {
1109 pfd = context.getContentResolver().openFileDescriptor(soundUri, mode);
1110 return new AssetFileDescriptor(pfd, 0, -1);
1111 } catch (FileNotFoundException ex) {
1112 // fall through and open the fallback ringtone below
1113 }
1114 }
1115
1116 try {
1117 return super.openAssetFile(soundUri, mode);
1118 } catch (FileNotFoundException ex) {
1119 // Since a non-null Uri was specified, but couldn't be opened,
1120 // fall back to the built-in ringtone.
1121 return context.getResources().openRawResourceFd(
1122 com.android.internal.R.raw.fallbackring);
1123 }
1124 }
1125 // no need to fall through and have openFile() try again, since we
1126 // already know that will fail.
1127 throw new FileNotFoundException(); // or return null ?
1128 }
1129
1130 // Note that this will end up calling openFile() above.
1131 return super.openAssetFile(uri, mode);
1132 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001133
1134 /**
1135 * In-memory LRU Cache of system and secure settings, along with
1136 * associated helper functions to keep cache coherent with the
1137 * database.
1138 */
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001139 private static final class SettingsCache extends LruCache<String, Bundle> {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001140
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001141 private final String mCacheName;
1142 private boolean mCacheFullyMatchesDisk = false; // has the whole database slurped.
1143
1144 public SettingsCache(String name) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001145 super(MAX_CACHE_ENTRIES);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001146 mCacheName = name;
1147 }
1148
1149 /**
1150 * Is the whole database table slurped into this cache?
1151 */
1152 public boolean fullyMatchesDisk() {
1153 synchronized (this) {
1154 return mCacheFullyMatchesDisk;
1155 }
1156 }
1157
1158 public void setFullyMatchesDisk(boolean value) {
1159 synchronized (this) {
1160 mCacheFullyMatchesDisk = value;
1161 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001162 }
1163
1164 @Override
Jesse Wilson32c80a22011-02-25 17:28:41 -08001165 protected void entryRemoved(boolean evicted, String key, Bundle oldValue, Bundle newValue) {
1166 if (evicted) {
1167 mCacheFullyMatchesDisk = false;
1168 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001169 }
1170
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001171 /**
1172 * Atomic cache population, conditional on size of value and if
1173 * we lost a race.
1174 *
1175 * @returns a Bundle to send back to the client from call(), even
1176 * if we lost the race.
1177 */
1178 public Bundle putIfAbsent(String key, String value) {
1179 Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
1180 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
1181 synchronized (this) {
Jesse Wilson0c7faee2011-02-10 11:33:19 -08001182 if (get(key) == null) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001183 put(key, bundle);
1184 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001185 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001186 }
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001187 return bundle;
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001188 }
1189
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001190 /**
1191 * Populates a key in a given (possibly-null) cache.
1192 */
1193 public static void populate(SettingsCache cache, ContentValues contentValues) {
1194 if (cache == null) {
1195 return;
1196 }
1197 String name = contentValues.getAsString(Settings.NameValueTable.NAME);
1198 if (name == null) {
1199 Log.w(TAG, "null name populating settings cache.");
1200 return;
1201 }
1202 String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001203 cache.populate(name, value);
1204 }
1205
1206 public void populate(String name, String value) {
1207 synchronized (this) {
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001208 if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001209 put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001210 } else {
Brad Fitzpatrickf366a9b2010-08-24 16:14:07 -07001211 put(name, TOO_LARGE_TO_CACHE_MARKER);
Brad Fitzpatrick342984a2010-03-09 16:59:30 -08001212 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001213 }
1214 }
1215
1216 /**
Brad Fitzpatrick547a96b2010-03-09 17:58:53 -08001217 * For suppressing duplicate/redundant settings inserts early,
1218 * checking our cache first (but without faulting it in),
1219 * before going to sqlite with the mutation.
1220 */
1221 public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
1222 if (cache == null) return false;
1223 synchronized (cache) {
1224 Bundle bundle = cache.get(name);
1225 if (bundle == null) return false;
1226 String oldValue = bundle.getPairValue();
1227 if (oldValue == null && value == null) return true;
1228 if ((oldValue == null) != (value == null)) return false;
1229 return oldValue.equals(value);
1230 }
1231 }
Brad Fitzpatrick1bd62bd2010-03-08 18:30:52 -08001232 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001233}