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