在Android中,如果你要打开或关闭数据连接,WiFi,飞行模式,蓝牙,你需要对数据库中这些开关的值进行修改,这时,你会使用到Settings.System,在settings数据库中这些属性值以键值对的形式存储,通过其get和put方法可进行这些系统属性的修改。
我们从如何添加一个属性开始,慢慢了解其使用方法。本例添加一个控制数据连接的属性:def_data_connection 。
1、定义属于该属性的字段,可定义为integer,string,boolean等,这里设置为boolean型,并赋值为true。
\frameworks\base\packages\SettingsProvider\res\values\defaults.xml
true
\frameworks\base\core\java\android\provider\Settings.java
public static final String DATA_CONNECTION = "data_connection";
在这个Settings.java里面同时写了获取Settings.System属性值的方法,
如putInt():
public static boolean putInt(ContentResolver cr, String name, int value) {
return putIntForUser(cr, name, value, UserHandle.myUserId());
}
/** @hide */
public static boolean putIntForUser(ContentResolver cr, String name, int value,
int userHandle) {
if (LOCATION_MODE.equals(name)) {
// HACK ALERT: temporary hack to work around b/10491283.
// TODO: once b/10491283 fixed, remove this hack
return setLocationModeForUser(cr, value, userHandle);
}
return putStringForUser(cr, name, Integer.toString(value), userHandle);
}
getInt():
public static int getInt(ContentResolver cr, String name)
throws SettingNotFoundException {
return getIntForUser(cr, name, UserHandle.myUserId());
}
/** @hide */
public static int getIntForUser(ContentResolver cr, String name, int userHandle)
throws SettingNotFoundException {
if (LOCATION_MODE.equals(name)) {
// HACK ALERT: temporary hack to work around b/10491283.
// TODO: once b/10491283 fixed, remove this hack
return getLocationModeForUser(cr, userHandle);
}
String v = getStringForUser(cr, name, userHandle);
try {
return Integer.parseInt(v);
} catch (NumberFormatException e) {
throw new SettingNotFoundException(name);
}
}
3、把该值插入到数据库中:
\frameworks\base\packages\SettingsProvider\src\com\android\providers\settings\DatabaseHelper.java
在loadSystemSettings方法中插入到数据库并赋予处置。
private void loadSystemSettings(SQLiteDatabase db) {
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
+ " VALUES(?,?);");
........
loadBooleanSetting(stmt, Settings.System.DATA_CONNECTION,R.bool.def_data_connection);//data connection
.........
} finally {
if (stmt != null) stmt.close();
}
}
其中loadBooleanSetting是赋值的方法:
private void loadBooleanSetting(SQLiteStatement stmt, String key, int resid) {
loadSetting(stmt, key,
mContext.getResources().getBoolean(resid) ? "1" : "0");
}
private void loadSetting(SQLiteStatement stmt, String key, Object value) {
stmt.bindString(1, key);
stmt.bindString(2, value.toString());
stmt.execute();
}
此时第1步定义的def_data_connection被赋给了Settings.System.DATA_CONNECTION。此时我们工作已经基本结束了,接下来可以调用该属性进行操作了。
取值:
boolean enable = Settings.System.getInt(getContentResolver(),Settings.System.DATA_CONNECTION, 1)==1;
Settings.System.putInt(context.getContentResolver(),Settings.System.DATA_CONNECTION, 0);