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