Android中Settings默认值的设置
设置Settings的默认值有两种方式
A. 在获取是有一个接口可以进行默认值设置,当数据库中查询不到该值时,就会返回传入的默认值。
public static int getInt(ContentResolver cr, String name, int def) {
return getIntForUser(cr, name, def, cr.getUserId());
}
其中int def就是要写入的默认值。
B. 在SettingProvider中进行设置,也就是写入到数据库中
首先,在SettingsProvider/res/values/defaults.xml中写入Settings中的值对应的默认值,例如:
然后在DatabaseHelper.java中创建完数据库进行默认值的插入
该插入的流程为:
onCreate(SQLiteDatabase db) -> loadSettings(db) -> loadSystemSettings(db);loadSecureSettings(db);loadGlobalSettings(db);
源码如下:
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE system (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT UNIQUE ON CONFLICT REPLACE," +
"value TEXT" +
");");
db.execSQL("CREATE INDEX systemIndex1 ON system (name);");
createSecureTable(db);
// Only create the global table for the singleton \'owner/system\' user
if (mUserHandle == UserHandle.USER_SYSTEM) {
createGlobalTable(db);
}
db.execSQL("CREATE TABLE bluetooth_devices (" +
"_id INTEGER PRIMARY KEY," +
"name TEXT," +
"addr TEXT," +
"channel INTEGER," +
"type INTEGER" +
");");
db.execSQL("CREATE TABLE bookmarks (" +
"_id INTEGER PRIMARY KEY," +
"title TEXT," +
"folder TEXT," +
"intent TEXT," +
"shortcut INTEGER," +
"ordering INTEGER" +
");");
db.execSQL("CREATE INDEX bookmarksIndex1 ON bookmarks (folder);");
db.execSQL("CREATE INDEX bookmarksIndex2 ON bookmarks (shortcut);");
// Populate bookmarks table with initial bookmarks
boolean onlyCore = false;
try {
onlyCore = IPackageManager.Stub.asInterface(ServiceManager.getService(
"package")).isOnlyCoreApps();
} catch (RemoteException e) {
}
if (!onlyCore) {
loadBookmarks(db);
}
// Load initial volume levels into DB
loadVolumeLevels(db);
// Load inital settings values
loadSettings(db);
}