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