1 /*
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 
17 package com.android.providers.settings;
18 
19 import android.content.ComponentName;
20 import android.content.ContentValues;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.pm.ActivityInfo;
24 import android.content.pm.IPackageManager;
25 import android.content.pm.PackageManager;
26 import android.content.res.Resources;
27 import android.content.res.XmlResourceParser;
28 import android.database.Cursor;
29 import android.database.sqlite.SQLiteDatabase;
30 import android.database.sqlite.SQLiteOpenHelper;
31 import android.database.sqlite.SQLiteStatement;
32 import android.media.AudioManager;
33 import android.media.AudioSystem;
34 import android.net.ConnectivityManager;
35 import android.os.Build;
36 import android.os.Environment;
37 import android.os.RemoteException;
38 import android.os.ServiceManager;
39 import android.os.SystemProperties;
40 import android.os.UserHandle;
41 import android.provider.Settings;
42 import android.provider.Settings.Global;
43 import android.provider.Settings.Secure;
44 import android.sysprop.TelephonyProperties;
45 import android.telephony.TelephonyManager;
46 import android.text.TextUtils;
47 import android.util.Log;
48 
49 import com.android.internal.content.PackageHelper;
50 import com.android.internal.telephony.Phone;
51 import com.android.internal.telephony.RILConstants;
52 import com.android.internal.util.XmlUtils;
53 import com.android.internal.widget.LockPatternUtils;
54 import com.android.internal.widget.LockPatternView;
55 import com.android.internal.widget.LockscreenCredential;
56 
57 import org.xmlpull.v1.XmlPullParser;
58 import org.xmlpull.v1.XmlPullParserException;
59 
60 import java.io.File;
61 import java.io.IOException;
62 import java.util.HashSet;
63 import java.util.List;
64 import java.util.Set;
65 
66 /**
67  * Legacy settings database helper class for {@link SettingsProvider}.
68  *
69  * IMPORTANT: Do not add any more upgrade steps here as the global,
70  * secure, and system settings are no longer stored in a database
71  * but are kept in memory and persisted to XML.
72  *
73  * See: SettingsProvider.UpgradeController#onUpgradeLocked
74  *
75  * @deprecated The implementation is frozen.  Do not add any new code to this class!
76  */
77 @Deprecated
78 class DatabaseHelper extends SQLiteOpenHelper {
79     private static final String TAG = "SettingsProvider";
80     private static final String DATABASE_NAME = "settings.db";
81 
82     // Please, please please. If you update the database version, check to make sure the
83     // database gets upgraded properly. At a minimum, please confirm that 'upgradeVersion'
84     // is properly propagated through your change.  Not doing so will result in a loss of user
85     // settings.
86     private static final int DATABASE_VERSION = 118;
87 
88     private Context mContext;
89     private int mUserHandle;
90 
91     private static final HashSet<String> mValidTables = new HashSet<String>();
92 
93     private static final String DATABASE_BACKUP_SUFFIX = "-backup";
94 
95     private static final String TABLE_SYSTEM = "system";
96     private static final String TABLE_SECURE = "secure";
97     private static final String TABLE_GLOBAL = "global";
98 
99     static {
100         mValidTables.add(TABLE_SYSTEM);
101         mValidTables.add(TABLE_SECURE);
102         mValidTables.add(TABLE_GLOBAL);
103 
104         // These are old.
105         mValidTables.add("bluetooth_devices");
106         mValidTables.add("bookmarks");
107         mValidTables.add("favorites");
108         mValidTables.add("old_favorites");
109         mValidTables.add("android_metadata");
110     }
111 
dbNameForUser(final int userHandle)112     static String dbNameForUser(final int userHandle) {
113         // The owner gets the unadorned db name;
114         if (userHandle == UserHandle.USER_SYSTEM) {
115             return DATABASE_NAME;
116         } else {
117             // Place the database in the user-specific data tree so that it's
118             // cleaned up automatically when the user is deleted.
119             File databaseFile = new File(
120                     Environment.getUserSystemDirectory(userHandle), DATABASE_NAME);
121             // If databaseFile doesn't exist, database can be kept in memory. It's safe because the
122             // database will be migrated and disposed of immediately after onCreate finishes
123             if (!databaseFile.exists()) {
124                 Log.i(TAG, "No previous database file exists - running in in-memory mode");
125                 return null;
126             }
127             return databaseFile.getPath();
128         }
129     }
130 
DatabaseHelper(Context context, int userHandle)131     public DatabaseHelper(Context context, int userHandle) {
132         super(context, dbNameForUser(userHandle), null, DATABASE_VERSION);
133         mContext = context;
134         mUserHandle = userHandle;
135     }
136 
isValidTable(String name)137     public static boolean isValidTable(String name) {
138         return mValidTables.contains(name);
139     }
140 
isInMemory()141     private boolean isInMemory() {
142         return getDatabaseName() == null;
143     }
144 
dropDatabase()145     public void dropDatabase() {
146         close();
147         // No need to remove files if db is in memory
148         if (isInMemory()) {
149             return;
150         }
151         File databaseFile = mContext.getDatabasePath(getDatabaseName());
152         if (databaseFile.exists()) {
153             SQLiteDatabase.deleteDatabase(databaseFile);
154         }
155     }
156 
backupDatabase()157     public void backupDatabase() {
158         close();
159         // No need to backup files if db is in memory
160         if (isInMemory()) {
161             return;
162         }
163         File databaseFile = mContext.getDatabasePath(getDatabaseName());
164         if (!databaseFile.exists()) {
165             return;
166         }
167         File backupFile = mContext.getDatabasePath(getDatabaseName()
168                 + DATABASE_BACKUP_SUFFIX);
169         if (backupFile.exists()) {
170             return;
171         }
172         databaseFile.renameTo(backupFile);
173     }
174 
createSecureTable(SQLiteDatabase db)175     private void createSecureTable(SQLiteDatabase db) {
176         db.execSQL("CREATE TABLE secure (" +
177                 "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
178                 "name TEXT UNIQUE ON CONFLICT REPLACE," +
179                 "value TEXT" +
180                 ");");
181         db.execSQL("CREATE INDEX secureIndex1 ON secure (name);");
182     }
183 
createGlobalTable(SQLiteDatabase db)184     private void createGlobalTable(SQLiteDatabase db) {
185         db.execSQL("CREATE TABLE global (" +
186                 "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
187                 "name TEXT UNIQUE ON CONFLICT REPLACE," +
188                 "value TEXT" +
189                 ");");
190         db.execSQL("CREATE INDEX globalIndex1 ON global (name);");
191     }
192 
193     @Override
onCreate(SQLiteDatabase db)194     public void onCreate(SQLiteDatabase db) {
195         db.execSQL("CREATE TABLE system (" +
196                     "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
197                     "name TEXT UNIQUE ON CONFLICT REPLACE," +
198                     "value TEXT" +
199                     ");");
200         db.execSQL("CREATE INDEX systemIndex1 ON system (name);");
201 
202         createSecureTable(db);
203 
204         // Only create the global table for the singleton 'owner/system' user
205         if (mUserHandle == UserHandle.USER_SYSTEM) {
206             createGlobalTable(db);
207         }
208 
209         db.execSQL("CREATE TABLE bluetooth_devices (" +
210                     "_id INTEGER PRIMARY KEY," +
211                     "name TEXT," +
212                     "addr TEXT," +
213                     "channel INTEGER," +
214                     "type INTEGER" +
215                     ");");
216 
217         db.execSQL("CREATE TABLE bookmarks (" +
218                     "_id INTEGER PRIMARY KEY," +
219                     "title TEXT," +
220                     "folder TEXT," +
221                     "intent TEXT," +
222                     "shortcut INTEGER," +
223                     "ordering INTEGER" +
224                     ");");
225 
226         db.execSQL("CREATE INDEX bookmarksIndex1 ON bookmarks (folder);");
227         db.execSQL("CREATE INDEX bookmarksIndex2 ON bookmarks (shortcut);");
228 
229         // Populate bookmarks table with initial bookmarks
230         boolean onlyCore = false;
231         try {
232             onlyCore = IPackageManager.Stub.asInterface(ServiceManager.getService(
233                     "package")).isOnlyCoreApps();
234         } catch (RemoteException e) {
235         }
236         if (!onlyCore) {
237             loadBookmarks(db);
238         }
239 
240         // Load initial volume levels into DB
241         loadVolumeLevels(db);
242 
243         // Load inital settings values
244         loadSettings(db);
245     }
246 
247     @Override
onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion)248     public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
249         Log.w(TAG, "Upgrading settings database from version " + oldVersion + " to "
250                 + currentVersion);
251 
252         int upgradeVersion = oldVersion;
253 
254         // Pattern for upgrade blocks:
255         //
256         //    if (upgradeVersion == [the DATABASE_VERSION you set] - 1) {
257         //        .. your upgrade logic..
258         //        upgradeVersion = [the DATABASE_VERSION you set]
259         //    }
260 
261         if (upgradeVersion == 20) {
262             /*
263              * Version 21 is part of the volume control refresh. There is no
264              * longer a UI-visible for setting notification vibrate on/off (in
265              * our design), but the functionality still exists. Force the
266              * notification vibrate to on.
267              */
268             loadVibrateSetting(db, true);
269 
270             upgradeVersion = 21;
271         }
272 
273         if (upgradeVersion < 22) {
274             upgradeVersion = 22;
275             // Upgrade the lock gesture storage location and format
276             upgradeLockPatternLocation(db);
277         }
278 
279         if (upgradeVersion < 23) {
280             db.execSQL("UPDATE favorites SET iconResource=0 WHERE iconType=0");
281             upgradeVersion = 23;
282         }
283 
284         if (upgradeVersion == 23) {
285             db.beginTransaction();
286             try {
287                 db.execSQL("ALTER TABLE favorites ADD spanX INTEGER");
288                 db.execSQL("ALTER TABLE favorites ADD spanY INTEGER");
289                 // Shortcuts, applications, folders
290                 db.execSQL("UPDATE favorites SET spanX=1, spanY=1 WHERE itemType<=0");
291                 // Photo frames, clocks
292                 db.execSQL(
293                     "UPDATE favorites SET spanX=2, spanY=2 WHERE itemType=1000 or itemType=1002");
294                 // Search boxes
295                 db.execSQL("UPDATE favorites SET spanX=4, spanY=1 WHERE itemType=1001");
296                 db.setTransactionSuccessful();
297             } finally {
298                 db.endTransaction();
299             }
300             upgradeVersion = 24;
301         }
302 
303         if (upgradeVersion == 24) {
304             db.beginTransaction();
305             try {
306                 // The value of the constants for preferring wifi or preferring mobile have been
307                 // swapped, so reload the default.
308                 db.execSQL("DELETE FROM system WHERE name='network_preference'");
309                 db.execSQL("INSERT INTO system ('name', 'value') values ('network_preference', '" +
310                         ConnectivityManager.DEFAULT_NETWORK_PREFERENCE + "')");
311                 db.setTransactionSuccessful();
312             } finally {
313                 db.endTransaction();
314             }
315             upgradeVersion = 25;
316         }
317 
318         if (upgradeVersion == 25) {
319             db.beginTransaction();
320             try {
321                 db.execSQL("ALTER TABLE favorites ADD uri TEXT");
322                 db.execSQL("ALTER TABLE favorites ADD displayMode INTEGER");
323                 db.setTransactionSuccessful();
324             } finally {
325                 db.endTransaction();
326             }
327             upgradeVersion = 26;
328         }
329 
330         if (upgradeVersion == 26) {
331             // This introduces the new secure settings table.
332             db.beginTransaction();
333             try {
334                 createSecureTable(db);
335                 db.setTransactionSuccessful();
336             } finally {
337                 db.endTransaction();
338             }
339             upgradeVersion = 27;
340         }
341 
342         if (upgradeVersion == 27) {
343             String[] settingsToMove = {
344                     Settings.Secure.ADB_ENABLED,
345                     Settings.Secure.ANDROID_ID,
346                     Settings.Secure.BLUETOOTH_ON,
347                     Settings.Secure.DATA_ROAMING,
348                     Settings.Secure.DEVICE_PROVISIONED,
349                     Settings.Secure.HTTP_PROXY,
350                     Settings.Secure.INSTALL_NON_MARKET_APPS,
351                     Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
352                     Settings.Secure.LOGGING_ID,
353                     Settings.Secure.NETWORK_PREFERENCE,
354                     Settings.Secure.PARENTAL_CONTROL_ENABLED,
355                     Settings.Secure.PARENTAL_CONTROL_LAST_UPDATE,
356                     Settings.Secure.PARENTAL_CONTROL_REDIRECT_URL,
357                     Settings.Secure.SETTINGS_CLASSNAME,
358                     Settings.Secure.USB_MASS_STORAGE_ENABLED,
359                     Settings.Secure.USE_GOOGLE_MAIL,
360                     Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
361                     Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY,
362                     Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT,
363                     Settings.Secure.WIFI_ON,
364                     Settings.Secure.WIFI_WATCHDOG_ACCEPTABLE_PACKET_LOSS_PERCENTAGE,
365                     Settings.Secure.WIFI_WATCHDOG_AP_COUNT,
366                     Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_DELAY_MS,
367                     Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_ENABLED,
368                     Settings.Secure.WIFI_WATCHDOG_BACKGROUND_CHECK_TIMEOUT_MS,
369                     Settings.Secure.WIFI_WATCHDOG_INITIAL_IGNORED_PING_COUNT,
370                     Settings.Secure.WIFI_WATCHDOG_MAX_AP_CHECKS,
371                     Settings.Secure.WIFI_WATCHDOG_ON,
372                     Settings.Secure.WIFI_WATCHDOG_PING_COUNT,
373                     Settings.Secure.WIFI_WATCHDOG_PING_DELAY_MS,
374                     Settings.Secure.WIFI_WATCHDOG_PING_TIMEOUT_MS,
375                 };
376             moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_SECURE, settingsToMove, false);
377             upgradeVersion = 28;
378         }
379 
380         if (upgradeVersion == 28 || upgradeVersion == 29) {
381             // Note: The upgrade to 28 was flawed since it didn't delete the old
382             // setting first before inserting. Combining 28 and 29 with the
383             // fixed version.
384 
385             // This upgrade adds the STREAM_NOTIFICATION type to the list of
386             // types affected by ringer modes (silent, vibrate, etc.)
387             db.beginTransaction();
388             try {
389                 db.execSQL("DELETE FROM system WHERE name='"
390                         + Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
391                 int newValue = (1 << AudioManager.STREAM_RING)
392                         | (1 << AudioManager.STREAM_NOTIFICATION)
393                         | (1 << AudioManager.STREAM_SYSTEM);
394                 db.execSQL("INSERT INTO system ('name', 'value') values ('"
395                         + Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
396                         + String.valueOf(newValue) + "')");
397                 db.setTransactionSuccessful();
398             } finally {
399                 db.endTransaction();
400             }
401 
402             upgradeVersion = 30;
403         }
404 
405         if (upgradeVersion == 30) {
406             /*
407              * Upgrade 31 clears the title for all quick launch shortcuts so the
408              * activities' titles will be resolved at display time. Also, the
409              * folder is changed to '@quicklaunch'.
410              */
411             db.beginTransaction();
412             try {
413                 db.execSQL("UPDATE bookmarks SET folder = '@quicklaunch'");
414                 db.execSQL("UPDATE bookmarks SET title = ''");
415                 db.setTransactionSuccessful();
416             } finally {
417                 db.endTransaction();
418             }
419             upgradeVersion = 31;
420         }
421 
422         if (upgradeVersion == 31) {
423             /*
424              * Animations are now managed in preferences, and may be
425              * enabled or disabled based on product resources.
426              */
427             db.beginTransaction();
428             SQLiteStatement stmt = null;
429             try {
430                 db.execSQL("DELETE FROM system WHERE name='"
431                         + Settings.System.WINDOW_ANIMATION_SCALE + "'");
432                 db.execSQL("DELETE FROM system WHERE name='"
433                         + Settings.System.TRANSITION_ANIMATION_SCALE + "'");
434                 stmt = db.compileStatement("INSERT INTO system(name,value)"
435                         + " VALUES(?,?);");
436                 loadDefaultAnimationSettings(stmt);
437                 db.setTransactionSuccessful();
438             } finally {
439                 db.endTransaction();
440                 if (stmt != null) stmt.close();
441             }
442             upgradeVersion = 32;
443         }
444 
445         if (upgradeVersion == 32) {
446             upgradeVersion = 33;
447         }
448 
449         if (upgradeVersion == 33) {
450             // Set the default zoom controls to: tap-twice to bring up +/-
451             db.beginTransaction();
452             try {
453                 db.execSQL("INSERT INTO system(name,value) values('zoom','2');");
454                 db.setTransactionSuccessful();
455             } finally {
456                 db.endTransaction();
457             }
458             upgradeVersion = 34;
459         }
460 
461         if (upgradeVersion == 34) {
462             db.beginTransaction();
463             SQLiteStatement stmt = null;
464             try {
465                 stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
466                         + " VALUES(?,?);");
467                 loadSecure35Settings(stmt);
468                 db.setTransactionSuccessful();
469             } finally {
470                 db.endTransaction();
471                 if (stmt != null) stmt.close();
472             }
473             upgradeVersion = 35;
474         }
475             // due to a botched merge from donut to eclair, the initialization of ASSISTED_GPS_ENABLED
476             // was accidentally done out of order here.
477             // to fix this, ASSISTED_GPS_ENABLED is now initialized while upgrading from 38 to 39,
478             // and we intentionally do nothing from 35 to 36 now.
479         if (upgradeVersion == 35) {
480             upgradeVersion = 36;
481         }
482 
483         if (upgradeVersion == 36) {
484            // This upgrade adds the STREAM_SYSTEM_ENFORCED type to the list of
485             // types affected by ringer modes (silent, vibrate, etc.)
486             db.beginTransaction();
487             try {
488                 db.execSQL("DELETE FROM system WHERE name='"
489                         + Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
490                 int newValue = (1 << AudioManager.STREAM_RING)
491                         | (1 << AudioManager.STREAM_NOTIFICATION)
492                         | (1 << AudioManager.STREAM_SYSTEM)
493                         | (1 << AudioManager.STREAM_SYSTEM_ENFORCED);
494                 db.execSQL("INSERT INTO system ('name', 'value') values ('"
495                         + Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
496                         + String.valueOf(newValue) + "')");
497                 db.setTransactionSuccessful();
498             } finally {
499                 db.endTransaction();
500             }
501             upgradeVersion = 37;
502         }
503 
504         if (upgradeVersion == 37) {
505             db.beginTransaction();
506             SQLiteStatement stmt = null;
507             try {
508                 stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
509                         + " VALUES(?,?);");
510                 loadStringSetting(stmt, Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS,
511                         R.string.airplane_mode_toggleable_radios);
512                 db.setTransactionSuccessful();
513             } finally {
514                 db.endTransaction();
515                 if (stmt != null) stmt.close();
516             }
517             upgradeVersion = 38;
518         }
519 
520         if (upgradeVersion == 38) {
521             db.beginTransaction();
522             try {
523                 String value =
524                         mContext.getResources().getBoolean(R.bool.assisted_gps_enabled) ? "1" : "0";
525                 db.execSQL("INSERT OR IGNORE INTO secure(name,value) values('" +
526                         Settings.Global.ASSISTED_GPS_ENABLED + "','" + value + "');");
527                 db.setTransactionSuccessful();
528             } finally {
529                 db.endTransaction();
530             }
531 
532             upgradeVersion = 39;
533         }
534 
535         if (upgradeVersion == 39) {
536             upgradeAutoBrightness(db);
537             upgradeVersion = 40;
538         }
539 
540         if (upgradeVersion == 40) {
541             /*
542              * All animations are now turned on by default!
543              */
544             db.beginTransaction();
545             SQLiteStatement stmt = null;
546             try {
547                 db.execSQL("DELETE FROM system WHERE name='"
548                         + Settings.System.WINDOW_ANIMATION_SCALE + "'");
549                 db.execSQL("DELETE FROM system WHERE name='"
550                         + Settings.System.TRANSITION_ANIMATION_SCALE + "'");
551                 stmt = db.compileStatement("INSERT INTO system(name,value)"
552                         + " VALUES(?,?);");
553                 loadDefaultAnimationSettings(stmt);
554                 db.setTransactionSuccessful();
555             } finally {
556                 db.endTransaction();
557                 if (stmt != null) stmt.close();
558             }
559             upgradeVersion = 41;
560         }
561 
562         if (upgradeVersion == 41) {
563             /*
564              * Initialize newly public haptic feedback setting
565              */
566             db.beginTransaction();
567             SQLiteStatement stmt = null;
568             try {
569                 db.execSQL("DELETE FROM system WHERE name='"
570                         + Settings.System.HAPTIC_FEEDBACK_ENABLED + "'");
571                 stmt = db.compileStatement("INSERT INTO system(name,value)"
572                         + " VALUES(?,?);");
573                 loadDefaultHapticSettings(stmt);
574                 db.setTransactionSuccessful();
575             } finally {
576                 db.endTransaction();
577                 if (stmt != null) stmt.close();
578             }
579             upgradeVersion = 42;
580         }
581 
582         if (upgradeVersion == 42) {
583             /*
584              * Initialize new notification pulse setting
585              */
586             db.beginTransaction();
587             SQLiteStatement stmt = null;
588             try {
589                 stmt = db.compileStatement("INSERT INTO system(name,value)"
590                         + " VALUES(?,?);");
591                 loadBooleanSetting(stmt, Settings.System.NOTIFICATION_LIGHT_PULSE,
592                         R.bool.def_notification_pulse);
593                 db.setTransactionSuccessful();
594             } finally {
595                 db.endTransaction();
596                 if (stmt != null) stmt.close();
597             }
598             upgradeVersion = 43;
599         }
600 
601         if (upgradeVersion == 43) {
602             /*
603              * This upgrade stores bluetooth volume separately from voice volume
604              */
605             db.beginTransaction();
606             SQLiteStatement stmt = null;
607             try {
608                 stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
609                         + " VALUES(?,?);");
610                 loadSetting(stmt, Settings.System.VOLUME_BLUETOOTH_SCO,
611                         AudioSystem.getDefaultStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO));
612                 db.setTransactionSuccessful();
613             } finally {
614                 db.endTransaction();
615                 if (stmt != null) stmt.close();
616             }
617             upgradeVersion = 44;
618         }
619 
620         if (upgradeVersion == 44) {
621             /*
622              * Gservices was moved into vendor/google.
623              */
624             db.execSQL("DROP TABLE IF EXISTS gservices");
625             db.execSQL("DROP INDEX IF EXISTS gservicesIndex1");
626             upgradeVersion = 45;
627         }
628 
629         if (upgradeVersion == 45) {
630              /*
631               * New settings for StorageManagerService
632               */
633             db.beginTransaction();
634             try {
635                 db.execSQL("INSERT INTO secure(name,value) values('" +
636                         Settings.Secure.MOUNT_PLAY_NOTIFICATION_SND + "','1');");
637                 db.execSQL("INSERT INTO secure(name,value) values('" +
638                         Settings.Secure.MOUNT_UMS_AUTOSTART + "','0');");
639                 db.execSQL("INSERT INTO secure(name,value) values('" +
640                         Settings.Secure.MOUNT_UMS_PROMPT + "','1');");
641                 db.execSQL("INSERT INTO secure(name,value) values('" +
642                         Settings.Secure.MOUNT_UMS_NOTIFY_ENABLED + "','1');");
643                 db.setTransactionSuccessful();
644             } finally {
645                 db.endTransaction();
646             }
647             upgradeVersion = 46;
648         }
649 
650         if (upgradeVersion == 46) {
651             /*
652              * The password mode constants have changed; reset back to no
653              * password.
654              */
655             db.beginTransaction();
656             try {
657                 db.execSQL("DELETE FROM system WHERE name='lockscreen.password_type';");
658                 db.setTransactionSuccessful();
659             } finally {
660                 db.endTransaction();
661             }
662            upgradeVersion = 47;
663        }
664 
665 
666         if (upgradeVersion == 47) {
667             /*
668              * The password mode constants have changed again; reset back to no
669              * password.
670              */
671             db.beginTransaction();
672             try {
673                 db.execSQL("DELETE FROM system WHERE name='lockscreen.password_type';");
674                 db.setTransactionSuccessful();
675             } finally {
676                 db.endTransaction();
677             }
678            upgradeVersion = 48;
679        }
680 
681        if (upgradeVersion == 48) {
682            /*
683             * Default recognition service no longer initialized here,
684             * moved to RecognitionManagerService.
685             */
686            upgradeVersion = 49;
687        }
688 
689        if (upgradeVersion == 49) {
690            /*
691             * New settings for new user interface noises.
692             */
693            db.beginTransaction();
694            SQLiteStatement stmt = null;
695            try {
696                 stmt = db.compileStatement("INSERT INTO system(name,value)"
697                         + " VALUES(?,?);");
698                 loadUISoundEffectsSettings(stmt);
699                 db.setTransactionSuccessful();
700             } finally {
701                 db.endTransaction();
702                 if (stmt != null) stmt.close();
703             }
704 
705            upgradeVersion = 50;
706        }
707 
708        if (upgradeVersion == 50) {
709            /*
710             * Install location no longer initiated here.
711             */
712            upgradeVersion = 51;
713        }
714 
715        if (upgradeVersion == 51) {
716            /* Move the lockscreen related settings to Secure, including some private ones. */
717            String[] settingsToMove = {
718                    Secure.LOCK_PATTERN_ENABLED,
719                    Secure.LOCK_PATTERN_VISIBLE,
720                    Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED,
721                    "lockscreen.password_type",
722                    "lockscreen.lockoutattemptdeadline",
723                    "lockscreen.patterneverchosen",
724                    "lock_pattern_autolock",
725                    "lockscreen.lockedoutpermanently",
726                    "lockscreen.password_salt"
727            };
728            moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_SECURE, settingsToMove, false);
729            upgradeVersion = 52;
730        }
731 
732         if (upgradeVersion == 52) {
733             // new vibration/silent mode settings
734             db.beginTransaction();
735             SQLiteStatement stmt = null;
736             try {
737                 stmt = db.compileStatement("INSERT INTO system(name,value)"
738                         + " VALUES(?,?);");
739                 loadBooleanSetting(stmt, Settings.System.VIBRATE_IN_SILENT,
740                         R.bool.def_vibrate_in_silent);
741                 db.setTransactionSuccessful();
742             } finally {
743                 db.endTransaction();
744                 if (stmt != null) stmt.close();
745             }
746 
747             upgradeVersion = 53;
748         }
749 
750         if (upgradeVersion == 53) {
751             /*
752              * New settings for set install location UI no longer initiated here.
753              */
754             upgradeVersion = 54;
755         }
756 
757         if (upgradeVersion == 54) {
758             /*
759              * Update the screen timeout value if set to never
760              */
761             db.beginTransaction();
762             try {
763                 upgradeScreenTimeoutFromNever(db);
764                 db.setTransactionSuccessful();
765             } finally {
766                 db.endTransaction();
767             }
768 
769             upgradeVersion = 55;
770         }
771 
772         if (upgradeVersion == 55) {
773             /* Move the install location settings. */
774             String[] settingsToMove = {
775                     Global.SET_INSTALL_LOCATION,
776                     Global.DEFAULT_INSTALL_LOCATION
777             };
778             moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_SECURE, settingsToMove, false);
779             db.beginTransaction();
780             SQLiteStatement stmt = null;
781             try {
782                 stmt = db.compileStatement("INSERT INTO system(name,value)"
783                         + " VALUES(?,?);");
784                 loadSetting(stmt, Global.SET_INSTALL_LOCATION, 0);
785                 loadSetting(stmt, Global.DEFAULT_INSTALL_LOCATION,
786                         PackageHelper.APP_INSTALL_AUTO);
787                 db.setTransactionSuccessful();
788              } finally {
789                  db.endTransaction();
790                  if (stmt != null) stmt.close();
791              }
792             upgradeVersion = 56;
793         }
794 
795         if (upgradeVersion == 56) {
796             /*
797              * Add Bluetooth to list of toggleable radios in airplane mode
798              */
799             db.beginTransaction();
800             SQLiteStatement stmt = null;
801             try {
802                 db.execSQL("DELETE FROM system WHERE name='"
803                         + Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS + "'");
804                 stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
805                         + " VALUES(?,?);");
806                 loadStringSetting(stmt, Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS,
807                         R.string.airplane_mode_toggleable_radios);
808                 db.setTransactionSuccessful();
809             } finally {
810                 db.endTransaction();
811                 if (stmt != null) stmt.close();
812             }
813             upgradeVersion = 57;
814         }
815 
816         /************* The following are Honeycomb changes ************/
817 
818         if (upgradeVersion == 57) {
819             /*
820              * No longer initializing deleted setting ACCESSIBILITY_SCRIPT_INJECTION.
821              */
822             upgradeVersion = 58;
823         }
824 
825         if (upgradeVersion == 58) {
826             /* Add default for new Auto Time Zone */
827             int autoTimeValue = getIntValueFromSystem(db, Settings.System.AUTO_TIME, 0);
828             db.beginTransaction();
829             SQLiteStatement stmt = null;
830             try {
831                 stmt = db.compileStatement("INSERT INTO system(name,value)" + " VALUES(?,?);");
832                 loadSetting(stmt, Settings.System.AUTO_TIME_ZONE,
833                         autoTimeValue); // Sync timezone to NITZ if auto_time was enabled
834                 db.setTransactionSuccessful();
835             } finally {
836                 db.endTransaction();
837                 if (stmt != null) stmt.close();
838             }
839             upgradeVersion = 59;
840         }
841 
842         if (upgradeVersion == 59) {
843             // Persistence for the rotation lock feature.
844             db.beginTransaction();
845             SQLiteStatement stmt = null;
846             try {
847                 stmt = db.compileStatement("INSERT INTO system(name,value)"
848                         + " VALUES(?,?);");
849                 loadBooleanSetting(stmt, Settings.System.USER_ROTATION,
850                         R.integer.def_user_rotation); // should be zero degrees
851                 db.setTransactionSuccessful();
852             } finally {
853                 db.endTransaction();
854                 if (stmt != null) stmt.close();
855             }
856             upgradeVersion = 60;
857         }
858 
859         if (upgradeVersion == 60) {
860             // Don't do this for upgrades from Gingerbread
861             // Were only required for intra-Honeycomb upgrades for testing
862             // upgradeScreenTimeout(db);
863             upgradeVersion = 61;
864         }
865 
866         if (upgradeVersion == 61) {
867             // Don't do this for upgrades from Gingerbread
868             // Were only required for intra-Honeycomb upgrades for testing
869             // upgradeScreenTimeout(db);
870             upgradeVersion = 62;
871         }
872 
873         // Change the default for screen auto-brightness mode
874         if (upgradeVersion == 62) {
875             // Don't do this for upgrades from Gingerbread
876             // Were only required for intra-Honeycomb upgrades for testing
877             // upgradeAutoBrightness(db);
878             upgradeVersion = 63;
879         }
880 
881         if (upgradeVersion == 63) {
882             // This upgrade adds the STREAM_MUSIC type to the list of
883              // types affected by ringer modes (silent, vibrate, etc.)
884              db.beginTransaction();
885              try {
886                  db.execSQL("DELETE FROM system WHERE name='"
887                          + Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
888                  int newValue = (1 << AudioManager.STREAM_RING)
889                          | (1 << AudioManager.STREAM_NOTIFICATION)
890                          | (1 << AudioManager.STREAM_SYSTEM)
891                          | (1 << AudioManager.STREAM_SYSTEM_ENFORCED)
892                          | (1 << AudioManager.STREAM_MUSIC);
893                  db.execSQL("INSERT INTO system ('name', 'value') values ('"
894                          + Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
895                          + String.valueOf(newValue) + "')");
896                  db.setTransactionSuccessful();
897              } finally {
898                  db.endTransaction();
899              }
900              upgradeVersion = 64;
901          }
902 
903         if (upgradeVersion == 64) {
904             // New setting to configure the long press timeout.
905             db.beginTransaction();
906             SQLiteStatement stmt = null;
907             try {
908                 stmt = db.compileStatement("INSERT INTO secure(name,value)"
909                         + " VALUES(?,?);");
910                 loadIntegerSetting(stmt, Settings.Secure.LONG_PRESS_TIMEOUT,
911                         R.integer.def_long_press_timeout_millis);
912                 stmt.close();
913                 db.setTransactionSuccessful();
914             } finally {
915                 db.endTransaction();
916                 if (stmt != null) stmt.close();
917             }
918             upgradeVersion = 65;
919         }
920 
921         /************* The following are Ice Cream Sandwich changes ************/
922 
923         if (upgradeVersion == 65) {
924             /*
925              * Animations are removed from Settings. Turned on by default
926              */
927             db.beginTransaction();
928             SQLiteStatement stmt = null;
929             try {
930                 db.execSQL("DELETE FROM system WHERE name='"
931                         + Settings.System.WINDOW_ANIMATION_SCALE + "'");
932                 db.execSQL("DELETE FROM system WHERE name='"
933                         + Settings.System.TRANSITION_ANIMATION_SCALE + "'");
934                 stmt = db.compileStatement("INSERT INTO system(name,value)"
935                         + " VALUES(?,?);");
936                 loadDefaultAnimationSettings(stmt);
937                 db.setTransactionSuccessful();
938             } finally {
939                 db.endTransaction();
940                 if (stmt != null) stmt.close();
941             }
942             upgradeVersion = 66;
943         }
944 
945         if (upgradeVersion == 66) {
946             // This upgrade makes sure that MODE_RINGER_STREAMS_AFFECTED is set
947             // according to device voice capability
948             db.beginTransaction();
949             try {
950                 int ringerModeAffectedStreams = (1 << AudioManager.STREAM_RING) |
951                                                 (1 << AudioManager.STREAM_NOTIFICATION) |
952                                                 (1 << AudioManager.STREAM_SYSTEM) |
953                                                 (1 << AudioManager.STREAM_SYSTEM_ENFORCED);
954                 if (!getTelephonyManager().isVoiceCapable()) {
955                     ringerModeAffectedStreams |= (1 << AudioManager.STREAM_MUSIC);
956                 }
957                 db.execSQL("DELETE FROM system WHERE name='"
958                         + Settings.System.MODE_RINGER_STREAMS_AFFECTED + "'");
959                 db.execSQL("INSERT INTO system ('name', 'value') values ('"
960                         + Settings.System.MODE_RINGER_STREAMS_AFFECTED + "', '"
961                         + String.valueOf(ringerModeAffectedStreams) + "')");
962                 db.setTransactionSuccessful();
963             } finally {
964                 db.endTransaction();
965             }
966             upgradeVersion = 67;
967         }
968 
969         if (upgradeVersion == 67) {
970             // New setting to enable touch exploration.
971             db.beginTransaction();
972             SQLiteStatement stmt = null;
973             try {
974                 stmt = db.compileStatement("INSERT INTO secure(name,value)"
975                         + " VALUES(?,?);");
976                 loadBooleanSetting(stmt, Settings.Secure.TOUCH_EXPLORATION_ENABLED,
977                         R.bool.def_touch_exploration_enabled);
978                 stmt.close();
979                 db.setTransactionSuccessful();
980             } finally {
981                 db.endTransaction();
982                 if (stmt != null) stmt.close();
983             }
984             upgradeVersion = 68;
985         }
986 
987         if (upgradeVersion == 68) {
988             // Enable all system sounds by default
989             db.beginTransaction();
990             try {
991                 db.execSQL("DELETE FROM system WHERE name='"
992                         + Settings.System.NOTIFICATIONS_USE_RING_VOLUME + "'");
993                 db.setTransactionSuccessful();
994             } finally {
995                 db.endTransaction();
996             }
997             upgradeVersion = 69;
998         }
999 
1000         if (upgradeVersion == 69) {
1001             // Add RADIO_NFC to AIRPLANE_MODE_RADIO and AIRPLANE_MODE_TOGGLEABLE_RADIOS
1002             String airplaneRadios = mContext.getResources().getString(
1003                     R.string.def_airplane_mode_radios);
1004             String toggleableRadios = mContext.getResources().getString(
1005                     R.string.airplane_mode_toggleable_radios);
1006             db.beginTransaction();
1007             try {
1008                 db.execSQL("UPDATE system SET value='" + airplaneRadios + "' " +
1009                         "WHERE name='" + Settings.System.AIRPLANE_MODE_RADIOS + "'");
1010                 db.execSQL("UPDATE system SET value='" + toggleableRadios + "' " +
1011                         "WHERE name='" + Settings.System.AIRPLANE_MODE_TOGGLEABLE_RADIOS + "'");
1012                 db.setTransactionSuccessful();
1013             } finally {
1014                 db.endTransaction();
1015             }
1016             upgradeVersion = 70;
1017         }
1018 
1019         if (upgradeVersion == 70) {
1020             // Update all built-in bookmarks.  Some of the package names have changed.
1021             loadBookmarks(db);
1022             upgradeVersion = 71;
1023         }
1024 
1025         if (upgradeVersion == 71) {
1026              // New setting to specify whether to speak passwords in accessibility mode.
1027             db.beginTransaction();
1028             SQLiteStatement stmt = null;
1029             try {
1030                 stmt = db.compileStatement("INSERT INTO secure(name,value)"
1031                         + " VALUES(?,?);");
1032                 loadBooleanSetting(stmt, Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
1033                         R.bool.def_accessibility_speak_password);
1034                 db.setTransactionSuccessful();
1035             } finally {
1036                 db.endTransaction();
1037                 if (stmt != null) stmt.close();
1038             }
1039             upgradeVersion = 72;
1040         }
1041 
1042         if (upgradeVersion == 72) {
1043             // update vibration settings
1044             db.beginTransaction();
1045             SQLiteStatement stmt = null;
1046             try {
1047                 stmt = db.compileStatement("INSERT OR REPLACE INTO system(name,value)"
1048                         + " VALUES(?,?);");
1049                 loadBooleanSetting(stmt, Settings.System.VIBRATE_IN_SILENT,
1050                         R.bool.def_vibrate_in_silent);
1051                 db.setTransactionSuccessful();
1052             } finally {
1053                 db.endTransaction();
1054                 if (stmt != null) stmt.close();
1055             }
1056             upgradeVersion = 73;
1057         }
1058 
1059         if (upgradeVersion == 73) {
1060             upgradeVibrateSettingFromNone(db);
1061             upgradeVersion = 74;
1062         }
1063 
1064         if (upgradeVersion == 74) {
1065             // No longer using URL from which WebView loads a JavaScript based screen-reader.
1066             upgradeVersion = 75;
1067         }
1068         if (upgradeVersion == 75) {
1069             db.beginTransaction();
1070             SQLiteStatement stmt = null;
1071             Cursor c = null;
1072             try {
1073                 c = db.query(TABLE_SECURE, new String[] {"_id", "value"},
1074                         "name='lockscreen.disabled'",
1075                         null, null, null, null);
1076                 // only set default if it has not yet been set
1077                 if (c == null || c.getCount() == 0) {
1078                     stmt = db.compileStatement("INSERT INTO system(name,value)"
1079                             + " VALUES(?,?);");
1080                     loadBooleanSetting(stmt, Settings.System.LOCKSCREEN_DISABLED,
1081                             R.bool.def_lockscreen_disabled);
1082                 }
1083                 db.setTransactionSuccessful();
1084             } finally {
1085                 db.endTransaction();
1086                 if (c != null) c.close();
1087                 if (stmt != null) stmt.close();
1088             }
1089             upgradeVersion = 76;
1090         }
1091 
1092         /************* The following are Jelly Bean changes ************/
1093 
1094         if (upgradeVersion == 76) {
1095             // Removed VIBRATE_IN_SILENT setting
1096             db.beginTransaction();
1097             try {
1098                 db.execSQL("DELETE FROM system WHERE name='"
1099                                 + Settings.System.VIBRATE_IN_SILENT + "'");
1100                 db.setTransactionSuccessful();
1101             } finally {
1102                 db.endTransaction();
1103             }
1104 
1105             upgradeVersion = 77;
1106         }
1107 
1108         if (upgradeVersion == 77) {
1109             // "vibrate when ringing" setting moved to SettingsProvider version 168
1110             upgradeVersion = 78;
1111         }
1112 
1113         if (upgradeVersion == 78) {
1114             // ACCESSIBILITY_SCREEN_READER_URL has been removed
1115             upgradeVersion = 79;
1116         }
1117 
1118         if (upgradeVersion == 79) {
1119             // Before touch exploration was a global setting controlled by the user
1120             // via the UI. However, if the enabled accessibility services do not
1121             // handle touch exploration mode, enabling it makes no sense. Therefore,
1122             // now the services request touch exploration mode and the user is
1123             // presented with a dialog to allow that and if she does we store that
1124             // in the database. As a result of this change a user that has enabled
1125             // accessibility, touch exploration, and some accessibility services
1126             // may lose touch exploration state, thus rendering the device useless
1127             // unless sighted help is provided, since the enabled service(s) are
1128             // not in the list of services to which the user granted a permission
1129             // to put the device in touch explore mode. Here we are allowing all
1130             // enabled accessibility services to toggle touch exploration provided
1131             // accessibility and touch exploration are enabled and no services can
1132             // toggle touch exploration. Note that the user has already manually
1133             // enabled the services and touch exploration which means the she has
1134             // given consent to have these services work in touch exploration mode.
1135             final boolean accessibilityEnabled = getIntValueFromTable(db, TABLE_SECURE,
1136                     Settings.Secure.ACCESSIBILITY_ENABLED, 0) == 1;
1137             final boolean touchExplorationEnabled = getIntValueFromTable(db, TABLE_SECURE,
1138                     Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0) == 1;
1139             if (accessibilityEnabled && touchExplorationEnabled) {
1140                 String enabledServices = getStringValueFromTable(db, TABLE_SECURE,
1141                         Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, "");
1142                 String touchExplorationGrantedServices = getStringValueFromTable(db, TABLE_SECURE,
1143                         Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES, "");
1144                 if (TextUtils.isEmpty(touchExplorationGrantedServices)
1145                         && !TextUtils.isEmpty(enabledServices)) {
1146                     SQLiteStatement stmt = null;
1147                     try {
1148                         db.beginTransaction();
1149                         stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
1150                                 + " VALUES(?,?);");
1151                         loadSetting(stmt,
1152                                 Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES,
1153                                 enabledServices);
1154                         db.setTransactionSuccessful();
1155                     } finally {
1156                         db.endTransaction();
1157                         if (stmt != null) stmt.close();
1158                     }
1159                 }
1160             }
1161             upgradeVersion = 80;
1162         }
1163 
1164         // vvv Jelly Bean MR1 changes begin here vvv
1165 
1166         if (upgradeVersion == 80) {
1167             // update screensaver settings
1168             db.beginTransaction();
1169             SQLiteStatement stmt = null;
1170             try {
1171                 stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
1172                         + " VALUES(?,?);");
1173                 loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ENABLED,
1174                         com.android.internal.R.bool.config_dreamsEnabledByDefault);
1175                 loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
1176                         com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
1177                 loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
1178                         com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
1179                 loadStringSetting(stmt, Settings.Secure.SCREENSAVER_COMPONENTS,
1180                         com.android.internal.R.string.config_dreamsDefaultComponent);
1181                 loadStringSetting(stmt, Settings.Secure.SCREENSAVER_DEFAULT_COMPONENT,
1182                         com.android.internal.R.string.config_dreamsDefaultComponent);
1183 
1184                 db.setTransactionSuccessful();
1185             } finally {
1186                 db.endTransaction();
1187                 if (stmt != null) stmt.close();
1188             }
1189             upgradeVersion = 81;
1190         }
1191 
1192         if (upgradeVersion == 81) {
1193             // package_verifier_enable has been removed
1194             upgradeVersion = 82;
1195         }
1196 
1197         if (upgradeVersion == 82) {
1198             // Move to per-user settings dbs
1199             if (mUserHandle == UserHandle.USER_SYSTEM) {
1200 
1201                 db.beginTransaction();
1202                 SQLiteStatement stmt = null;
1203                 try {
1204                     // Migrate now-global settings. Note that this happens before
1205                     // new users can be created.
1206                     createGlobalTable(db);
1207                     String[] settingsToMove = setToStringArray(
1208                             SettingsProvider.sSystemMovedToGlobalSettings);
1209                     moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, false);
1210                     settingsToMove = setToStringArray(
1211                             SettingsProvider.sSecureMovedToGlobalSettings);
1212                     moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, false);
1213 
1214                     db.setTransactionSuccessful();
1215                 } finally {
1216                     db.endTransaction();
1217                     if (stmt != null) stmt.close();
1218                 }
1219             }
1220             upgradeVersion = 83;
1221         }
1222 
1223         if (upgradeVersion == 83) {
1224             // 1. Setting whether screen magnification is enabled.
1225             // 2. Setting for screen magnification scale.
1226             // 3. Setting for screen magnification auto update.
1227             db.beginTransaction();
1228             SQLiteStatement stmt = null;
1229             try {
1230                 stmt = db.compileStatement("INSERT INTO secure(name,value) VALUES(?,?);");
1231                 loadBooleanSetting(stmt,
1232                         Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED,
1233                         R.bool.def_accessibility_display_magnification_enabled);
1234                 stmt.close();
1235                 stmt = db.compileStatement("INSERT INTO secure(name,value) VALUES(?,?);");
1236                 loadFractionSetting(stmt, Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_SCALE,
1237                         R.fraction.def_accessibility_display_magnification_scale, 1);
1238                 stmt.close();
1239 
1240                 db.setTransactionSuccessful();
1241             } finally {
1242                 db.endTransaction();
1243                 if (stmt != null) stmt.close();
1244             }
1245             upgradeVersion = 84;
1246         }
1247 
1248         if (upgradeVersion == 84) {
1249             if (mUserHandle == UserHandle.USER_SYSTEM) {
1250                 db.beginTransaction();
1251                 SQLiteStatement stmt = null;
1252                 try {
1253                     // Patch up the slightly-wrong key migration from 82 -> 83 for those
1254                     // devices that missed it, ignoring if the move is redundant
1255                     String[] settingsToMove = {
1256                             Settings.Secure.ADB_ENABLED,
1257                             Settings.Secure.BLUETOOTH_ON,
1258                             Settings.Secure.DATA_ROAMING,
1259                             Settings.Secure.DEVICE_PROVISIONED,
1260                             Settings.Secure.INSTALL_NON_MARKET_APPS,
1261                             Settings.Secure.USB_MASS_STORAGE_ENABLED
1262                     };
1263                     moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
1264                     db.setTransactionSuccessful();
1265                 } finally {
1266                     db.endTransaction();
1267                     if (stmt != null) stmt.close();
1268                 }
1269             }
1270             upgradeVersion = 85;
1271         }
1272 
1273         if (upgradeVersion == 85) {
1274             if (mUserHandle == UserHandle.USER_SYSTEM) {
1275                 db.beginTransaction();
1276                 try {
1277                     // Fix up the migration, ignoring already-migrated elements, to snap up to
1278                     // date with new changes to the set of global versus system/secure settings
1279                     String[] settingsToMove = { Settings.System.STAY_ON_WHILE_PLUGGED_IN };
1280                     moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, true);
1281 
1282                     db.setTransactionSuccessful();
1283                 } finally {
1284                     db.endTransaction();
1285                 }
1286             }
1287             upgradeVersion = 86;
1288         }
1289 
1290         if (upgradeVersion == 86) {
1291             if (mUserHandle == UserHandle.USER_SYSTEM) {
1292                 db.beginTransaction();
1293                 try {
1294                     String[] settingsToMove = {
1295                             Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
1296                             Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE
1297                     };
1298                     moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
1299 
1300                     db.setTransactionSuccessful();
1301                 } finally {
1302                     db.endTransaction();
1303                 }
1304             }
1305             upgradeVersion = 87;
1306         }
1307 
1308         if (upgradeVersion == 87) {
1309             if (mUserHandle == UserHandle.USER_SYSTEM) {
1310                 db.beginTransaction();
1311                 try {
1312                     String[] settingsToMove = {
1313                             Settings.Global.DATA_STALL_ALARM_NON_AGGRESSIVE_DELAY_IN_MS,
1314                             Settings.Global.DATA_STALL_ALARM_AGGRESSIVE_DELAY_IN_MS,
1315                             Settings.Global.GPRS_REGISTER_CHECK_PERIOD_MS
1316                     };
1317                     moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
1318 
1319                     db.setTransactionSuccessful();
1320                 } finally {
1321                     db.endTransaction();
1322                 }
1323             }
1324             upgradeVersion = 88;
1325         }
1326 
1327         if (upgradeVersion == 88) {
1328             if (mUserHandle == UserHandle.USER_SYSTEM) {
1329                 db.beginTransaction();
1330                 try {
1331                     String[] settingsToMove = {
1332                             Settings.Global.BATTERY_DISCHARGE_DURATION_THRESHOLD,
1333                             Settings.Global.BATTERY_DISCHARGE_THRESHOLD,
1334                             Settings.Global.SEND_ACTION_APP_ERROR,
1335                             Settings.Global.DROPBOX_AGE_SECONDS,
1336                             Settings.Global.DROPBOX_MAX_FILES,
1337                             Settings.Global.DROPBOX_QUOTA_KB,
1338                             Settings.Global.DROPBOX_QUOTA_PERCENT,
1339                             Settings.Global.DROPBOX_RESERVE_PERCENT,
1340                             Settings.Global.DROPBOX_TAG_PREFIX,
1341                             Settings.Global.ERROR_LOGCAT_PREFIX,
1342                             Settings.Global.SYS_FREE_STORAGE_LOG_INTERVAL,
1343                             Settings.Global.DISK_FREE_CHANGE_REPORTING_THRESHOLD,
1344                             Settings.Global.SYS_STORAGE_THRESHOLD_PERCENTAGE,
1345                             Settings.Global.SYS_STORAGE_THRESHOLD_MAX_BYTES,
1346                             Settings.Global.SYS_STORAGE_FULL_THRESHOLD_BYTES,
1347                             Settings.Global.SYNC_MAX_RETRY_DELAY_IN_SECONDS,
1348                             Settings.Global.CONNECTIVITY_CHANGE_DELAY,
1349                             Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED,
1350                             Settings.Global.CAPTIVE_PORTAL_SERVER,
1351                             Settings.Global.NSD_ON,
1352                             Settings.Global.SET_INSTALL_LOCATION,
1353                             Settings.Global.DEFAULT_INSTALL_LOCATION,
1354                             Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY,
1355                             Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY,
1356                             Settings.Global.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT,
1357                             Settings.Global.HTTP_PROXY,
1358                             Settings.Global.GLOBAL_HTTP_PROXY_HOST,
1359                             Settings.Global.GLOBAL_HTTP_PROXY_PORT,
1360                             Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
1361                             Settings.Global.SET_GLOBAL_HTTP_PROXY,
1362                             Settings.Global.DEFAULT_DNS_SERVER,
1363                     };
1364                     moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
1365                     db.setTransactionSuccessful();
1366                 } finally {
1367                     db.endTransaction();
1368                 }
1369             }
1370             upgradeVersion = 89;
1371         }
1372 
1373         if (upgradeVersion == 89) {
1374             if (mUserHandle == UserHandle.USER_SYSTEM) {
1375                 db.beginTransaction();
1376                 try {
1377                     String[] prefixesToMove = {
1378                             Settings.Global.BLUETOOTH_HEADSET_PRIORITY_PREFIX,
1379                             Settings.Global.BLUETOOTH_A2DP_SINK_PRIORITY_PREFIX,
1380                             Settings.Global.BLUETOOTH_INPUT_DEVICE_PRIORITY_PREFIX,
1381                     };
1382 
1383                     movePrefixedSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, prefixesToMove);
1384 
1385                     db.setTransactionSuccessful();
1386                 } finally {
1387                     db.endTransaction();
1388                 }
1389             }
1390             upgradeVersion = 90;
1391         }
1392 
1393         if (upgradeVersion == 90) {
1394             if (mUserHandle == UserHandle.USER_SYSTEM) {
1395                 db.beginTransaction();
1396                 try {
1397                     String[] systemToGlobal = {
1398                             Settings.Global.WINDOW_ANIMATION_SCALE,
1399                             Settings.Global.TRANSITION_ANIMATION_SCALE,
1400                             Settings.Global.ANIMATOR_DURATION_SCALE,
1401                             Settings.Global.FANCY_IME_ANIMATIONS,
1402                             Settings.Global.COMPATIBILITY_MODE,
1403                             Settings.Global.EMERGENCY_TONE,
1404                             Settings.Global.CALL_AUTO_RETRY,
1405                             Settings.Global.DEBUG_APP,
1406                             Settings.Global.WAIT_FOR_DEBUGGER,
1407                             Settings.Global.ALWAYS_FINISH_ACTIVITIES,
1408                     };
1409                     String[] secureToGlobal = {
1410                             Settings.Global.PREFERRED_NETWORK_MODE,
1411                             Settings.Global.CDMA_SUBSCRIPTION_MODE,
1412                     };
1413 
1414                     moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, systemToGlobal, true);
1415                     moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, secureToGlobal, true);
1416 
1417                     db.setTransactionSuccessful();
1418                 } finally {
1419                     db.endTransaction();
1420                 }
1421             }
1422             upgradeVersion = 91;
1423         }
1424 
1425         if (upgradeVersion == 91) {
1426             if (mUserHandle == UserHandle.USER_SYSTEM) {
1427                 db.beginTransaction();
1428                 try {
1429                     // Move ringer mode from system to global settings
1430                     String[] settingsToMove = { Settings.Global.MODE_RINGER };
1431                     moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, true);
1432 
1433                     db.setTransactionSuccessful();
1434                 } finally {
1435                     db.endTransaction();
1436                 }
1437             }
1438             upgradeVersion = 92;
1439         }
1440 
1441         if (upgradeVersion == 92) {
1442             SQLiteStatement stmt = null;
1443             try {
1444                 stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
1445                         + " VALUES(?,?);");
1446                 if (mUserHandle == UserHandle.USER_SYSTEM) {
1447                     // consider existing primary users to have made it through user setup
1448                     // if the globally-scoped device-provisioned bit is set
1449                     // (indicating they already made it through setup as primary)
1450                     int deviceProvisioned = getIntValueFromTable(db, TABLE_GLOBAL,
1451                             Settings.Global.DEVICE_PROVISIONED, 0);
1452                     loadSetting(stmt, Settings.Secure.USER_SETUP_COMPLETE,
1453                             deviceProvisioned);
1454                 } else {
1455                     // otherwise use the default
1456                     loadBooleanSetting(stmt, Settings.Secure.USER_SETUP_COMPLETE,
1457                             R.bool.def_user_setup_complete);
1458                 }
1459             } finally {
1460                 if (stmt != null) stmt.close();
1461             }
1462             upgradeVersion = 93;
1463         }
1464 
1465         if (upgradeVersion == 93) {
1466             // Redo this step, since somehow it didn't work the first time for some users
1467             if (mUserHandle == UserHandle.USER_SYSTEM) {
1468                 db.beginTransaction();
1469                 try {
1470                     // Migrate now-global settings
1471                     String[] settingsToMove = setToStringArray(
1472                             SettingsProvider.sSystemMovedToGlobalSettings);
1473                     moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_GLOBAL, settingsToMove, true);
1474                     settingsToMove = setToStringArray(
1475                             SettingsProvider.sSecureMovedToGlobalSettings);
1476                     moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
1477 
1478                     db.setTransactionSuccessful();
1479                 } finally {
1480                     db.endTransaction();
1481                 }
1482             }
1483             upgradeVersion = 94;
1484         }
1485 
1486         if (upgradeVersion == 94) {
1487             // charging sound moved to SettingsProvider version 184
1488             upgradeVersion = 95;
1489         }
1490 
1491         if (upgradeVersion == 95) {
1492             if (mUserHandle == UserHandle.USER_SYSTEM) {
1493                 db.beginTransaction();
1494                 try {
1495                     String[] settingsToMove = { Settings.Global.BUGREPORT_IN_POWER_MENU };
1496                     moveSettingsToNewTable(db, TABLE_SECURE, TABLE_GLOBAL, settingsToMove, true);
1497                     db.setTransactionSuccessful();
1498                 } finally {
1499                     db.endTransaction();
1500                 }
1501             }
1502             upgradeVersion = 96;
1503         }
1504 
1505         if (upgradeVersion == 96) {
1506             // NOP bump due to a reverted change that some people got on upgrade.
1507             upgradeVersion = 97;
1508         }
1509 
1510         if (upgradeVersion == 97) {
1511             if (mUserHandle == UserHandle.USER_SYSTEM) {
1512                 db.beginTransaction();
1513                 SQLiteStatement stmt = null;
1514                 try {
1515                     stmt = db.compileStatement("INSERT OR REPLACE INTO global(name,value)"
1516                             + " VALUES(?,?);");
1517                     loadIntegerSetting(stmt, Settings.Global.LOW_BATTERY_SOUND_TIMEOUT,
1518                             R.integer.def_low_battery_sound_timeout);
1519                     db.setTransactionSuccessful();
1520                 } finally {
1521                     db.endTransaction();
1522                     if (stmt != null) stmt.close();
1523                 }
1524             }
1525             upgradeVersion = 98;
1526         }
1527 
1528         if (upgradeVersion == 98) {
1529             // no-op; LOCK_SCREEN_SHOW_NOTIFICATIONS now handled in version 106
1530             upgradeVersion = 99;
1531         }
1532 
1533         if (upgradeVersion == 99) {
1534             // no-op; HEADS_UP_NOTIFICATIONS_ENABLED now handled in version 100
1535             upgradeVersion = 100;
1536         }
1537 
1538         if (upgradeVersion == 100) {
1539             // note: LOCK_SCREEN_SHOW_NOTIFICATIONS now handled in version 106
1540             if (mUserHandle == UserHandle.USER_SYSTEM) {
1541                 db.beginTransaction();
1542                 SQLiteStatement stmt = null;
1543                 try {
1544                     stmt = db.compileStatement("INSERT OR REPLACE INTO global(name,value)"
1545                             + " VALUES(?,?);");
1546                     loadIntegerSetting(stmt, Global.HEADS_UP_NOTIFICATIONS_ENABLED,
1547                             R.integer.def_heads_up_enabled);
1548                     db.setTransactionSuccessful();
1549                 } finally {
1550                     db.endTransaction();
1551                     if (stmt != null) stmt.close();
1552                 }
1553             }
1554             upgradeVersion = 101;
1555         }
1556 
1557         if (upgradeVersion == 101) {
1558             if (mUserHandle == UserHandle.USER_SYSTEM) {
1559                 db.beginTransaction();
1560                 SQLiteStatement stmt = null;
1561                 try {
1562                     stmt = db.compileStatement("INSERT OR IGNORE INTO global(name,value)"
1563                             + " VALUES(?,?);");
1564                     loadSetting(stmt, Settings.Global.DEVICE_NAME, getDefaultDeviceName());
1565                     db.setTransactionSuccessful();
1566                 } finally {
1567                     db.endTransaction();
1568                     if (stmt != null) stmt.close();
1569                 }
1570             }
1571             upgradeVersion = 102;
1572         }
1573 
1574         if (upgradeVersion == 102) {
1575             db.beginTransaction();
1576             SQLiteStatement stmt = null;
1577             try {
1578                 // The INSTALL_NON_MARKET_APPS setting is becoming per-user rather
1579                 // than device-global.
1580                 if (mUserHandle == UserHandle.USER_SYSTEM) {
1581                     // In the owner user, the global table exists so we can migrate the
1582                     // entry from there to the secure table, preserving its value.
1583                     String[] globalToSecure = {
1584                             Settings.Secure.INSTALL_NON_MARKET_APPS
1585                     };
1586                     moveSettingsToNewTable(db, TABLE_GLOBAL, TABLE_SECURE, globalToSecure, true);
1587                 } else {
1588                     // Secondary users' dbs don't have the global table, so institute the
1589                     // default.
1590                     stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
1591                             + " VALUES(?,?);");
1592                     loadBooleanSetting(stmt, Settings.Secure.INSTALL_NON_MARKET_APPS,
1593                             R.bool.def_install_non_market_apps);
1594                 }
1595                 db.setTransactionSuccessful();
1596             } finally {
1597                 db.endTransaction();
1598                 if (stmt != null) stmt.close();
1599             }
1600             upgradeVersion = 103;
1601         }
1602 
1603         if (upgradeVersion == 103) {
1604             db.beginTransaction();
1605             SQLiteStatement stmt = null;
1606             try {
1607                 stmt = db.compileStatement("INSERT OR REPLACE INTO secure(name,value)"
1608                         + " VALUES(?,?);");
1609                 loadBooleanSetting(stmt, Settings.Secure.WAKE_GESTURE_ENABLED,
1610                         R.bool.def_wake_gesture_enabled);
1611                 db.setTransactionSuccessful();
1612             } finally {
1613                 db.endTransaction();
1614                 if (stmt != null) stmt.close();
1615             }
1616             upgradeVersion = 104;
1617         }
1618 
1619         if (upgradeVersion < 105) {
1620             // No-op: GUEST_USER_ENABLED setting was removed
1621             upgradeVersion = 105;
1622         }
1623 
1624         if (upgradeVersion < 106) {
1625             // LOCK_SCREEN_SHOW_NOTIFICATIONS is now per-user.
1626             db.beginTransaction();
1627             SQLiteStatement stmt = null;
1628             try {
1629                 stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
1630                         + " VALUES(?,?);");
1631                 loadIntegerSetting(stmt, Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
1632                         R.integer.def_lock_screen_show_notifications);
1633                 if (mUserHandle == UserHandle.USER_SYSTEM) {
1634                     final int oldShow = getIntValueFromTable(db,
1635                             TABLE_GLOBAL, Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, -1);
1636                     if (oldShow >= 0) {
1637                         // overwrite the default with whatever you had
1638                         loadSetting(stmt, Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, oldShow);
1639                         final SQLiteStatement deleteStmt
1640                                 = db.compileStatement("DELETE FROM global WHERE name=?");
1641                         deleteStmt.bindString(1, Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS);
1642                         deleteStmt.execute();
1643                     }
1644                 }
1645                 db.setTransactionSuccessful();
1646             } finally {
1647                 db.endTransaction();
1648                 if (stmt != null) stmt.close();
1649             }
1650             upgradeVersion = 106;
1651         }
1652 
1653         if (upgradeVersion < 107) {
1654             // Add trusted sound setting
1655             if (mUserHandle == UserHandle.USER_SYSTEM) {
1656                 db.beginTransaction();
1657                 SQLiteStatement stmt = null;
1658                 try {
1659                     stmt = db.compileStatement("INSERT OR REPLACE INTO global(name,value)"
1660                             + " VALUES(?,?);");
1661                     loadStringSetting(stmt, Settings.Global.TRUSTED_SOUND,
1662                             R.string.def_trusted_sound);
1663                     db.setTransactionSuccessful();
1664                 } finally {
1665                     db.endTransaction();
1666                     if (stmt != null) stmt.close();
1667                 }
1668             }
1669             upgradeVersion = 107;
1670         }
1671 
1672         if (upgradeVersion < 108) {
1673             // Reset the auto-brightness setting to default since the behavior
1674             // of the feature is now quite different and is being presented to
1675             // the user in a new way as "adaptive brightness".
1676             db.beginTransaction();
1677             SQLiteStatement stmt = null;
1678             try {
1679                 stmt = db.compileStatement("INSERT OR REPLACE INTO system(name,value)"
1680                         + " VALUES(?,?);");
1681                 loadBooleanSetting(stmt, Settings.System.SCREEN_BRIGHTNESS_MODE,
1682                         R.bool.def_screen_brightness_automatic_mode);
1683                 db.setTransactionSuccessful();
1684             } finally {
1685                 db.endTransaction();
1686                 if (stmt != null) stmt.close();
1687             }
1688             upgradeVersion = 108;
1689         }
1690 
1691         if (upgradeVersion < 109) {
1692             db.beginTransaction();
1693             SQLiteStatement stmt = null;
1694             try {
1695                 stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
1696                         + " VALUES(?,?);");
1697                 loadBooleanSetting(stmt, Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
1698                         R.bool.def_lock_screen_allow_private_notifications);
1699                 db.setTransactionSuccessful();
1700             } finally {
1701                 db.endTransaction();
1702                 if (stmt != null) stmt.close();
1703             }
1704             upgradeVersion = 109;
1705         }
1706 
1707         if (upgradeVersion < 110) {
1708             // The SIP_CALL_OPTIONS value SIP_ASK_EACH_TIME is being deprecated.
1709             // If the SIP_CALL_OPTIONS setting is set to SIP_ASK_EACH_TIME, default to
1710             // SIP_ADDRESS_ONLY.
1711             db.beginTransaction();
1712             SQLiteStatement stmt = null;
1713             try {
1714                 stmt = db.compileStatement("UPDATE system SET value = ? " +
1715                         "WHERE name = ? AND value = ?;");
1716                 stmt.bindString(1, Settings.System.SIP_ADDRESS_ONLY);
1717                 stmt.bindString(2, Settings.System.SIP_CALL_OPTIONS);
1718                 stmt.bindString(3, Settings.System.SIP_ASK_ME_EACH_TIME);
1719                 stmt.execute();
1720                 db.setTransactionSuccessful();
1721             } finally {
1722                 db.endTransaction();
1723                 if (stmt != null) stmt.close();
1724             }
1725             upgradeVersion = 110;
1726         }
1727 
1728         if (upgradeVersion < 111) {
1729             // reset ringer mode, so it doesn't force zen mode to follow
1730             if (mUserHandle == UserHandle.USER_SYSTEM) {
1731                 db.beginTransaction();
1732                 SQLiteStatement stmt = null;
1733                 try {
1734                     stmt = db.compileStatement("INSERT OR REPLACE INTO global(name,value)"
1735                             + " VALUES(?,?);");
1736                     loadSetting(stmt, Settings.Global.MODE_RINGER, AudioManager.RINGER_MODE_NORMAL);
1737                     db.setTransactionSuccessful();
1738                 } finally {
1739                     db.endTransaction();
1740                     if (stmt != null) stmt.close();
1741                 }
1742             }
1743             upgradeVersion = 111;
1744         }
1745 
1746         if (upgradeVersion < 112) {
1747             if (mUserHandle == UserHandle.USER_SYSTEM) {
1748                 // When device name was added, we went with Manufacturer + Model, device name should
1749                 // actually be Model only.
1750                 // Update device name to Model if it wasn't modified by user.
1751                 db.beginTransaction();
1752                 SQLiteStatement stmt = null;
1753                 try {
1754                     stmt = db.compileStatement("UPDATE global SET value = ? "
1755                         + " WHERE name = ? AND value = ?");
1756                     stmt.bindString(1, getDefaultDeviceName()); // new default device name
1757                     stmt.bindString(2, Settings.Global.DEVICE_NAME);
1758                     stmt.bindString(3, getOldDefaultDeviceName()); // old default device name
1759                     stmt.execute();
1760                     db.setTransactionSuccessful();
1761                 } finally {
1762                     db.endTransaction();
1763                     if (stmt != null) stmt.close();
1764                 }
1765             }
1766             upgradeVersion = 112;
1767         }
1768 
1769         if (upgradeVersion < 113) {
1770             db.beginTransaction();
1771             SQLiteStatement stmt = null;
1772             try {
1773                 stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
1774                         + " VALUES(?,?);");
1775                 loadIntegerSetting(stmt, Settings.Secure.SLEEP_TIMEOUT,
1776                         R.integer.def_sleep_timeout);
1777                 db.setTransactionSuccessful();
1778             } finally {
1779                 db.endTransaction();
1780                 if (stmt != null) stmt.close();
1781             }
1782             upgradeVersion = 113;
1783         }
1784 
1785         // We skipped 114 to handle a merge conflict with the introduction of theater mode.
1786 
1787         if (upgradeVersion < 115) {
1788             if (mUserHandle == UserHandle.USER_SYSTEM) {
1789                 db.beginTransaction();
1790                 SQLiteStatement stmt = null;
1791                 try {
1792                     stmt = db.compileStatement("INSERT OR IGNORE INTO global(name,value)"
1793                             + " VALUES(?,?);");
1794                     loadBooleanSetting(stmt, Global.THEATER_MODE_ON,
1795                             R.bool.def_theater_mode_on);
1796                     db.setTransactionSuccessful();
1797                 } finally {
1798                     db.endTransaction();
1799                     if (stmt != null) stmt.close();
1800                 }
1801             }
1802             upgradeVersion = 115;
1803         }
1804 
1805         if (upgradeVersion < 116) {
1806             /*
1807              * To control the default value by carrier config manager, initializing
1808              * ENHANCED_4G_MODE_ENABLED has been removed.
1809              */
1810             upgradeVersion = 116;
1811         }
1812 
1813         if (upgradeVersion < 117) {
1814             db.beginTransaction();
1815             try {
1816                 String[] systemToSecure = {
1817                         Settings.Secure.LOCK_TO_APP_EXIT_LOCKED
1818                 };
1819                 moveSettingsToNewTable(db, TABLE_SYSTEM, TABLE_SECURE, systemToSecure, true);
1820                 db.setTransactionSuccessful();
1821             } finally {
1822                 db.endTransaction();
1823             }
1824             upgradeVersion = 117;
1825         }
1826 
1827         if (upgradeVersion < 118) {
1828             // Reset rotation-lock-for-accessibility on upgrade, since it now hides the display
1829             // setting.
1830             db.beginTransaction();
1831             SQLiteStatement stmt = null;
1832             try {
1833                 stmt = db.compileStatement("INSERT OR REPLACE INTO system(name,value)"
1834                         + " VALUES(?,?);");
1835                 loadSetting(stmt, Settings.System.HIDE_ROTATION_LOCK_TOGGLE_FOR_ACCESSIBILITY, 0);
1836                 db.setTransactionSuccessful();
1837             } finally {
1838                 db.endTransaction();
1839                 if (stmt != null) stmt.close();
1840             }
1841             upgradeVersion = 118;
1842         }
1843 
1844         /*
1845          * IMPORTANT: Do not add any more upgrade steps here as the global,
1846          * secure, and system settings are no longer stored in a database
1847          * but are kept in memory and persisted to XML.
1848          *
1849          * See: SettingsProvider.UpgradeController#onUpgradeLocked
1850          */
1851 
1852         if (upgradeVersion != currentVersion) {
1853             recreateDatabase(db, oldVersion, upgradeVersion, currentVersion);
1854         }
1855     }
1856 
recreateDatabase(SQLiteDatabase db, int oldVersion, int upgradeVersion, int currentVersion)1857     public void recreateDatabase(SQLiteDatabase db, int oldVersion,
1858             int upgradeVersion, int currentVersion) {
1859         db.execSQL("DROP TABLE IF EXISTS global");
1860         db.execSQL("DROP TABLE IF EXISTS globalIndex1");
1861         db.execSQL("DROP TABLE IF EXISTS system");
1862         db.execSQL("DROP INDEX IF EXISTS systemIndex1");
1863         db.execSQL("DROP TABLE IF EXISTS secure");
1864         db.execSQL("DROP INDEX IF EXISTS secureIndex1");
1865         db.execSQL("DROP TABLE IF EXISTS gservices");
1866         db.execSQL("DROP INDEX IF EXISTS gservicesIndex1");
1867         db.execSQL("DROP TABLE IF EXISTS bluetooth_devices");
1868         db.execSQL("DROP TABLE IF EXISTS bookmarks");
1869         db.execSQL("DROP INDEX IF EXISTS bookmarksIndex1");
1870         db.execSQL("DROP INDEX IF EXISTS bookmarksIndex2");
1871         db.execSQL("DROP TABLE IF EXISTS favorites");
1872 
1873         onCreate(db);
1874 
1875         // Added for diagnosing settings.db wipes after the fact
1876         String wipeReason = oldVersion + "/" + upgradeVersion + "/" + currentVersion;
1877         db.execSQL("INSERT INTO secure(name,value) values('" +
1878                 "wiped_db_reason" + "','" + wipeReason + "');");
1879     }
1880 
setToStringArray(Set<String> set)1881     private String[] setToStringArray(Set<String> set) {
1882         String[] array = new String[set.size()];
1883         return set.toArray(array);
1884     }
1885 
moveSettingsToNewTable(SQLiteDatabase db, String sourceTable, String destTable, String[] settingsToMove, boolean doIgnore)1886     private void moveSettingsToNewTable(SQLiteDatabase db,
1887             String sourceTable, String destTable,
1888             String[] settingsToMove, boolean doIgnore) {
1889         // Copy settings values from the source table to the dest, and remove from the source
1890         SQLiteStatement insertStmt = null;
1891         SQLiteStatement deleteStmt = null;
1892 
1893         db.beginTransaction();
1894         try {
1895             insertStmt = db.compileStatement("INSERT "
1896                     + (doIgnore ? " OR IGNORE " : "")
1897                     + " INTO " + destTable + " (name,value) SELECT name,value FROM "
1898                     + sourceTable + " WHERE name=?");
1899             deleteStmt = db.compileStatement("DELETE FROM " + sourceTable + " WHERE name=?");
1900 
1901             for (String setting : settingsToMove) {
1902                 insertStmt.bindString(1, setting);
1903                 insertStmt.execute();
1904 
1905                 deleteStmt.bindString(1, setting);
1906                 deleteStmt.execute();
1907             }
1908             db.setTransactionSuccessful();
1909         } finally {
1910             db.endTransaction();
1911             if (insertStmt != null) {
1912                 insertStmt.close();
1913             }
1914             if (deleteStmt != null) {
1915                 deleteStmt.close();
1916             }
1917         }
1918     }
1919 
1920     /**
1921      * Move any settings with the given prefixes from the source table to the
1922      * destination table.
1923      */
movePrefixedSettingsToNewTable( SQLiteDatabase db, String sourceTable, String destTable, String[] prefixesToMove)1924     private void movePrefixedSettingsToNewTable(
1925             SQLiteDatabase db, String sourceTable, String destTable, String[] prefixesToMove) {
1926         SQLiteStatement insertStmt = null;
1927         SQLiteStatement deleteStmt = null;
1928 
1929         db.beginTransaction();
1930         try {
1931             insertStmt = db.compileStatement("INSERT INTO " + destTable
1932                     + " (name,value) SELECT name,value FROM " + sourceTable
1933                     + " WHERE substr(name,0,?)=?");
1934             deleteStmt = db.compileStatement(
1935                     "DELETE FROM " + sourceTable + " WHERE substr(name,0,?)=?");
1936 
1937             for (String prefix : prefixesToMove) {
1938                 insertStmt.bindLong(1, prefix.length() + 1);
1939                 insertStmt.bindString(2, prefix);
1940                 insertStmt.execute();
1941 
1942                 deleteStmt.bindLong(1, prefix.length() + 1);
1943                 deleteStmt.bindString(2, prefix);
1944                 deleteStmt.execute();
1945             }
1946             db.setTransactionSuccessful();
1947         } finally {
1948             db.endTransaction();
1949             if (insertStmt != null) {
1950                 insertStmt.close();
1951             }
1952             if (deleteStmt != null) {
1953                 deleteStmt.close();
1954             }
1955         }
1956     }
1957 
upgradeLockPatternLocation(SQLiteDatabase db)1958     private void upgradeLockPatternLocation(SQLiteDatabase db) {
1959         Cursor c = db.query(TABLE_SYSTEM, new String[] {"_id", "value"}, "name='lock_pattern'",
1960                 null, null, null, null);
1961         if (c.getCount() > 0) {
1962             c.moveToFirst();
1963             String lockPattern = c.getString(1);
1964             if (!TextUtils.isEmpty(lockPattern)) {
1965                 // Convert lock pattern
1966                 try {
1967                     LockPatternUtils lpu = new LockPatternUtils(mContext);
1968                     List<LockPatternView.Cell> cellPattern =
1969                             LockPatternUtils.byteArrayToPattern(lockPattern.getBytes());
1970                     lpu.setLockCredential(
1971                             LockscreenCredential.createPattern(cellPattern),
1972                             LockscreenCredential.createNone(),
1973                             UserHandle.USER_SYSTEM);
1974                 } catch (IllegalArgumentException e) {
1975                     // Don't want corrupted lock pattern to hang the reboot process
1976                 }
1977             }
1978             c.close();
1979             db.delete(TABLE_SYSTEM, "name='lock_pattern'", null);
1980         } else {
1981             c.close();
1982         }
1983     }
1984 
upgradeScreenTimeoutFromNever(SQLiteDatabase db)1985     private void upgradeScreenTimeoutFromNever(SQLiteDatabase db) {
1986         // See if the timeout is -1 (for "Never").
1987         Cursor c = db.query(TABLE_SYSTEM, new String[] { "_id", "value" }, "name=? AND value=?",
1988                 new String[] { Settings.System.SCREEN_OFF_TIMEOUT, "-1" },
1989                 null, null, null);
1990 
1991         SQLiteStatement stmt = null;
1992         if (c.getCount() > 0) {
1993             c.close();
1994             try {
1995                 stmt = db.compileStatement("INSERT OR REPLACE INTO system(name,value)"
1996                         + " VALUES(?,?);");
1997 
1998                 // Set the timeout to 30 minutes in milliseconds
1999                 loadSetting(stmt, Settings.System.SCREEN_OFF_TIMEOUT,
2000                         Integer.toString(30 * 60 * 1000));
2001             } finally {
2002                 if (stmt != null) stmt.close();
2003             }
2004         } else {
2005             c.close();
2006         }
2007     }
2008 
upgradeVibrateSettingFromNone(SQLiteDatabase db)2009     private void upgradeVibrateSettingFromNone(SQLiteDatabase db) {
2010         int vibrateSetting = getIntValueFromSystem(db, Settings.System.VIBRATE_ON, 0);
2011         // If the ringer vibrate value is invalid, set it to the default
2012         if ((vibrateSetting & 3) == AudioManager.VIBRATE_SETTING_OFF) {
2013             vibrateSetting = AudioSystem.getValueForVibrateSetting(0,
2014                     AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ONLY_SILENT);
2015         }
2016         // Apply the same setting to the notification vibrate value
2017         vibrateSetting = AudioSystem.getValueForVibrateSetting(vibrateSetting,
2018                 AudioManager.VIBRATE_TYPE_NOTIFICATION, vibrateSetting);
2019 
2020         SQLiteStatement stmt = null;
2021         try {
2022             stmt = db.compileStatement("INSERT OR REPLACE INTO system(name,value)"
2023                     + " VALUES(?,?);");
2024             loadSetting(stmt, Settings.System.VIBRATE_ON, vibrateSetting);
2025         } finally {
2026             if (stmt != null)
2027                 stmt.close();
2028         }
2029     }
2030 
upgradeScreenTimeout(SQLiteDatabase db)2031     private void upgradeScreenTimeout(SQLiteDatabase db) {
2032         // Change screen timeout to current default
2033         db.beginTransaction();
2034         SQLiteStatement stmt = null;
2035         try {
2036             stmt = db.compileStatement("INSERT OR REPLACE INTO system(name,value)"
2037                     + " VALUES(?,?);");
2038             loadIntegerSetting(stmt, Settings.System.SCREEN_OFF_TIMEOUT,
2039                     R.integer.def_screen_off_timeout);
2040             db.setTransactionSuccessful();
2041         } finally {
2042             db.endTransaction();
2043             if (stmt != null)
2044                 stmt.close();
2045         }
2046     }
2047 
upgradeAutoBrightness(SQLiteDatabase db)2048     private void upgradeAutoBrightness(SQLiteDatabase db) {
2049         db.beginTransaction();
2050         try {
2051             String value =
2052                     mContext.getResources().getBoolean(
2053                     R.bool.def_screen_brightness_automatic_mode) ? "1" : "0";
2054             db.execSQL("INSERT OR REPLACE INTO system(name,value) values('" +
2055                     Settings.System.SCREEN_BRIGHTNESS_MODE + "','" + value + "');");
2056             db.setTransactionSuccessful();
2057         } finally {
2058             db.endTransaction();
2059         }
2060     }
2061 
2062     /**
2063      * Loads the default set of bookmarked shortcuts from an xml file.
2064      *
2065      * @param db The database to write the values into
2066      */
loadBookmarks(SQLiteDatabase db)2067     private void loadBookmarks(SQLiteDatabase db) {
2068         ContentValues values = new ContentValues();
2069 
2070         PackageManager packageManager = mContext.getPackageManager();
2071         try {
2072             XmlResourceParser parser = mContext.getResources().getXml(R.xml.bookmarks);
2073             XmlUtils.beginDocument(parser, "bookmarks");
2074 
2075             final int depth = parser.getDepth();
2076             int type;
2077 
2078             while (((type = parser.next()) != XmlPullParser.END_TAG ||
2079                     parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
2080 
2081                 if (type != XmlPullParser.START_TAG) {
2082                     continue;
2083                 }
2084 
2085                 String name = parser.getName();
2086                 if (!"bookmark".equals(name)) {
2087                     break;
2088                 }
2089 
2090                 String pkg = parser.getAttributeValue(null, "package");
2091                 String cls = parser.getAttributeValue(null, "class");
2092                 String shortcutStr = parser.getAttributeValue(null, "shortcut");
2093                 String category = parser.getAttributeValue(null, "category");
2094 
2095                 int shortcutValue = shortcutStr.charAt(0);
2096                 if (TextUtils.isEmpty(shortcutStr)) {
2097                     Log.w(TAG, "Unable to get shortcut for: " + pkg + "/" + cls);
2098                     continue;
2099                 }
2100 
2101                 final Intent intent;
2102                 final String title;
2103                 if (pkg != null && cls != null) {
2104                     ActivityInfo info = null;
2105                     ComponentName cn = new ComponentName(pkg, cls);
2106                     try {
2107                         info = packageManager.getActivityInfo(cn, 0);
2108                     } catch (PackageManager.NameNotFoundException e) {
2109                         String[] packages = packageManager.canonicalToCurrentPackageNames(
2110                                 new String[] { pkg });
2111                         cn = new ComponentName(packages[0], cls);
2112                         try {
2113                             info = packageManager.getActivityInfo(cn, 0);
2114                         } catch (PackageManager.NameNotFoundException e1) {
2115                             Log.w(TAG, "Unable to add bookmark: " + pkg + "/" + cls, e);
2116                             continue;
2117                         }
2118                     }
2119 
2120                     intent = new Intent(Intent.ACTION_MAIN, null);
2121                     intent.addCategory(Intent.CATEGORY_LAUNCHER);
2122                     intent.setComponent(cn);
2123                     title = info.loadLabel(packageManager).toString();
2124                 } else if (category != null) {
2125                     intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category);
2126                     title = "";
2127                 } else {
2128                     Log.w(TAG, "Unable to add bookmark for shortcut " + shortcutStr
2129                             + ": missing package/class or category attributes");
2130                     continue;
2131                 }
2132 
2133                 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2134                 values.put(Settings.Bookmarks.INTENT, intent.toUri(0));
2135                 values.put(Settings.Bookmarks.TITLE, title);
2136                 values.put(Settings.Bookmarks.SHORTCUT, shortcutValue);
2137                 db.delete("bookmarks", "shortcut = ?",
2138                         new String[] { Integer.toString(shortcutValue) });
2139                 db.insert("bookmarks", null, values);
2140             }
2141         } catch (XmlPullParserException e) {
2142             Log.w(TAG, "Got execption parsing bookmarks.", e);
2143         } catch (IOException e) {
2144             Log.w(TAG, "Got execption parsing bookmarks.", e);
2145         }
2146     }
2147 
2148     /**
2149      * Loads the default volume levels. It is actually inserting the index of
2150      * the volume array for each of the volume controls.
2151      *
2152      * @param db the database to insert the volume levels into
2153      */
loadVolumeLevels(SQLiteDatabase db)2154     private void loadVolumeLevels(SQLiteDatabase db) {
2155         SQLiteStatement stmt = null;
2156         try {
2157             stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
2158                     + " VALUES(?,?);");
2159 
2160             loadSetting(stmt, Settings.System.VOLUME_MUSIC,
2161                     AudioSystem.getDefaultStreamVolume(AudioManager.STREAM_MUSIC));
2162             loadSetting(stmt, Settings.System.VOLUME_RING,
2163                     AudioSystem.getDefaultStreamVolume(AudioManager.STREAM_RING));
2164             loadSetting(stmt, Settings.System.VOLUME_SYSTEM,
2165                     AudioSystem.getDefaultStreamVolume(AudioManager.STREAM_SYSTEM));
2166             loadSetting(
2167                     stmt,
2168                     Settings.System.VOLUME_VOICE,
2169                     AudioSystem.getDefaultStreamVolume(AudioManager.STREAM_VOICE_CALL));
2170             loadSetting(stmt, Settings.System.VOLUME_ALARM,
2171                     AudioSystem.getDefaultStreamVolume(AudioManager.STREAM_ALARM));
2172             loadSetting(
2173                     stmt,
2174                     Settings.System.VOLUME_NOTIFICATION,
2175                     AudioSystem.getDefaultStreamVolume(AudioManager.STREAM_NOTIFICATION));
2176             loadSetting(
2177                     stmt,
2178                     Settings.System.VOLUME_BLUETOOTH_SCO,
2179                     AudioSystem.getDefaultStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO));
2180 
2181             // By default:
2182             // - ringtones, notification, system and music streams are affected by ringer mode
2183             // on non voice capable devices (tablets)
2184             // - ringtones, notification and system streams are affected by ringer mode
2185             // on voice capable devices (phones)
2186             int ringerModeAffectedStreams = (1 << AudioManager.STREAM_RING) |
2187                                             (1 << AudioManager.STREAM_NOTIFICATION) |
2188                                             (1 << AudioManager.STREAM_SYSTEM) |
2189                                             (1 << AudioManager.STREAM_SYSTEM_ENFORCED);
2190             if (!mContext.getResources().getBoolean(
2191                     com.android.internal.R.bool.config_voice_capable)) {
2192                 ringerModeAffectedStreams |= (1 << AudioManager.STREAM_MUSIC);
2193             }
2194             loadSetting(stmt, Settings.System.MODE_RINGER_STREAMS_AFFECTED,
2195                     ringerModeAffectedStreams);
2196 
2197             loadSetting(stmt, Settings.System.MUTE_STREAMS_AFFECTED,
2198                     AudioSystem.DEFAULT_MUTE_STREAMS_AFFECTED);
2199         } finally {
2200             if (stmt != null) stmt.close();
2201         }
2202     }
2203 
loadVibrateSetting(SQLiteDatabase db, boolean deleteOld)2204     private void loadVibrateSetting(SQLiteDatabase db, boolean deleteOld) {
2205         if (deleteOld) {
2206             db.execSQL("DELETE FROM system WHERE name='" + Settings.System.VIBRATE_ON + "'");
2207         }
2208 
2209         SQLiteStatement stmt = null;
2210         try {
2211             stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
2212                     + " VALUES(?,?);");
2213 
2214             // Vibrate on by default for ringer, on for notification
2215             int vibrate = 0;
2216             vibrate = AudioSystem.getValueForVibrateSetting(vibrate,
2217                     AudioManager.VIBRATE_TYPE_NOTIFICATION,
2218                     AudioManager.VIBRATE_SETTING_ONLY_SILENT);
2219             vibrate |= AudioSystem.getValueForVibrateSetting(vibrate,
2220                     AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ONLY_SILENT);
2221             loadSetting(stmt, Settings.System.VIBRATE_ON, vibrate);
2222         } finally {
2223             if (stmt != null) stmt.close();
2224         }
2225     }
2226 
loadSettings(SQLiteDatabase db)2227     private void loadSettings(SQLiteDatabase db) {
2228         loadSystemSettings(db);
2229         loadSecureSettings(db);
2230         // The global table only exists for the 'owner/system' user
2231         if (mUserHandle == UserHandle.USER_SYSTEM) {
2232             loadGlobalSettings(db);
2233         }
2234     }
2235 
loadSystemSettings(SQLiteDatabase db)2236     private void loadSystemSettings(SQLiteDatabase db) {
2237         SQLiteStatement stmt = null;
2238         try {
2239             stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
2240                     + " VALUES(?,?);");
2241 
2242             loadBooleanSetting(stmt, Settings.System.DIM_SCREEN,
2243                     R.bool.def_dim_screen);
2244             loadIntegerSetting(stmt, Settings.System.SCREEN_OFF_TIMEOUT,
2245                     R.integer.def_screen_off_timeout);
2246 
2247             // Set default cdma DTMF type
2248             loadSetting(stmt, Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, 0);
2249 
2250             // Set default hearing aid
2251             loadSetting(stmt, Settings.System.HEARING_AID, 0);
2252 
2253             // Set default tty mode
2254             loadSetting(stmt, Settings.System.TTY_MODE, 0);
2255 
2256             loadIntegerSetting(stmt, Settings.System.SCREEN_BRIGHTNESS,
2257                     R.integer.def_screen_brightness);
2258 
2259             loadIntegerSetting(stmt, Settings.System.SCREEN_BRIGHTNESS_FOR_VR,
2260                     com.android.internal.R.integer.config_screenBrightnessForVrSettingDefault);
2261 
2262             loadBooleanSetting(stmt, Settings.System.SCREEN_BRIGHTNESS_MODE,
2263                     R.bool.def_screen_brightness_automatic_mode);
2264 
2265             loadBooleanSetting(stmt, Settings.System.ACCELEROMETER_ROTATION,
2266                     R.bool.def_accelerometer_rotation);
2267 
2268             loadDefaultHapticSettings(stmt);
2269 
2270             loadBooleanSetting(stmt, Settings.System.NOTIFICATION_LIGHT_PULSE,
2271                     R.bool.def_notification_pulse);
2272 
2273             loadUISoundEffectsSettings(stmt);
2274 
2275             loadIntegerSetting(stmt, Settings.System.POINTER_SPEED,
2276                     R.integer.def_pointer_speed);
2277 
2278             /*
2279              * IMPORTANT: Do not add any more upgrade steps here as the global,
2280              * secure, and system settings are no longer stored in a database
2281              * but are kept in memory and persisted to XML.
2282              *
2283              * See: SettingsProvider.UpgradeController#onUpgradeLocked
2284              */
2285         } finally {
2286             if (stmt != null) stmt.close();
2287         }
2288     }
2289 
loadUISoundEffectsSettings(SQLiteStatement stmt)2290     private void loadUISoundEffectsSettings(SQLiteStatement stmt) {
2291         loadBooleanSetting(stmt, Settings.System.DTMF_TONE_WHEN_DIALING,
2292                 R.bool.def_dtmf_tones_enabled);
2293         loadBooleanSetting(stmt, Settings.System.SOUND_EFFECTS_ENABLED,
2294                 R.bool.def_sound_effects_enabled);
2295         loadBooleanSetting(stmt, Settings.System.HAPTIC_FEEDBACK_ENABLED,
2296                 R.bool.def_haptic_feedback);
2297 
2298         loadIntegerSetting(stmt, Settings.System.LOCKSCREEN_SOUNDS_ENABLED,
2299             R.integer.def_lockscreen_sounds_enabled);
2300     }
2301 
loadDefaultAnimationSettings(SQLiteStatement stmt)2302     private void loadDefaultAnimationSettings(SQLiteStatement stmt) {
2303         loadFractionSetting(stmt, Settings.System.WINDOW_ANIMATION_SCALE,
2304                 R.fraction.def_window_animation_scale, 1);
2305         loadFractionSetting(stmt, Settings.System.TRANSITION_ANIMATION_SCALE,
2306                 R.fraction.def_window_transition_scale, 1);
2307     }
2308 
loadDefaultHapticSettings(SQLiteStatement stmt)2309     private void loadDefaultHapticSettings(SQLiteStatement stmt) {
2310         loadBooleanSetting(stmt, Settings.System.HAPTIC_FEEDBACK_ENABLED,
2311                 R.bool.def_haptic_feedback);
2312     }
2313 
loadSecureSettings(SQLiteDatabase db)2314     private void loadSecureSettings(SQLiteDatabase db) {
2315         SQLiteStatement stmt = null;
2316         try {
2317             stmt = db.compileStatement("INSERT OR IGNORE INTO secure(name,value)"
2318                     + " VALUES(?,?);");
2319 
2320             // Don't do this.  The SystemServer will initialize ADB_ENABLED from a
2321             // persistent system property instead.
2322             //loadSetting(stmt, Settings.Secure.ADB_ENABLED, 0);
2323 
2324             // Allow mock locations default, based on build
2325             loadSetting(stmt, Settings.Secure.ALLOW_MOCK_LOCATION,
2326                     "1".equals(SystemProperties.get("ro.allow.mock.location")) ? 1 : 0);
2327 
2328             loadSecure35Settings(stmt);
2329 
2330             loadBooleanSetting(stmt, Settings.Secure.MOUNT_PLAY_NOTIFICATION_SND,
2331                     R.bool.def_mount_play_notification_snd);
2332 
2333             loadBooleanSetting(stmt, Settings.Secure.MOUNT_UMS_AUTOSTART,
2334                     R.bool.def_mount_ums_autostart);
2335 
2336             loadBooleanSetting(stmt, Settings.Secure.MOUNT_UMS_PROMPT,
2337                     R.bool.def_mount_ums_prompt);
2338 
2339             loadBooleanSetting(stmt, Settings.Secure.MOUNT_UMS_NOTIFY_ENABLED,
2340                     R.bool.def_mount_ums_notify_enabled);
2341 
2342             loadIntegerSetting(stmt, Settings.Secure.LONG_PRESS_TIMEOUT,
2343                     R.integer.def_long_press_timeout_millis);
2344 
2345             loadBooleanSetting(stmt, Settings.Secure.TOUCH_EXPLORATION_ENABLED,
2346                     R.bool.def_touch_exploration_enabled);
2347 
2348             loadBooleanSetting(stmt, Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
2349                     R.bool.def_accessibility_speak_password);
2350 
2351             if (SystemProperties.getBoolean("ro.lockscreen.disable.default", false) == true) {
2352                 loadSetting(stmt, Settings.System.LOCKSCREEN_DISABLED, "1");
2353             } else {
2354                 loadBooleanSetting(stmt, Settings.System.LOCKSCREEN_DISABLED,
2355                         R.bool.def_lockscreen_disabled);
2356             }
2357 
2358             loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ENABLED,
2359                     com.android.internal.R.bool.config_dreamsEnabledByDefault);
2360             loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
2361                     com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
2362             loadBooleanSetting(stmt, Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
2363                     com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
2364             loadStringSetting(stmt, Settings.Secure.SCREENSAVER_COMPONENTS,
2365                     com.android.internal.R.string.config_dreamsDefaultComponent);
2366             loadStringSetting(stmt, Settings.Secure.SCREENSAVER_DEFAULT_COMPONENT,
2367                     com.android.internal.R.string.config_dreamsDefaultComponent);
2368 
2369             loadBooleanSetting(stmt, Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED,
2370                     R.bool.def_accessibility_display_magnification_enabled);
2371 
2372             loadFractionSetting(stmt, Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_SCALE,
2373                     R.fraction.def_accessibility_display_magnification_scale, 1);
2374 
2375             loadBooleanSetting(stmt, Settings.Secure.USER_SETUP_COMPLETE,
2376                     R.bool.def_user_setup_complete);
2377 
2378             loadStringSetting(stmt, Settings.Secure.IMMERSIVE_MODE_CONFIRMATIONS,
2379                         R.string.def_immersive_mode_confirmations);
2380 
2381             loadBooleanSetting(stmt, Settings.Secure.INSTALL_NON_MARKET_APPS,
2382                     R.bool.def_install_non_market_apps);
2383 
2384             loadBooleanSetting(stmt, Settings.Secure.WAKE_GESTURE_ENABLED,
2385                     R.bool.def_wake_gesture_enabled);
2386 
2387             loadIntegerSetting(stmt, Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
2388                     R.integer.def_lock_screen_show_notifications);
2389 
2390             loadBooleanSetting(stmt, Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
2391                     R.bool.def_lock_screen_allow_private_notifications);
2392 
2393             loadIntegerSetting(stmt, Settings.Secure.SLEEP_TIMEOUT,
2394                     R.integer.def_sleep_timeout);
2395 
2396             /*
2397              * IMPORTANT: Do not add any more upgrade steps here as the global,
2398              * secure, and system settings are no longer stored in a database
2399              * but are kept in memory and persisted to XML.
2400              *
2401              * See: SettingsProvider.UpgradeController#onUpgradeLocked
2402              */
2403         } finally {
2404             if (stmt != null) stmt.close();
2405         }
2406     }
2407 
loadSecure35Settings(SQLiteStatement stmt)2408     private void loadSecure35Settings(SQLiteStatement stmt) {
2409         loadBooleanSetting(stmt, Settings.Secure.BACKUP_ENABLED,
2410                 R.bool.def_backup_enabled);
2411 
2412         loadStringSetting(stmt, Settings.Secure.BACKUP_TRANSPORT,
2413                 R.string.def_backup_transport);
2414     }
2415 
loadGlobalSettings(SQLiteDatabase db)2416     private void loadGlobalSettings(SQLiteDatabase db) {
2417         SQLiteStatement stmt = null;
2418         final Resources res = mContext.getResources();
2419         try {
2420             stmt = db.compileStatement("INSERT OR IGNORE INTO global(name,value)"
2421                     + " VALUES(?,?);");
2422 
2423             // --- Previously in 'system'
2424             loadBooleanSetting(stmt, Settings.Global.AIRPLANE_MODE_ON,
2425                     R.bool.def_airplane_mode_on);
2426 
2427             loadBooleanSetting(stmt, Settings.Global.THEATER_MODE_ON,
2428                     R.bool.def_theater_mode_on);
2429 
2430             loadStringSetting(stmt, Settings.Global.AIRPLANE_MODE_RADIOS,
2431                     R.string.def_airplane_mode_radios);
2432 
2433             loadStringSetting(stmt, Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS,
2434                     R.string.airplane_mode_toggleable_radios);
2435 
2436             loadBooleanSetting(stmt, Settings.Global.ASSISTED_GPS_ENABLED,
2437                     R.bool.assisted_gps_enabled);
2438 
2439             loadBooleanSetting(stmt, Settings.Global.AUTO_TIME,
2440                     R.bool.def_auto_time); // Sync time to NITZ
2441 
2442             loadBooleanSetting(stmt, Settings.Global.AUTO_TIME_ZONE,
2443                     R.bool.def_auto_time_zone); // Sync timezone to NITZ
2444 
2445             loadSetting(stmt, Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
2446                     ("1".equals(SystemProperties.get("ro.kernel.qemu")) ||
2447                         res.getBoolean(R.bool.def_stay_on_while_plugged_in))
2448                      ? 1 : 0);
2449 
2450             loadIntegerSetting(stmt, Settings.Global.WIFI_SLEEP_POLICY,
2451                     R.integer.def_wifi_sleep_policy);
2452 
2453             loadSetting(stmt, Settings.Global.MODE_RINGER,
2454                     AudioManager.RINGER_MODE_NORMAL);
2455 
2456             loadDefaultAnimationSettings(stmt);
2457 
2458             // --- Previously in 'secure'
2459             loadBooleanSetting(stmt, Settings.Global.WIFI_ON,
2460                     R.bool.def_wifi_on);
2461 
2462             loadBooleanSetting(stmt, Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
2463                     R.bool.def_networks_available_notification_on);
2464 
2465             loadBooleanSetting(stmt, Settings.Global.BLUETOOTH_ON,
2466                     R.bool.def_bluetooth_on);
2467 
2468             // Enable or disable Cell Broadcast SMS
2469             loadSetting(stmt, Settings.Global.CDMA_CELL_BROADCAST_SMS,
2470                     RILConstants.CDMA_CELL_BROADCAST_SMS_DISABLED);
2471 
2472             // Data roaming default, based on build
2473             loadSetting(stmt, Settings.Global.DATA_ROAMING,
2474                     TelephonyProperties.data_roaming().orElse(false) ? 1 : 0);
2475 
2476             loadBooleanSetting(stmt, Settings.Global.DEVICE_PROVISIONED,
2477                     R.bool.def_device_provisioned);
2478 
2479             final int maxBytes = res.getInteger(
2480                     R.integer.def_download_manager_max_bytes_over_mobile);
2481             if (maxBytes > 0) {
2482                 loadSetting(stmt, Settings.Global.DOWNLOAD_MAX_BYTES_OVER_MOBILE,
2483                         Integer.toString(maxBytes));
2484             }
2485 
2486             final int recommendedMaxBytes = res.getInteger(
2487                     R.integer.def_download_manager_recommended_max_bytes_over_mobile);
2488             if (recommendedMaxBytes > 0) {
2489                 loadSetting(stmt, Settings.Global.DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE,
2490                         Integer.toString(recommendedMaxBytes));
2491             }
2492 
2493             // Mobile Data default, based on build
2494             loadSetting(stmt, Settings.Global.MOBILE_DATA,
2495                     TelephonyProperties.mobile_data().orElse(true) ? 1 : 0);
2496 
2497             loadBooleanSetting(stmt, Settings.Global.NETSTATS_ENABLED,
2498                     R.bool.def_netstats_enabled);
2499 
2500             loadBooleanSetting(stmt, Settings.Global.USB_MASS_STORAGE_ENABLED,
2501                     R.bool.def_usb_mass_storage_enabled);
2502 
2503             loadIntegerSetting(stmt, Settings.Global.WIFI_MAX_DHCP_RETRY_COUNT,
2504                     R.integer.def_max_dhcp_retries);
2505 
2506             loadBooleanSetting(stmt, Settings.Global.WIFI_DISPLAY_ON,
2507                     R.bool.def_wifi_display_on);
2508 
2509             loadStringSetting(stmt, Settings.Global.LOCK_SOUND,
2510                     R.string.def_lock_sound);
2511             loadStringSetting(stmt, Settings.Global.UNLOCK_SOUND,
2512                     R.string.def_unlock_sound);
2513             loadStringSetting(stmt, Settings.Global.TRUSTED_SOUND,
2514                     R.string.def_trusted_sound);
2515             loadIntegerSetting(stmt, Settings.Global.POWER_SOUNDS_ENABLED,
2516                     R.integer.def_power_sounds_enabled);
2517             loadStringSetting(stmt, Settings.Global.LOW_BATTERY_SOUND,
2518                     R.string.def_low_battery_sound);
2519             loadIntegerSetting(stmt, Settings.Global.DOCK_SOUNDS_ENABLED,
2520                     R.integer.def_dock_sounds_enabled);
2521             loadIntegerSetting(stmt, Settings.Global.DOCK_SOUNDS_ENABLED_WHEN_ACCESSIBILITY,
2522                     R.integer.def_dock_sounds_enabled_when_accessibility);
2523             loadStringSetting(stmt, Settings.Global.DESK_DOCK_SOUND,
2524                     R.string.def_desk_dock_sound);
2525             loadStringSetting(stmt, Settings.Global.DESK_UNDOCK_SOUND,
2526                     R.string.def_desk_undock_sound);
2527             loadStringSetting(stmt, Settings.Global.CAR_DOCK_SOUND,
2528                     R.string.def_car_dock_sound);
2529             loadStringSetting(stmt, Settings.Global.CAR_UNDOCK_SOUND,
2530                     R.string.def_car_undock_sound);
2531 
2532             loadIntegerSetting(stmt, Settings.Global.DOCK_AUDIO_MEDIA_ENABLED,
2533                     R.integer.def_dock_audio_media_enabled);
2534 
2535             loadSetting(stmt, Settings.Global.SET_INSTALL_LOCATION, 0);
2536             loadSetting(stmt, Settings.Global.DEFAULT_INSTALL_LOCATION,
2537                     PackageHelper.APP_INSTALL_AUTO);
2538 
2539             // Set default cdma emergency tone
2540             loadSetting(stmt, Settings.Global.EMERGENCY_TONE, 0);
2541 
2542             // Set default cdma call auto retry
2543             loadSetting(stmt, Settings.Global.CALL_AUTO_RETRY, 0);
2544 
2545             // Set the preferred network mode to target desired value or Default
2546             // value defined in system property
2547             StringBuilder val = new StringBuilder();
2548             List<Integer> defaultNetworks = TelephonyProperties.default_network();
2549             int phoneCount = 1;
2550             TelephonyManager telephonyManager = getTelephonyManager();
2551             if (telephonyManager != null) {
2552                 phoneCount = telephonyManager.getSupportedModemCount();
2553             }
2554             for (int phoneId = 0; phoneId < phoneCount; phoneId++) {
2555                 int mode = defaultNetworks.size() <= phoneId
2556                         || defaultNetworks.get(phoneId) == null
2557                         ? TelephonyManager.DEFAULT_PREFERRED_NETWORK_MODE : defaultNetworks.get(phoneId);
2558                 if (phoneId > 0) val.append(',');
2559                 val.append(mode);
2560             }
2561             loadSetting(stmt, Settings.Global.PREFERRED_NETWORK_MODE, val.toString());
2562 
2563             // Set the preferred cdma subscription source to target desired value or default
2564             // value defined in Phone
2565             int type = SystemProperties.getInt("ro.telephony.default_cdma_sub",
2566                     Phone.PREFERRED_CDMA_SUBSCRIPTION);
2567             loadSetting(stmt, Settings.Global.CDMA_SUBSCRIPTION_MODE, type);
2568 
2569             loadIntegerSetting(stmt, Settings.Global.LOW_BATTERY_SOUND_TIMEOUT,
2570                     R.integer.def_low_battery_sound_timeout);
2571 
2572             loadIntegerSetting(stmt, Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE,
2573                     R.integer.def_wifi_scan_always_available);
2574 
2575             loadIntegerSetting(stmt, Global.HEADS_UP_NOTIFICATIONS_ENABLED,
2576                     R.integer.def_heads_up_enabled);
2577 
2578             loadSetting(stmt, Settings.Global.DEVICE_NAME, getDefaultDeviceName());
2579 
2580             // Set default lid/cover behaviour according to legacy device config
2581             final int defaultLidBehavior;
2582             if (res.getBoolean(com.android.internal.R.bool.config_lidControlsSleep)) {
2583                 // WindowManagerFuncs.LID_BEHAVIOR_SLEEP
2584                 defaultLidBehavior = 1;
2585             } else if (res.getBoolean(com.android.internal.R.bool.config_lidControlsScreenLock)) {
2586                 // WindowManagerFuncs.LID_BEHAVIOR_LOCK
2587                 defaultLidBehavior = 2;
2588             } else {
2589                 // WindowManagerFuncs.LID_BEHAVIOR_NONE
2590                 defaultLidBehavior = 0;
2591             }
2592             loadSetting(stmt, Settings.Global.LID_BEHAVIOR, defaultLidBehavior);
2593 
2594             /*
2595              * IMPORTANT: Do not add any more upgrade steps here as the global,
2596              * secure, and system settings are no longer stored in a database
2597              * but are kept in memory and persisted to XML.
2598              *
2599              * See: SettingsProvider.UpgradeController#onUpgradeLocked
2600              */
2601         } finally {
2602             if (stmt != null) stmt.close();
2603         }
2604     }
2605 
loadSetting(SQLiteStatement stmt, String key, Object value)2606     private void loadSetting(SQLiteStatement stmt, String key, Object value) {
2607         stmt.bindString(1, key);
2608         stmt.bindString(2, value.toString());
2609         stmt.execute();
2610     }
2611 
loadStringSetting(SQLiteStatement stmt, String key, int resid)2612     private void loadStringSetting(SQLiteStatement stmt, String key, int resid) {
2613         loadSetting(stmt, key, mContext.getResources().getString(resid));
2614     }
2615 
loadBooleanSetting(SQLiteStatement stmt, String key, int resid)2616     private void loadBooleanSetting(SQLiteStatement stmt, String key, int resid) {
2617         loadSetting(stmt, key,
2618                 mContext.getResources().getBoolean(resid) ? "1" : "0");
2619     }
2620 
loadIntegerSetting(SQLiteStatement stmt, String key, int resid)2621     private void loadIntegerSetting(SQLiteStatement stmt, String key, int resid) {
2622         loadSetting(stmt, key,
2623                 Integer.toString(mContext.getResources().getInteger(resid)));
2624     }
2625 
loadFractionSetting(SQLiteStatement stmt, String key, int resid, int base)2626     private void loadFractionSetting(SQLiteStatement stmt, String key, int resid, int base) {
2627         loadSetting(stmt, key,
2628                 Float.toString(mContext.getResources().getFraction(resid, base, base)));
2629     }
2630 
getIntValueFromSystem(SQLiteDatabase db, String name, int defaultValue)2631     private int getIntValueFromSystem(SQLiteDatabase db, String name, int defaultValue) {
2632         return getIntValueFromTable(db, TABLE_SYSTEM, name, defaultValue);
2633     }
2634 
getIntValueFromTable(SQLiteDatabase db, String table, String name, int defaultValue)2635     private int getIntValueFromTable(SQLiteDatabase db, String table, String name,
2636             int defaultValue) {
2637         String value = getStringValueFromTable(db, table, name, null);
2638         return (value != null) ? Integer.parseInt(value) : defaultValue;
2639     }
2640 
getStringValueFromTable(SQLiteDatabase db, String table, String name, String defaultValue)2641     private String getStringValueFromTable(SQLiteDatabase db, String table, String name,
2642             String defaultValue) {
2643         Cursor c = null;
2644         try {
2645             c = db.query(table, new String[] { Settings.System.VALUE }, "name='" + name + "'",
2646                     null, null, null, null);
2647             if (c != null && c.moveToFirst()) {
2648                 String val = c.getString(0);
2649                 return val == null ? defaultValue : val;
2650             }
2651         } finally {
2652             if (c != null) c.close();
2653         }
2654         return defaultValue;
2655     }
2656 
getOldDefaultDeviceName()2657     private String getOldDefaultDeviceName() {
2658         return mContext.getResources().getString(R.string.def_device_name,
2659                 Build.MANUFACTURER, Build.MODEL);
2660     }
2661 
getDefaultDeviceName()2662     private String getDefaultDeviceName() {
2663         return mContext.getResources().getString(R.string.def_device_name_simple, Build.MODEL);
2664     }
2665 
getTelephonyManager()2666     private TelephonyManager getTelephonyManager() {
2667         return (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
2668     }
2669 }
2670