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