本文主要是介绍对Android Realm数据库进行加密及版本升级管理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Realm从设计之初便是为适应移动端的使用场景。使用简洁,操作速度快。是一款很不错的移动端嵌入式数据库。
1.基础配置
public class RealmDBConfig {private final static char[] hexArray = "0123456789ABCDEF".toCharArray();static RealmConfiguration realmConfig = null;private static int version = 1; // 数据库版本号/*** 初始化数据库*/public static void setInitRealm(int version) {RealmDBConfig.version= version;if (Realm.getDefaultConfiguration() == null) {Realm.init(MyApplication.getAppContext());}configRealm(version); }private static void configRealm(int version) {ECKey ecKey = ECKey.fromPrivate(OcMath.toBigInt("0abc4301"));byte[] sha256 = Sha256Hash.hash(ecKey.getPubKey());realmConfig = new RealmConfiguration.Builder()//设置数据库升级.migration(migrationDb)//设置数据库密码.encryptionKey(OcMath.toHexStringNoPrefix(sha256).getBytes()) .name("test.realm")//是否允许在UI线程中操作写入数据库.allowWritesOnUiThread(true)//设置数据库版本.schemaVersion(version).build();Realm.setDefaultConfiguration(realmConfig);}public static Realm getRealm() {return Realm.getInstance(getRealmConfiguration());}public static RealmConfiguration getRealmConfiguration() {if (realmConfig == null) {setWalletOCRealm();}return realmConfig;}/*** 数据库版本管理*/protected static RealmMigration migrationDb = new RealmMigration() {//升级数据库@Overridepublic void migrate(DynamicRealm realm, long oldVersion, long newVersion) {RealmSchema schema = realm.getSchema();//给已有表新增字段if (oldVersion == 1) {schema.get("Rm_User").addField("nickname",String.class);}//新增表if (oldVersion == 2) {schema.create("Rm_Order").addField("orderId", String.class).addField("name", String.class).addField("number", int.class);}//删除字段if (oldVersion == 3) {schema.get("Rm_Wallet").removeField("hash", String.class);}//删除表if (oldVersion == 4) {schema.remove("Rm_Contract");}oldVersion++;}};}
这篇关于对Android Realm数据库进行加密及版本升级管理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!