项目中有时候需要保存一些永久变量,使用系统数据库是一个好的选择,但是如果该变量需要在第三方APP中访问,就还需要解决要解决权限问题。
下面以变量notification_panel_enable
,bool类型为例
一、添加变量
首先要进行变量初始化,一般位于SettingsProvider
定义变量,方便引用
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java public final class Settings { */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/global"); + //bianjb 状态栏下拉开关 + public static final String NOTIFICATION_PANEL_ENABLE = "notification_panel_enable"; +
初始化变量
diff --git a/packages/SettingsProvider/res/values/defaults.xml <resources> + <!--bianjb 添加状态栏下拉开关 --> + <bool name="notification_panel_enable">true</bool> diff --git a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java class DatabaseHelper extends SQLiteOpenHelper { try { stmt = db.compileStatement("INSERT OR IGNORE INTO global(name,value)" + " VALUES(?,?);"); + //bianjb 添加状态栏下拉开关 + loadBooleanSetting(stmt, Settings.Global.NOTIFICATION_PANEL_ENABLE, + R.bool.notification_panel_enable);
二、解决第三方APP读写的权限问题
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java @@ -1249,18 +1250,23 @@ public class SettingsProvider extends ContentProvider { private boolean mutateGlobalSetting(String name, String value, String tag, boolean makeDefault, int requestingUserId, int operation, boolean forceNotify, int mode) { - // Make sure the caller can change the settings - treated as secure. - enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS); String pkg = "com.android.settings"; //数据写入时使用系统settings应用的包名,系统会进行调用进程的包名判断 if(!"notification_panel_enable".equals(name)){ //bianjb 自定义数据不进行权限验证 pkg = ""; // Make sure the caller can change the settings - treated as secure. enforceWritePermission(Manifest.permission.WRITE_SECURE_SETTINGS); } //下面修改在插入操作时使用上面预设的包名,绕过包名验证 @@ -1268,7 +1274,7 @@ public class SettingsProvider extends ContentProvider { case MUTATION_OPERATION_INSERT: { return mSettingsRegistry.insertSettingLocked(SETTINGS_TYPE_GLOBAL, UserHandle.USER_SYSTEM, name, value, tag, makeDefault, - getCallingPackage(), forceNotify, CRITICAL_GLOBAL_SETTINGS); + "".equals(pkg)?getCallingPackage():pkg, forceNotify, CRITICAL_GLOBAL_SETTINGS); }
三、变量读写
//写 Settings.Global.putInt(mContext.getContentResolver(),Settings.Global.NOTIFICATION_PANEL_ENABLE,1); //读 Settings.Global.getInt(mContext.getContentResolver(),Settings.Global.NOTIFICATION_PANEL_ENABLE, 1)