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