├── .gitignore ├── .idea ├── .gitignore ├── compiler.xml ├── gradle.xml ├── jarRepositories.xml ├── misc.xml └── vcs.xml ├── LICENSE ├── README.md ├── build.gradle ├── example ├── .gitignore ├── [src │ └── main │ │ └── java] │ │ └── com │ │ └── taoweiji │ │ └── kvstorage │ │ └── example │ │ ├── FitStorage.java │ │ └── Storage.java ├── build.gradle ├── cloud_config.yaml ├── fit_storage.yaml ├── proguard-rules.pro ├── src │ ├── androidTest │ │ └── java │ │ │ └── com │ │ │ └── taoweiji │ │ │ └── kvstorage │ │ │ └── ExampleInstrumentedTest.kt │ ├── main │ │ ├── AndroidManifest.xml │ │ ├── java │ │ │ └── com │ │ │ │ └── taoweiji │ │ │ │ └── kvstorage │ │ │ │ └── example │ │ │ │ ├── Account.java │ │ │ │ ├── BrowsingHistory.kt │ │ │ │ ├── CloudConfig.java │ │ │ │ ├── CloudReadOnlyConfig.java │ │ │ │ ├── FitStorage.java │ │ │ │ ├── MainActivity.kt │ │ │ │ ├── MyApplication.java │ │ │ │ └── Storage.java │ │ └── res │ │ │ ├── drawable-v24 │ │ │ └── ic_launcher_foreground.xml │ │ │ ├── drawable │ │ │ └── ic_launcher_background.xml │ │ │ ├── layout │ │ │ └── activity_main.xml │ │ │ ├── mipmap-anydpi-v26 │ │ │ ├── ic_launcher.xml │ │ │ └── ic_launcher_round.xml │ │ │ ├── mipmap-hdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ │ ├── mipmap-mdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ │ ├── mipmap-xhdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ │ ├── mipmap-xxhdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ │ ├── mipmap-xxxhdpi │ │ │ ├── ic_launcher.webp │ │ │ └── ic_launcher_round.webp │ │ │ ├── values-night │ │ │ └── themes.xml │ │ │ └── values │ │ │ ├── colors.xml │ │ │ ├── strings.xml │ │ │ └── themes.xml │ └── test │ │ └── java │ │ └── com │ │ └── taoweiji │ │ └── kvstorage │ │ └── example │ │ ├── CloudReadOnlyMetadataTest.java │ │ └── ExampleUnitTest.kt └── storage.yaml ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── kvstorage-gradle-plugin ├── .gitignore ├── build.gradle └── src │ ├── main │ ├── groovy │ │ └── com │ │ │ └── taoweiji │ │ │ └── kvstorage │ │ │ ├── KVStorageExtension.groovy │ │ │ └── KVStoragePlugin.groovy │ ├── java │ │ └── com │ │ │ └── taoweiji │ │ │ └── kvstorage │ │ │ ├── BuildJavaFile.java │ │ │ ├── ConfigBuilder.java │ │ │ ├── StringUtils.java │ │ │ └── YamlParserHelper.java │ └── resources │ │ └── META-INF │ │ └── gradle-plugins │ │ └── kvstorage.properties │ └── test │ └── java │ └── com │ └── taoweiji │ └── kvstorage │ ├── YamlParserHelperTest.java │ └── YamlTest.java ├── kvstorage-mmkv ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── taoweiji │ │ └── kvstorage │ │ └── mmkv │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── com │ │ └── taoweiji │ │ └── kvstorage │ │ └── mmkv │ │ └── MMKVPreferencesProvider.java │ └── test │ └── java │ └── com │ └── taoweiji │ └── kvstorage │ └── mmkv │ └── ExampleUnitTest.java ├── kvstorage ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── taoweiji │ │ └── kvstorage │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── com │ │ └── taoweiji │ │ └── kvstorage │ │ ├── EncryptMetadata.java │ │ ├── FileMetadata.java │ │ ├── Group.java │ │ ├── GroupData.java │ │ ├── KVStorage.java │ │ ├── ListMetadata.java │ │ ├── Metadata.java │ │ ├── ObjectListMetadata.java │ │ ├── ObjectMetadata.java │ │ ├── PreferencesProvider.java │ │ ├── ReadOnlyConfigGroup.java │ │ ├── ReadOnlyMetadata.java │ │ ├── SetMetadata.java │ │ └── SharedPreferencesProvider.java │ └── test │ └── java │ └── com │ └── taoweiji │ └── kvstorage │ └── ExampleUnitTest.java ├── maven_public.gradle └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | local.properties 16 | /repo -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 23 | 24 | -------------------------------------------------------------------------------- /.idea/jarRepositories.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 14 | 15 | 19 | 20 | 24 | 25 | 29 | 30 | 34 | 35 | 39 | 40 | 44 | 45 | 49 | 50 | 54 | 55 | 59 | 60 | 64 | 65 | 69 | 70 | 74 | 75 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 强大的 Android 结构化KV存储框架,基于 yaml 生成 java 结构化存储类 2 | 3 | [![Maven Central](https://img.shields.io/maven-central/v/io.github.taoweiji.kvstorage/kvstorage)](https://search.maven.org/search?q=io.github.taoweiji.kvstorage) 4 | 5 | 6 | 使用 yaml 配置文件声明键值对的字段名、类型、默认值、是否加密、分组等,通过 Gradle 插件自动生成对象类,让键值对存储的使用变成get/set形式,让代码调用更加安全、优雅。 7 | 8 | - 支持对字段单独加密,避免敏感信息明文存储; 9 | - 通过 yaml 配置存储字段信息,配置简单易懂,一目了然; 10 | - 支持基本类型、对象和列表数据,代替SharePreference及部分SQLite场景; 11 | - 支持自定义文件名,实现多用户之间的数据隔离; 12 | - 支持自定义存储数据源,开发者可以自行实现把部分数据同步到云端; 13 | - 支持自定义存储数据源,提供 [MMKV拓展](#使用-mmkv-作为存储底层) 支持。 14 | - 提供只读参数类生成插件,开发者可以自行实现在线KV参数服务。 15 | 16 | 17 | #### 相对传统KV,结构化KV带来的改进 18 | - 解决传统KV需要定义大量常量字符串KEY_NAME带来的凌乱问题; 19 | - 解决传统KV多个地方使用可能会导致默认值、类型不一致导致的异常问题; 20 | - 解决传统KV部分数据需要对不同用户隔离的实现过于繁琐问题; 21 | - 解决传统KV部分数据需要加密存储的实现过于繁琐问题; 22 | - 解决传统KV存储list/set类型数据时,增删改列表数据需要编写复杂代码问题; 23 | 24 | #### 推荐规范 25 | 26 | - 推荐只使用一个yaml配置文件,放在公共 module 内,方便组件化开发调用; 27 | - 推荐不同的业务划分不同的分组,避免所有的配置都写在一个组内; 28 | - 编写yaml时,所有的字段都应该编写注释,说明其用法; 29 | - bool类型数据不用增加is_前缀,bool类型会默认生成 setXX / isXX 方法; 30 | 31 | ### 编写 yaml 配置文件 32 | 33 | 在公共 module(或 app)目录下创建 yaml 配置文件,比如 storage.yaml 会生成 Storage.java,不同文件名存储数据是隔离的,一旦定好后不建议修改。一个项目无论有多少个 module,都推荐使用一个 yaml 配置文件,放在公共的module里面。 34 | 35 | ```yaml 36 | #storage.yaml 37 | account: 38 | login_account(object,encrypt): #用户登录信息 39 | login_type(string): null #登录方式:qq、weixin、weibo、phone 40 | browsing_history(list): #浏览记录 41 | teenager_mode(bool): false #是否开启青少年模式 42 | current_user_tags(list): #当前用户标签 43 | global: 44 | open_app_num_of_times(int): 0 #打开APP的次数 45 | last_open_app_time(long): 0 #上次打开app时间,13位 46 | tags(set): #标签 47 | ``` 48 | 49 | - 配置文件仅允许使用小写字母、数字、下划线,字段必须使用字母开头。 50 | - 带有括号 `()`是字段,否则就是分组。如上,account 是分组,而login_account、login_time是字段。 51 | - 字段必须在括号`()`内填写类型,仅支持`int`、`long`、`float`、`bool`、`string`、`object`、`list`、`list`、`list`、`list`、`list`、`list`、`set`、`set`、`set`、`set`、`set`、`set`。 52 | - 如果字段需要加密,就需要在括号内填写 `encrypt`,如(object,encrypt)、(int,encrypt)。 53 | 54 | ### 配置 Gradle 55 | 56 | 修改项目根目录的 build.gradle 57 | 58 | ```groovy 59 | buildscript { 60 | repositories { 61 | mavenCentral() 62 | } 63 | dependencies { 64 | classpath 'io.github.taoweiji.kvstorage:kvstorage-gradle-plugin:+' 65 | } 66 | } 67 | ``` 68 | 69 | 修改公共 module(或 app)的 build.gradle 70 | 71 | ```groovy 72 | apply plugin: 'kvstorage' 73 | dependencies { 74 | implementation 'io.github.taoweiji.kvstorage:kvstorage:+' 75 | } 76 | kvstorage { 77 | yamlFiles = ["storage.yaml"] // 配置文件,多个配置文件用","分割 78 | packageName = "com.taoweiji.kvstorage.example" // 生成代码的包名 79 | outputDir = "src/main/java" // 代码生成的目录 80 | } 81 | ``` 82 | 83 | 点击 Gradle sync 即可生成对应的类。 84 | 85 | ### 使用 86 | 87 | ```kotlin 88 | // 在Application进行初始化 89 | KVStorage.init(this) 90 | 91 | // 对象操作 92 | Storage.get().account.loginAccount.setObject(Account(1, "Wiki")) 93 | val account = Storage.get().account.loginAccount.convert(Account::class.java) 94 | Storage.get().account.loginAccount.set("gender", 1) 95 | val name = Storage.get().account.loginAccount.getString("name", "") 96 | Log.e(TAG, "登录用户信息:" + Storage.get().account.loginAccount.data) 97 | 98 | Log.e(TAG, "最后打开APP时间:" + Date(Storage.get().global.lastOpenAppTime)) 99 | Storage.get().global.lastOpenAppTime = System.currentTimeMillis() 100 | 101 | Storage.get().global.openAppNumOfTimes++ 102 | Log.e(TAG, "打开APP次数:${Storage.get().global.openAppNumOfTimes}") 103 | 104 | if (Storage.get().isTeenagerMode) { 105 | Log.e(TAG, "是否开启青少年模式:" + Storage.get().isTeenagerMode) 106 | } 107 | Storage.get().isTeenagerMode = true 108 | 109 | // 列表操作 110 | Storage.get().currentUserTags.add("可爱") 111 | Storage.get().currentUserTags.add("好看") 112 | Log.e(TAG, "当用户标签:" + JSON.toJSONString(Storage.get().currentUserTags.data)) 113 | 114 | Storage.get().browsingHistory.addObject( 115 | BrowsingHistory( 116 | "link", 117 | "http://github.com/taoweiji" 118 | ) 119 | ) 120 | Log.e( 121 | TAG, 122 | "浏览记录:" + JSON.toJSONString(Storage.get().browsingHistory.convert(BrowsingHistory::class.java)) 123 | ) 124 | ``` 125 | 126 | 127 | 128 | ## 高级用法 129 | 130 | ### 自定义文件名,实现多用户存储隔离 131 | 132 | 如果账号支持多用户登录,或者切换账号的时候需要保留上一个账号的信息,可以通过自定义存储的文件名称实现区分。 133 | 134 | ```java 135 | KVStorage.init(this, new KVStorage.Interceptor() { 136 | @Override 137 | public String customFileName(@NonNull String name) { 138 | // 设置 storage.global 全局生效,不对用户隔离 139 | if (name.equals("storage.global")) { 140 | return name; 141 | } 142 | // 默认所有配置都进行用户隔离 143 | String userId = "1234"; 144 | return userId + "_" + name; 145 | } 146 | }); 147 | ``` 148 | 149 | 150 | 151 | ### 自定义对象序列化、反序列化 152 | 153 | 默认使用 FastJson 作为序列化库,开发者可以自定义序列化库,下面是gson的示例。 154 | ```groovy 155 | dependencies { 156 | implementation('io.github.taoweiji.kvstorage:kvstorage:+') { 157 | // 移除 fastjson 依赖 158 | exclude group: 'com.alibaba', module: 'fastjson' 159 | } 160 | implementation 'com.google.code.gson:gson:2.8.6' 161 | } 162 | ``` 163 | 修改初始化 164 | ```java 165 | KVStorage.init(this, new KVStorage.Interceptor() { 166 | @Override 167 | public String toJSONString(@NonNull Object object) { 168 | return new Gson().toJson(object); 169 | } 170 | 171 | @Override 172 | public List parseArray(@NonNull String text, Class clazz) { 173 | Type userListType = new TypeToken>() {}.getType(); 174 | return new Gson().fromJson(text, userListType); 175 | } 176 | 177 | @Override 178 | public T parseObject(@NonNull String text, Class clazz) { 179 | return new Gson().fromJson(text, clazz); 180 | } 181 | }); 182 | ``` 183 | 184 | 185 | 186 | ### 自定义加密/解密算法 187 | 188 | ```yaml 189 | login_account(object,encrypt): #登录信息,加密 190 | ``` 191 | 192 | 通过 `encrypt` 可以对字段进行单独的加密,避免敏感信息明文存储在文件当中,比如密码、手机号码等。框架默认使用 base64作为简单处理,避免明文存储。但是base64并不是一个加密算法,如果需要对字段加密需要自己实现相关接口,推荐官方的 [KeyStore](https://developer.android.google.cn/training/articles/keystore.html)。 193 | 194 | ```java 195 | KVStorage.init(this, new KVStorage.Interceptor() { 196 | @Override 197 | public String decryption(@NonNull String data) { 198 | // TODO 解密 199 | // return new String(Base64.decode(data, Base64.DEFAULT)); 200 | } 201 | 202 | @Override 203 | public String encryption(@NonNull String data) { 204 | // TODO 加密 205 | // return Base64.encodeToString(data.getBytes(), Base64.DEFAULT); 206 | } 207 | }); 208 | ``` 209 | ### 自定义存储数据源:云同步键值对存储服务 210 | 开发者可以自定义存储数据源,比如用来实现本地键值对数据同步到云端,跟随着用户登录的账号,不会随着卸载而丢失,但是与服务端联动的代码需要开发者自行实现。 211 | #### 定义需要同步的分组 212 | ```yaml 213 | #storage.yaml 214 | cloud: 215 | open_comment_push(bool): true #是否开启评论推送 216 | login_divices(list): #登录的设备信息 217 | ``` 218 | #### 自定义存储数据源 219 | ```java 220 | KVStorage.init(this, new KVStorage.Interceptor() { 221 | @Override 222 | public PreferencesAdapter createPreferencesProvider(String fileName) { 223 | if(fileName.equals("storage.cloud")){ 224 | // TODO 针对 storage.cloud 分组自行实现云同步 225 | } 226 | return super.createPreferencesProvider(fileName); 227 | } 228 | }); 229 | ``` 230 | 231 | 232 | ### 自定义存储数据源:使用MMKV作为存储数据源 233 | 234 | 默认是使用 SharedPreferences 作为存储底层,开发者可以自定义存储底层,比如使用 [MMKV](https://github.com/Tencent/MMKV) 作为底层存储,从而获取更高的性能。 235 | 236 | #### 引入 mmkv 拓展 237 | 238 | ```groovy 239 | implementation 'io.github.taoweiji.kvstorage:kvstorage-mmkv:+' 240 | ``` 241 | 242 | #### 初始化 243 | 244 | ```java 245 | MMKV.initialize(this); 246 | 247 | KVStorage.init(this, new KVStorage.Interceptor() { 248 | @Override 249 | public PreferencesAdapter createPreferencesProvider(String fileName) { 250 | // 返回 mmkv 适配器 251 | return new MMKVPreferencesProvider(fileName); 252 | } 253 | }); 254 | ``` 255 | 256 | 这样存储数据源就会改成mmkv,其它用法没有任何差异。 257 | 258 | 259 | ### 只读KV类生成插件:实现在线参数服务 260 | 通常的项目都会有在线参数服务,用于下发参数到客户端,控制客户端的显示逻辑,部分在线参数服务还具备ab测试能力,不同的用户下发不同的参数,比如只让部分用户体验新功能。客户端使用参数服务和键值对存储使用方式类似,不同的是参数服务只允许读取数据。对于一个成熟的APP,必然会大规模使用在线参数服务,就会存在大量的字段名,和键值对一样,如果没有合理使用,也会让代码变得凌乱。KVStorage也提供了解决方案,可以根据yaml配置文件生成相关的工具类,但是后端服务和客户端服务提供还是需要开发者自行实现。 261 | 262 | #### 创建cloud_config.yaml 263 | 264 | 在公共的Module目录下创建cloud_config.yaml,填写对应的自定义,编写规则和 storage 是一样的,也支持分组,config仅支持 int、long、float、bool、string类型。 265 | 266 | ```yaml 267 | # cloud_config.yaml 268 | ad: 269 | launch_app_ads(string): #启动APP广告 270 | launch_app_alert_ads(bool): #启动APP是否显示弹出广告 271 | alert_ads_show_duration(long): 3000 #弹窗广告显示时长,单位:秒 272 | 273 | launch_welcome_message(string): 欢迎使用KVStorage #启动欢迎语 274 | splash_screen_duration(long): 1000 #闪屏时长 275 | home_default_tab_index(int): 0 #首页默认显示第几个tab 276 | ``` 277 | 278 | ##### 修改build.gradle 279 | 280 | ```groovy 281 | apply plugin: 'kvstorage' 282 | dependencies { 283 | implementation 'io.github.taoweiji.kvstorage:kvstorage:+' 284 | } 285 | kvstorage { 286 | packageName = "com.taoweiji.kvstorage.example" // 生成代码的包名 287 | outputDir = "src/main/java" // 代码生成的目录 288 | configYamlFiles = ["cloud_config.yaml"] 289 | } 290 | ``` 291 | 292 | #### 实现数据提供 293 | 294 | 配置服务端的数据提供需要开发者自行实现。 295 | 296 | ```java 297 | KVStorage.setReadOnlyConfigProvider(new KVStorage.ReadOnlyConfigProvider() { 298 | @Override 299 | public int getInt(String groupName, String key, int def) { 300 | // TODO 301 | } 302 | @Override 303 | public float getFloat(String groupName, String key, float def) { 304 | // TODO 305 | } 306 | @Override 307 | public long getLong(String groupName, String key, long def) { 308 | // TODO 309 | } 310 | @Override 311 | public boolean getBool(String groupName, String key, boolean def) { 312 | // TODO 313 | } 314 | @Override 315 | public String getString(String groupName, String key, String def) { 316 | // TODO 317 | } 318 | }); 319 | ``` 320 | 321 | #### 使用 322 | 323 | ```kotlin 324 | if (CloudConfig.get().ad.isLaunchAppAlertAds) { 325 | println("显示弹出广告:" + CloudConfig.get().ad.launchAppAds) 326 | } 327 | ``` 328 | 329 | 330 | 331 | ## License 332 | 333 | Copyright 2021 taoweiji. 334 | 335 | Licensed under the Apache License, Version 2.0 (the "License"); 336 | you may not use this file except in compliance with the License. 337 | You may obtain a copy of the License at 338 | 339 | http://www.apache.org/licenses/LICENSE-2.0 340 | 341 | Unless required by applicable law or agreed to in writing, software 342 | distributed under the License is distributed on an "AS IS" BASIS, 343 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 344 | See the License for the specific language governing permissions and 345 | limitations under the License. 346 | 347 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | buildscript { 3 | repositories { 4 | maven { url uri('./repo') } 5 | google() 6 | mavenCentral() 7 | } 8 | dependencies { 9 | classpath 'com.android.tools.build:gradle:3.5.4' 10 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.0" 11 | classpath 'io.github.taoweiji.kvstorage:kvstorage-gradle-plugin:+' 12 | // NOTE: Do not place your application dependencies here; they belong 13 | // in the individual module build.gradle files 14 | } 15 | } 16 | allprojects { 17 | repositories { 18 | maven { url uri('./repo') } 19 | mavenCentral() 20 | google() 21 | } 22 | } 23 | 24 | task clean(type: Delete) { 25 | delete rootProject.buildDir 26 | } 27 | allprojects { 28 | tasks.withType(Javadoc) { 29 | options.addStringOption('Xdoclint:none', '-quiet') 30 | options.addStringOption('encoding', 'UTF-8') 31 | } 32 | } -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /example/[src/main/java]/com/taoweiji/kvstorage/example/FitStorage.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.example; 2 | 3 | import com.taoweiji.kvstorage.Group; 4 | import com.taoweiji.kvstorage.GroupData; 5 | import com.taoweiji.kvstorage.KVStorage; 6 | import com.taoweiji.kvstorage.ObjectListMetadata; 7 | import com.taoweiji.kvstorage.ObjectMetadata; 8 | import com.taoweiji.kvstorage.SetMetadata; 9 | import java.lang.Override; 10 | import java.lang.String; 11 | 12 | public class FitStorage extends Group { 13 | FitStorage(GroupData data) { 14 | super(data); 15 | } 16 | 17 | public static FitStorage get() { 18 | return new FitStorage(KVStorage.getRootGroupData("fit_storage")); 19 | } 20 | 21 | public long getLastLoginTime() { 22 | return get("last_login_time").getLong(0); 23 | } 24 | 25 | public void setLastLoginTime(long value) { 26 | get("last_login_time").set(value); 27 | } 28 | 29 | public FitStorage.Account getAccount() { 30 | return new FitStorage.Account(createGroupData("account")); 31 | } 32 | 33 | public SetMetadata getLoginUserTags() { 34 | return createSetMetadata("login_user_tags",String.class,false); 35 | } 36 | 37 | public FitStorage.Cloud getCloud() { 38 | return new FitStorage.Cloud(createGroupData("cloud")); 39 | } 40 | 41 | public int getIntType() { 42 | return get("int_type", true).getInt(10); 43 | } 44 | 45 | public void setIntType(int value) { 46 | get("int_type", true).set(value); 47 | } 48 | 49 | public boolean isBoolType() { 50 | return get("bool_type").getBool(true); 51 | } 52 | 53 | public void setBoolType(boolean value) { 54 | get("bool_type").set(value); 55 | } 56 | 57 | public ObjectMetadata getLoginAccount() { 58 | return createObjectMetadata("login_account",true); 59 | } 60 | 61 | public FitStorage.Fit getFit() { 62 | return new FitStorage.Fit(createGroupData("fit")); 63 | } 64 | 65 | public String getString3() { 66 | return get("string3").getString(""); 67 | } 68 | 69 | public void setString3(String value) { 70 | get("string3").set(value); 71 | } 72 | 73 | public String getString1() { 74 | return get("string1").getString("Hello World"); 75 | } 76 | 77 | public void setString1(String value) { 78 | get("string1").set(value); 79 | } 80 | 81 | public String getString2() { 82 | return get("string2").getString(null); 83 | } 84 | 85 | public void setString2(String value) { 86 | get("string2").set(value); 87 | } 88 | 89 | public float getFloatType() { 90 | return get("float_type").getFloat(1.0f); 91 | } 92 | 93 | public void setFloatType(float value) { 94 | get("float_type").set(value); 95 | } 96 | 97 | public float getDoubleType() { 98 | return get("double_type", true).getFloat(2.0f); 99 | } 100 | 101 | public void setDoubleType(float value) { 102 | get("double_type", true).set(value); 103 | } 104 | 105 | public ObjectListMetadata getLoginMomentDrafts() { 106 | return createObjectListMetadata("login_moment_drafts",false); 107 | } 108 | 109 | public long getLongType() { 110 | return get("long_type").getLong(100); 111 | } 112 | 113 | public void setLongType(long value) { 114 | get("long_type").set(value); 115 | } 116 | 117 | public FitStorage.BodyInfo getBodyInfo() { 118 | return new FitStorage.BodyInfo(createGroupData("body_info")); 119 | } 120 | 121 | @Override 122 | public void clear() { 123 | getAccount().clear(); 124 | getCloud().clear(); 125 | getFit().clear(); 126 | getBodyInfo().clear(); 127 | super.clear(); 128 | } 129 | 130 | public class Account extends Group { 131 | Account(GroupData data) { 132 | super(data); 133 | } 134 | 135 | public String getLoginType() { 136 | return get("login_type").getString(null); 137 | } 138 | 139 | public void setLoginType(String value) { 140 | get("login_type").set(value); 141 | } 142 | 143 | public long getLoginTime() { 144 | return get("login_time").getLong(0); 145 | } 146 | 147 | public void setLoginTime(long value) { 148 | get("login_time").set(value); 149 | } 150 | 151 | public ObjectMetadata getLoginAccount() { 152 | return createObjectMetadata("login_account",true); 153 | } 154 | } 155 | 156 | public class Cloud extends Group { 157 | Cloud(GroupData data) { 158 | super(data); 159 | } 160 | 161 | public boolean isEnableBrowsingHistory() { 162 | return get("enable_browsing_history").getBool(true); 163 | } 164 | 165 | public void setEnableBrowsingHistory(boolean value) { 166 | get("enable_browsing_history").set(value); 167 | } 168 | 169 | public boolean isActiveVisible() { 170 | return get("active_visible").getBool(true); 171 | } 172 | 173 | public void setActiveVisible(boolean value) { 174 | get("active_visible").set(value); 175 | } 176 | 177 | public ObjectListMetadata getLoginDevices() { 178 | return createObjectListMetadata("login_devices",false); 179 | } 180 | 181 | public boolean isEnableLocalCity() { 182 | return get("enable_local_city").getBool(true); 183 | } 184 | 185 | public void setEnableLocalCity(boolean value) { 186 | get("enable_local_city").set(value); 187 | } 188 | } 189 | 190 | public class Fit extends Group { 191 | Fit(GroupData data) { 192 | super(data); 193 | } 194 | 195 | public Fit.Body getBody() { 196 | return new Fit.Body(createGroupData("body")); 197 | } 198 | 199 | public ObjectListMetadata getCollect() { 200 | return createObjectListMetadata("collect",false); 201 | } 202 | 203 | @Override 204 | public void clear() { 205 | getBody().clear(); 206 | super.clear(); 207 | } 208 | 209 | public class Body extends Group { 210 | Body(GroupData data) { 211 | super(data); 212 | } 213 | 214 | public int getWeight() { 215 | return get("weight").getInt(0); 216 | } 217 | 218 | public void setWeight(int value) { 219 | get("weight").set(value); 220 | } 221 | 222 | public int getHeight() { 223 | return get("height").getInt(0); 224 | } 225 | 226 | public void setHeight(int value) { 227 | get("height").set(value); 228 | } 229 | } 230 | } 231 | 232 | public class BodyInfo extends Group { 233 | BodyInfo(GroupData data) { 234 | super(data); 235 | } 236 | 237 | public int getGender() { 238 | return get("gender").getInt(0); 239 | } 240 | 241 | public void setGender(int value) { 242 | get("gender").set(value); 243 | } 244 | 245 | public int getWeight() { 246 | return get("weight").getInt(0); 247 | } 248 | 249 | public void setWeight(int value) { 250 | get("weight").set(value); 251 | } 252 | 253 | public int getAge() { 254 | return get("age").getInt(18); 255 | } 256 | 257 | public void setAge(int value) { 258 | get("age").set(value); 259 | } 260 | 261 | public int getHeight() { 262 | return get("height").getInt(0); 263 | } 264 | 265 | public void setHeight(int value) { 266 | get("height").set(value); 267 | } 268 | } 269 | } 270 | -------------------------------------------------------------------------------- /example/[src/main/java]/com/taoweiji/kvstorage/example/Storage.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.example; 2 | 3 | import com.taoweiji.kvstorage.Group; 4 | import com.taoweiji.kvstorage.GroupData; 5 | import com.taoweiji.kvstorage.KVStorage; 6 | import com.taoweiji.kvstorage.ListMetadata; 7 | import com.taoweiji.kvstorage.ObjectListMetadata; 8 | import com.taoweiji.kvstorage.ObjectMetadata; 9 | import com.taoweiji.kvstorage.SetMetadata; 10 | import java.lang.Override; 11 | import java.lang.String; 12 | 13 | public class Storage extends Group { 14 | Storage(GroupData data) { 15 | super(data); 16 | } 17 | 18 | public static Storage get() { 19 | return new Storage(KVStorage.getRootGroupData("storage")); 20 | } 21 | 22 | public Storage.Account getAccount() { 23 | return new Storage.Account(createGroupData("account")); 24 | } 25 | 26 | public boolean isTeenagerMode() { 27 | return get("teenager_mode").getBool(false); 28 | } 29 | 30 | public void setTeenagerMode(boolean value) { 31 | get("teenager_mode").set(value); 32 | } 33 | 34 | public ObjectListMetadata getShippingAddress() { 35 | return createObjectListMetadata("shipping_address",false); 36 | } 37 | 38 | public ObjectListMetadata getBrowsingHistory() { 39 | return createObjectListMetadata("browsing_history",false); 40 | } 41 | 42 | public ListMetadata getCurrentUserTags() { 43 | return createListMetadata("current_user_tags",String.class,false); 44 | } 45 | 46 | public Storage.Global getGlobal() { 47 | return new Storage.Global(createGroupData("global")); 48 | } 49 | 50 | public SetMetadata getTags() { 51 | return createSetMetadata("tags",String.class,false); 52 | } 53 | 54 | @Override 55 | public void clear() { 56 | getAccount().clear(); 57 | getGlobal().clear(); 58 | super.clear(); 59 | } 60 | 61 | public class Account extends Group { 62 | Account(GroupData data) { 63 | super(data); 64 | } 65 | 66 | public String getLoginType() { 67 | return get("login_type").getString(null); 68 | } 69 | 70 | public void setLoginType(String value) { 71 | get("login_type").set(value); 72 | } 73 | 74 | public ObjectMetadata getLoginAccount() { 75 | return createObjectMetadata("login_account",true); 76 | } 77 | } 78 | 79 | public class Global extends Group { 80 | Global(GroupData data) { 81 | super(data); 82 | } 83 | 84 | public int getOpenAppNumOfTimes() { 85 | return get("open_app_num_of_times").getInt(0); 86 | } 87 | 88 | public void setOpenAppNumOfTimes(int value) { 89 | get("open_app_num_of_times").set(value); 90 | } 91 | 92 | public long getLastOpenAppTime() { 93 | return get("last_open_app_time").getLong(0); 94 | } 95 | 96 | public void setLastOpenAppTime(long value) { 97 | get("last_open_app_time").set(value); 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /example/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kvstorage' 4 | 5 | android { 6 | compileSdkVersion 30 7 | defaultConfig { 8 | applicationId "com.taoweiji.storage.example" 9 | minSdkVersion 21 10 | targetSdkVersion 30 11 | versionCode 1 12 | versionName "1.0" 13 | 14 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 15 | } 16 | 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | compileOptions { 24 | sourceCompatibility JavaVersion.VERSION_1_8 25 | targetCompatibility JavaVersion.VERSION_1_8 26 | } 27 | kotlinOptions { 28 | jvmTarget = '1.8' 29 | } 30 | } 31 | 32 | dependencies { 33 | implementation 'androidx.core:core-ktx:1.6.0' 34 | implementation 'androidx.appcompat:appcompat:1.3.1' 35 | implementation 'com.google.android.material:material:1.4.0' 36 | implementation 'androidx.constraintlayout:constraintlayout:2.1.0' 37 | implementation project(path: ':kvstorage') 38 | implementation project(path: ':kvstorage-mmkv') 39 | testImplementation 'junit:junit:4.+' 40 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 41 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 42 | implementation 'com.alibaba:fastjson:1.1.54.android' 43 | implementation 'com.google.code.gson:gson:2.8.6' 44 | } 45 | kvstorage { 46 | yamlFiles = ["storage.yaml", "fit_storage.yaml"] // 配置文件,多个配置文件用","分割 47 | packageName = "com.taoweiji.kvstorage.example" // 生成代码的包名 48 | outputDir = "src/main/java" // 代码生成的目录 49 | configYamlFiles = ["cloud_config.yaml"] 50 | } 51 | -------------------------------------------------------------------------------- /example/cloud_config.yaml: -------------------------------------------------------------------------------- 1 | # cloud_config.yaml 2 | ad: 3 | launch_app_ads(string): #启动APP广告 4 | launch_app_alert_ads(bool): #启动APP是否显示弹出广告 5 | alert_ads_show_duration(long): 3000 #弹窗广告显示时长,单位:秒 6 | 7 | launch_welcome_message(string): 欢迎使用KVStorage #启动欢迎语 8 | splash_screen_duration(long): 1000 #闪屏时长 9 | home_default_tab_index(int): 0 #首页默认显示第几个tab 10 | -------------------------------------------------------------------------------- /example/fit_storage.yaml: -------------------------------------------------------------------------------- 1 | # 会根据文件名称生成相应的文件 2 | login_account(object,encrypt): "" #登录的用户信息 3 | last_login_time(long): 0 #最后登录时间 4 | #login_user_avatar(file): null #登录用户的头像 5 | login_user_tags(set): [] #登录用户标签 6 | login_moment_drafts(list): [] #草稿箱 7 | body_info: 8 | height(int): 0 9 | weight(int): 0 10 | age(int): 18 11 | gender(int): 0 12 | 13 | 14 | 15 | account: 16 | login_account(object,encrypt): #用户登录信息 17 | login_time(long): 0 #最后登录时间 18 | login_type(string): null #登录方式:qq、weixin、weibo、phone 19 | 20 | 21 | fit: 22 | collect(list): 23 | body: 24 | weight(int): 0 25 | height(int): 0 26 | cloud: 27 | login_devices(list,lazy): [] #登录的设备 28 | enable_local_city(bool): true #同城展示 29 | active_visible(bool): true #活跃状态 30 | enable_browsing_history(bool): true #浏览记录 31 | 32 | 33 | int_type(int,encrypt): 10 34 | long_type(long): 100 35 | float_type(float): 1.0 36 | double_type(double,encrypt): 2.0 37 | bool_type(bool): true 38 | string1(string): Hello World 39 | string2(string): null 40 | string3(string): "" 41 | 42 | -------------------------------------------------------------------------------- /example/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /example/src/androidTest/java/com/taoweiji/kvstorage/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("com.taoweiji.storage", appContext.packageName) 23 | } 24 | } -------------------------------------------------------------------------------- /example/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 13 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /example/src/main/java/com/taoweiji/kvstorage/example/Account.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.example; 2 | 3 | public class Account { 4 | 5 | private int id; 6 | private String name; 7 | private int gender; 8 | private boolean momentVisible; 9 | 10 | public Account() { 11 | } 12 | 13 | public Account(int id, String name) { 14 | this.id = id; 15 | this.name = name; 16 | } 17 | 18 | public void setGender(int gender) { 19 | this.gender = gender; 20 | } 21 | 22 | public int getGender() { 23 | return gender; 24 | } 25 | 26 | public boolean isMomentVisible() { 27 | return momentVisible; 28 | } 29 | 30 | public void setMomentVisible(boolean momentVisible) { 31 | this.momentVisible = momentVisible; 32 | } 33 | 34 | public int getId() { 35 | return id; 36 | } 37 | 38 | public void setId(int id) { 39 | this.id = id; 40 | } 41 | 42 | public String getName() { 43 | return name; 44 | } 45 | 46 | public void setName(String name) { 47 | this.name = name; 48 | } 49 | 50 | @Override 51 | public String toString() { 52 | return "Account{" + 53 | "id=" + id + 54 | ", name='" + name + '\'' + 55 | '}'; 56 | } 57 | } -------------------------------------------------------------------------------- /example/src/main/java/com/taoweiji/kvstorage/example/BrowsingHistory.kt: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.example 2 | 3 | class BrowsingHistory { 4 | var name = "" 5 | var link = "" 6 | 7 | constructor(name: String, link: String) { 8 | this.name = name 9 | this.link = link 10 | } 11 | 12 | constructor() { 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /example/src/main/java/com/taoweiji/kvstorage/example/CloudConfig.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.example; 2 | 3 | import com.taoweiji.kvstorage.ReadOnlyConfigGroup; 4 | import java.lang.String; 5 | import java.lang.SuppressWarnings; 6 | 7 | @SuppressWarnings("UnnecessaryLocalVariable") 8 | public class CloudConfig extends ReadOnlyConfigGroup { 9 | CloudConfig(String data) { 10 | super(data); 11 | } 12 | 13 | public static CloudConfig get() { 14 | return new CloudConfig("cloud_config"); 15 | } 16 | 17 | public int getHomeDefaultTabIndex() { 18 | int home_default_tab_index = get("home_default_tab_index").getInt(0); 19 | return home_default_tab_index; 20 | } 21 | 22 | public String getLaunchWelcomeMessage() { 23 | String launch_welcome_message = get("launch_welcome_message").getString("欢迎使用KVStorage"); 24 | return launch_welcome_message; 25 | } 26 | 27 | public long getSplashScreenDuration() { 28 | long splash_screen_duration = get("splash_screen_duration").getLong(1000); 29 | return splash_screen_duration; 30 | } 31 | 32 | public CloudConfig.Ad getAd() { 33 | return new CloudConfig.Ad(createGroup("ad")); 34 | } 35 | 36 | public static class Ad extends ReadOnlyConfigGroup { 37 | Ad(String data) { 38 | super(data); 39 | } 40 | 41 | public boolean isLaunchAppAlertAds() { 42 | boolean launch_app_alert_ads = get("launch_app_alert_ads").getBool(false); 43 | return launch_app_alert_ads; 44 | } 45 | 46 | public String getLaunchAppAds() { 47 | String launch_app_ads = get("launch_app_ads").getString(null); 48 | return launch_app_ads; 49 | } 50 | 51 | public long getAlertAdsShowDuration() { 52 | long alert_ads_show_duration = get("alert_ads_show_duration").getLong(3000); 53 | return alert_ads_show_duration; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /example/src/main/java/com/taoweiji/kvstorage/example/CloudReadOnlyConfig.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.example; 2 | 3 | import com.taoweiji.kvstorage.ReadOnlyConfigGroup; 4 | import java.lang.String; 5 | 6 | public class CloudReadOnlyConfig extends ReadOnlyConfigGroup { 7 | CloudReadOnlyConfig(String data) { 8 | super(data); 9 | } 10 | 11 | public static CloudReadOnlyConfig get() { 12 | return new CloudReadOnlyConfig("cloud_config"); 13 | } 14 | 15 | public int getHomeDefaultTabIndex() { 16 | return get("home_default_tab_index").getInt(0); 17 | } 18 | 19 | public String getLaunchWelcomeMessage() { 20 | return get("launch_welcome_message").getString("欢迎使用KVStorage"); 21 | } 22 | 23 | public long getSplashScreenDuration() { 24 | return get("splash_screen_duration").getLong(1000); 25 | } 26 | 27 | public CloudReadOnlyConfig.Ad getAd() { 28 | return new CloudReadOnlyConfig.Ad(createGroup("ad")); 29 | } 30 | 31 | public class Ad extends ReadOnlyConfigGroup { 32 | Ad(String data) { 33 | super(data); 34 | } 35 | 36 | public boolean isLaunchAppAlertAds() { 37 | return get("launch_app_alert_ads").getBool(false); 38 | } 39 | 40 | public String getLaunchAppAds() { 41 | return get("launch_app_ads").getString(null); 42 | } 43 | 44 | public long getAlertAdsShowDuration() { 45 | return get("alert_ads_show_duration").getLong(3000); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /example/src/main/java/com/taoweiji/kvstorage/example/FitStorage.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.example; 2 | 3 | import com.taoweiji.kvstorage.Group; 4 | import com.taoweiji.kvstorage.GroupData; 5 | import com.taoweiji.kvstorage.KVStorage; 6 | import com.taoweiji.kvstorage.ObjectListMetadata; 7 | import com.taoweiji.kvstorage.ObjectMetadata; 8 | import com.taoweiji.kvstorage.SetMetadata; 9 | import java.lang.Override; 10 | import java.lang.String; 11 | import java.lang.SuppressWarnings; 12 | 13 | @SuppressWarnings("UnnecessaryLocalVariable") 14 | public class FitStorage extends Group { 15 | FitStorage(GroupData data) { 16 | super(data); 17 | } 18 | 19 | public static FitStorage get() { 20 | return new FitStorage(KVStorage.getRootGroupData("fit_storage")); 21 | } 22 | 23 | public long getLastLoginTime() { 24 | long last_login_time = get("last_login_time").getLong(0); 25 | return last_login_time; 26 | } 27 | 28 | public void setLastLoginTime(long value) { 29 | get("last_login_time").set(value); 30 | } 31 | 32 | public FitStorage.Account getAccount() { 33 | return new FitStorage.Account(createGroupData("account")); 34 | } 35 | 36 | public SetMetadata getLoginUserTags() { 37 | SetMetadata login_user_tags = createSetMetadata("login_user_tags",String.class,false); 38 | return login_user_tags; 39 | } 40 | 41 | public FitStorage.Cloud getCloud() { 42 | return new FitStorage.Cloud(createGroupData("cloud")); 43 | } 44 | 45 | public int getIntType() { 46 | int int_type = get("int_type", true).getInt(10); 47 | return int_type; 48 | } 49 | 50 | public void setIntType(int value) { 51 | get("int_type", true).set(value); 52 | } 53 | 54 | public boolean isBoolType() { 55 | boolean bool_type = get("bool_type").getBool(true); 56 | return bool_type; 57 | } 58 | 59 | public void setBoolType(boolean value) { 60 | get("bool_type").set(value); 61 | } 62 | 63 | public ObjectMetadata getLoginAccount() { 64 | ObjectMetadata login_account = createObjectMetadata("login_account",true); 65 | return login_account; 66 | } 67 | 68 | public FitStorage.Fit getFit() { 69 | return new FitStorage.Fit(createGroupData("fit")); 70 | } 71 | 72 | public String getString3() { 73 | String string3 = get("string3").getString(""); 74 | return string3; 75 | } 76 | 77 | public void setString3(String value) { 78 | get("string3").set(value); 79 | } 80 | 81 | public String getString1() { 82 | String string1 = get("string1").getString("Hello World"); 83 | return string1; 84 | } 85 | 86 | public void setString1(String value) { 87 | get("string1").set(value); 88 | } 89 | 90 | public String getString2() { 91 | String string2 = get("string2").getString(null); 92 | return string2; 93 | } 94 | 95 | public void setString2(String value) { 96 | get("string2").set(value); 97 | } 98 | 99 | public float getFloatType() { 100 | float float_type = get("float_type").getFloat(1.0f); 101 | return float_type; 102 | } 103 | 104 | public void setFloatType(float value) { 105 | get("float_type").set(value); 106 | } 107 | 108 | public float getDoubleType() { 109 | float double_type = get("double_type", true).getFloat(2.0f); 110 | return double_type; 111 | } 112 | 113 | public void setDoubleType(float value) { 114 | get("double_type", true).set(value); 115 | } 116 | 117 | public ObjectListMetadata getLoginMomentDrafts() { 118 | ObjectListMetadata login_moment_drafts = createObjectListMetadata("login_moment_drafts",false); 119 | return login_moment_drafts; 120 | } 121 | 122 | public long getLongType() { 123 | long long_type = get("long_type").getLong(100); 124 | return long_type; 125 | } 126 | 127 | public void setLongType(long value) { 128 | get("long_type").set(value); 129 | } 130 | 131 | public FitStorage.BodyInfo getBodyInfo() { 132 | return new FitStorage.BodyInfo(createGroupData("body_info")); 133 | } 134 | 135 | @Override 136 | public void clear() { 137 | getAccount().clear(); 138 | getCloud().clear(); 139 | getFit().clear(); 140 | getBodyInfo().clear(); 141 | super.clear(); 142 | } 143 | 144 | public static class Account extends Group { 145 | Account(GroupData data) { 146 | super(data); 147 | } 148 | 149 | public String getLoginType() { 150 | String login_type = get("login_type").getString(null); 151 | return login_type; 152 | } 153 | 154 | public void setLoginType(String value) { 155 | get("login_type").set(value); 156 | } 157 | 158 | public long getLoginTime() { 159 | long login_time = get("login_time").getLong(0); 160 | return login_time; 161 | } 162 | 163 | public void setLoginTime(long value) { 164 | get("login_time").set(value); 165 | } 166 | 167 | public ObjectMetadata getLoginAccount() { 168 | ObjectMetadata login_account = createObjectMetadata("login_account",true); 169 | return login_account; 170 | } 171 | } 172 | 173 | public static class Cloud extends Group { 174 | Cloud(GroupData data) { 175 | super(data); 176 | } 177 | 178 | public boolean isEnableBrowsingHistory() { 179 | boolean enable_browsing_history = get("enable_browsing_history").getBool(true); 180 | return enable_browsing_history; 181 | } 182 | 183 | public void setEnableBrowsingHistory(boolean value) { 184 | get("enable_browsing_history").set(value); 185 | } 186 | 187 | public boolean isActiveVisible() { 188 | boolean active_visible = get("active_visible").getBool(true); 189 | return active_visible; 190 | } 191 | 192 | public void setActiveVisible(boolean value) { 193 | get("active_visible").set(value); 194 | } 195 | 196 | public ObjectListMetadata getLoginDevices() { 197 | ObjectListMetadata login_devices = createObjectListMetadata("login_devices",false); 198 | return login_devices; 199 | } 200 | 201 | public boolean isEnableLocalCity() { 202 | boolean enable_local_city = get("enable_local_city").getBool(true); 203 | return enable_local_city; 204 | } 205 | 206 | public void setEnableLocalCity(boolean value) { 207 | get("enable_local_city").set(value); 208 | } 209 | } 210 | 211 | public static class Fit extends Group { 212 | Fit(GroupData data) { 213 | super(data); 214 | } 215 | 216 | public Fit.Body getBody() { 217 | return new Fit.Body(createGroupData("body")); 218 | } 219 | 220 | public ObjectListMetadata getCollect() { 221 | ObjectListMetadata collect = createObjectListMetadata("collect",false); 222 | return collect; 223 | } 224 | 225 | @Override 226 | public void clear() { 227 | getBody().clear(); 228 | super.clear(); 229 | } 230 | 231 | public static class Body extends Group { 232 | Body(GroupData data) { 233 | super(data); 234 | } 235 | 236 | public int getWeight() { 237 | int weight = get("weight").getInt(0); 238 | return weight; 239 | } 240 | 241 | public void setWeight(int value) { 242 | get("weight").set(value); 243 | } 244 | 245 | public int getHeight() { 246 | int height = get("height").getInt(0); 247 | return height; 248 | } 249 | 250 | public void setHeight(int value) { 251 | get("height").set(value); 252 | } 253 | } 254 | } 255 | 256 | public static class BodyInfo extends Group { 257 | BodyInfo(GroupData data) { 258 | super(data); 259 | } 260 | 261 | public int getGender() { 262 | int gender = get("gender").getInt(0); 263 | return gender; 264 | } 265 | 266 | public void setGender(int value) { 267 | get("gender").set(value); 268 | } 269 | 270 | public int getWeight() { 271 | int weight = get("weight").getInt(0); 272 | return weight; 273 | } 274 | 275 | public void setWeight(int value) { 276 | get("weight").set(value); 277 | } 278 | 279 | public int getAge() { 280 | int age = get("age").getInt(18); 281 | return age; 282 | } 283 | 284 | public void setAge(int value) { 285 | get("age").set(value); 286 | } 287 | 288 | public int getHeight() { 289 | int height = get("height").getInt(0); 290 | return height; 291 | } 292 | 293 | public void setHeight(int value) { 294 | get("height").set(value); 295 | } 296 | } 297 | } 298 | -------------------------------------------------------------------------------- /example/src/main/java/com/taoweiji/kvstorage/example/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.example 2 | 3 | import androidx.appcompat.app.AppCompatActivity 4 | import android.os.Bundle 5 | import android.util.Log 6 | import com.alibaba.fastjson.JSON 7 | import com.google.gson.Gson 8 | import com.taoweiji.kvstorage.KVStorage 9 | import org.json.JSONObject 10 | import java.util.* 11 | 12 | class MainActivity : AppCompatActivity() { 13 | val TAG = "KVStorage" 14 | 15 | override fun onCreate(savedInstanceState: Bundle?) { 16 | super.onCreate(savedInstanceState) 17 | setContentView(R.layout.activity_main) 18 | 19 | 20 | // 对象操作 21 | Storage.get().account.loginAccount.setObject(Account(1, "Wiki")) 22 | val account = Storage.get().account.loginAccount.convert(Account::class.java) 23 | Storage.get().account.loginAccount.set("gender", 1) 24 | val name = Storage.get().account.loginAccount.getString("name", "") 25 | Log.e(TAG, "登录用户信息:" + Storage.get().account.loginAccount.data) 26 | 27 | Log.e(TAG, "最后打开APP时间:" + Date(Storage.get().global.lastOpenAppTime)) 28 | Storage.get().global.lastOpenAppTime = System.currentTimeMillis() 29 | 30 | Storage.get().global.openAppNumOfTimes++ 31 | Log.e(TAG, "打开APP次数:${Storage.get().global.openAppNumOfTimes}") 32 | 33 | if (Storage.get().isTeenagerMode) { 34 | Log.e(TAG, "是否开启青少年模式:" + Storage.get().isTeenagerMode) 35 | } 36 | Storage.get().isTeenagerMode = true 37 | 38 | // 列表操作 39 | Storage.get().currentUserTags.add("可爱") 40 | Storage.get().currentUserTags.add("好看") 41 | Log.e(TAG, "当用户标签:" + JSON.toJSONString(Storage.get().currentUserTags.data)) 42 | 43 | 44 | 45 | Storage.get().tags.add("tag1") 46 | Storage.get().tags.add("tag2") 47 | Log.e(TAG, "Set标签:" + JSON.toJSONString(Storage.get().tags.data)) 48 | 49 | testObjectList() 50 | } 51 | 52 | private fun testObjectList() { 53 | // Storage.get().browsingHistory.addObject( 54 | // BrowsingHistory( 55 | // "link2", 56 | // "http://github.com/taoweiji" 57 | // ) 58 | // ) 59 | val tmp1 = Storage.get().browsingHistory.findByProperty("name", "link2") 60 | val all = Storage.get().browsingHistory.convert(BrowsingHistory::class.java) 61 | Log.e(TAG, "条件查找:$tmp1") 62 | Log.e(TAG, "转换对象:" + JSON.toJSONString(all)) 63 | uploadException { 64 | 65 | } 66 | } 67 | } 68 | 69 | fun uploadException(runnable: Runnable) { 70 | try { 71 | runnable.run() 72 | } catch (error: Throwable) { 73 | error.printStackTrace() 74 | // TODO 上传异常 75 | } 76 | } -------------------------------------------------------------------------------- /example/src/main/java/com/taoweiji/kvstorage/example/MyApplication.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.example; 2 | 3 | import android.app.Application; 4 | import android.util.Base64; 5 | 6 | import androidx.annotation.NonNull; 7 | 8 | import com.taoweiji.kvstorage.KVStorage; 9 | import com.taoweiji.kvstorage.PreferencesProvider; 10 | import com.taoweiji.kvstorage.mmkv.MMKVPreferencesProvider; 11 | import com.tencent.mmkv.MMKV; 12 | 13 | public class MyApplication extends Application { 14 | @Override 15 | public void onCreate() { 16 | super.onCreate(); 17 | MMKV.initialize(this); 18 | KVStorage.init(this, new KVStorage.Interceptor() { 19 | @NonNull 20 | @Override 21 | public String customFileName(@NonNull String name) { 22 | if (name.equals("storage.global")) { 23 | return name; 24 | } 25 | return "1_" + name; 26 | } 27 | 28 | @Override 29 | public String decryption(@NonNull String data) { 30 | return new String(Base64.decode(data, Base64.DEFAULT)); 31 | } 32 | 33 | @Override 34 | public String encryption(@NonNull String data) { 35 | return Base64.encodeToString(data.getBytes(), Base64.DEFAULT); 36 | } 37 | 38 | @Override 39 | public PreferencesProvider createPreferencesProvider(String fileName) { 40 | return new MMKVPreferencesProvider(fileName); 41 | } 42 | }); 43 | KVStorage.setReadOnlyConfigProvider(readOnlyConfigProvider); 44 | } 45 | 46 | 47 | KVStorage.ReadOnlyConfigProvider readOnlyConfigProvider = new KVStorage.ReadOnlyConfigProvider() { 48 | 49 | @Override 50 | public int getInt(String groupName, String name, int def) { 51 | return def; 52 | } 53 | 54 | @Override 55 | public float getFloat(String groupName, String name, float def) { 56 | return def; 57 | } 58 | 59 | @Override 60 | public long getLong(String groupName, String name, long def) { 61 | return def; 62 | } 63 | 64 | @Override 65 | public boolean getBool(String groupName, String name, boolean def) { 66 | return def; 67 | } 68 | 69 | @Override 70 | public String getString(String groupName, String name, String def) { 71 | return def; 72 | } 73 | }; 74 | } 75 | -------------------------------------------------------------------------------- /example/src/main/java/com/taoweiji/kvstorage/example/Storage.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.example; 2 | 3 | import com.taoweiji.kvstorage.Group; 4 | import com.taoweiji.kvstorage.GroupData; 5 | import com.taoweiji.kvstorage.KVStorage; 6 | import com.taoweiji.kvstorage.ListMetadata; 7 | import com.taoweiji.kvstorage.ObjectListMetadata; 8 | import com.taoweiji.kvstorage.ObjectMetadata; 9 | import com.taoweiji.kvstorage.SetMetadata; 10 | import java.lang.Override; 11 | import java.lang.String; 12 | import java.lang.SuppressWarnings; 13 | 14 | @SuppressWarnings("UnnecessaryLocalVariable") 15 | public class Storage extends Group { 16 | Storage(GroupData data) { 17 | super(data); 18 | } 19 | 20 | public static Storage get() { 21 | return new Storage(KVStorage.getRootGroupData("storage")); 22 | } 23 | 24 | public Storage.Account getAccount() { 25 | return new Storage.Account(createGroupData("account")); 26 | } 27 | 28 | public boolean isTeenagerMode() { 29 | boolean teenager_mode = get("teenager_mode").getBool(false); 30 | return teenager_mode; 31 | } 32 | 33 | public void setTeenagerMode(boolean value) { 34 | get("teenager_mode").set(value); 35 | } 36 | 37 | public ObjectListMetadata getShippingAddress() { 38 | ObjectListMetadata shipping_address = createObjectListMetadata("shipping_address",false); 39 | return shipping_address; 40 | } 41 | 42 | public ObjectListMetadata getBrowsingHistory() { 43 | ObjectListMetadata browsing_history = createObjectListMetadata("browsing_history",false); 44 | return browsing_history; 45 | } 46 | 47 | public ListMetadata getCurrentUserTags() { 48 | ListMetadata current_user_tags = createListMetadata("current_user_tags",String.class,false); 49 | return current_user_tags; 50 | } 51 | 52 | public Storage.Global getGlobal() { 53 | return new Storage.Global(createGroupData("global")); 54 | } 55 | 56 | public SetMetadata getTags() { 57 | SetMetadata tags = createSetMetadata("tags",String.class,false); 58 | return tags; 59 | } 60 | 61 | @Override 62 | public void clear() { 63 | getAccount().clear(); 64 | getGlobal().clear(); 65 | super.clear(); 66 | } 67 | 68 | public static class Account extends Group { 69 | Account(GroupData data) { 70 | super(data); 71 | } 72 | 73 | public String getLoginType() { 74 | String login_type = get("login_type").getString(null); 75 | return login_type; 76 | } 77 | 78 | public void setLoginType(String value) { 79 | get("login_type").set(value); 80 | } 81 | 82 | public ObjectMetadata getLoginAccount() { 83 | ObjectMetadata login_account = createObjectMetadata("login_account",true); 84 | return login_account; 85 | } 86 | } 87 | 88 | public static class Global extends Group { 89 | Global(GroupData data) { 90 | super(data); 91 | } 92 | 93 | public int getOpenAppNumOfTimes() { 94 | int open_app_num_of_times = get("open_app_num_of_times").getInt(0); 95 | return open_app_num_of_times; 96 | } 97 | 98 | public void setOpenAppNumOfTimes(int value) { 99 | get("open_app_num_of_times").set(value); 100 | } 101 | 102 | public long getLastOpenAppTime() { 103 | long last_open_app_time = get("last_open_app_time").getLong(0); 104 | return last_open_app_time; 105 | } 106 | 107 | public void setLastOpenAppTime(long value) { 108 | get("last_open_app_time").set(value); 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /example/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /example/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /example/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 17 | 18 | -------------------------------------------------------------------------------- /example/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /example/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /example/src/main/res/mipmap-hdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taoweiji/KVStorage/d4aa603faf098d5837eb5c848ab80eb69455a61e/example/src/main/res/mipmap-hdpi/ic_launcher.webp -------------------------------------------------------------------------------- /example/src/main/res/mipmap-hdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taoweiji/KVStorage/d4aa603faf098d5837eb5c848ab80eb69455a61e/example/src/main/res/mipmap-hdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /example/src/main/res/mipmap-mdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taoweiji/KVStorage/d4aa603faf098d5837eb5c848ab80eb69455a61e/example/src/main/res/mipmap-mdpi/ic_launcher.webp -------------------------------------------------------------------------------- /example/src/main/res/mipmap-mdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taoweiji/KVStorage/d4aa603faf098d5837eb5c848ab80eb69455a61e/example/src/main/res/mipmap-mdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /example/src/main/res/mipmap-xhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taoweiji/KVStorage/d4aa603faf098d5837eb5c848ab80eb69455a61e/example/src/main/res/mipmap-xhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /example/src/main/res/mipmap-xhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taoweiji/KVStorage/d4aa603faf098d5837eb5c848ab80eb69455a61e/example/src/main/res/mipmap-xhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /example/src/main/res/mipmap-xxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taoweiji/KVStorage/d4aa603faf098d5837eb5c848ab80eb69455a61e/example/src/main/res/mipmap-xxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /example/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taoweiji/KVStorage/d4aa603faf098d5837eb5c848ab80eb69455a61e/example/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /example/src/main/res/mipmap-xxxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taoweiji/KVStorage/d4aa603faf098d5837eb5c848ab80eb69455a61e/example/src/main/res/mipmap-xxxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /example/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taoweiji/KVStorage/d4aa603faf098d5837eb5c848ab80eb69455a61e/example/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /example/src/main/res/values-night/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | -------------------------------------------------------------------------------- /example/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #FFBB86FC 4 | #FF6200EE 5 | #FF3700B3 6 | #FF03DAC5 7 | #FF018786 8 | #FF000000 9 | #FFFFFFFF 10 | -------------------------------------------------------------------------------- /example/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Storage 3 | -------------------------------------------------------------------------------- /example/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | -------------------------------------------------------------------------------- /example/src/test/java/com/taoweiji/kvstorage/example/CloudReadOnlyMetadataTest.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.example; 2 | 3 | import org.junit.Test; 4 | 5 | public class CloudReadOnlyMetadataTest { 6 | @Test 7 | public void test1(){ 8 | if (CloudReadOnlyConfig.get().getAd().isLaunchAppAlertAds()){ 9 | 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /example/src/test/java/com/taoweiji/kvstorage/example/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.example 2 | 3 | import org.junit.Test 4 | 5 | /** 6 | * Example local unit test, which will execute on the development machine (host). 7 | * 8 | * See [testing documentation](http://d.android.com/tools/testing). 9 | */ 10 | class ExampleUnitTest { 11 | @Test 12 | fun addition_isCorrect() { 13 | if (CloudReadOnlyConfig.get().ad.isLaunchAppAlertAds) { 14 | println("显示弹出广告:" + CloudReadOnlyConfig.get().ad.launchAppAds) 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /example/storage.yaml: -------------------------------------------------------------------------------- 1 | account: 2 | login_account(object,encrypt): #用户登录信息 3 | login_type(string): null #登录方式:qq、weixin、weibo、phone 4 | browsing_history(list): #浏览记录 5 | teenager_mode(bool): false #是否开启青少年模式 6 | current_user_tags(list): #当前用户标签 7 | global: 8 | open_app_num_of_times(int): 0 #打开APP的次数 9 | last_open_app_time(long): 0 #上次打开app时间,13位 10 | tags(set): #用户标签 11 | shipping_address(list): #收货地址 12 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | # Kotlin code style for this project: "official" or "obsolete": 21 | kotlin.code.style=official 22 | 23 | GROUP_ID=io.github.taoweiji.kvstorage 24 | VERSION_NAME=0.2.1 25 | POM_NAME=KVStorage 26 | POM_DESCRIPTION=KVStorage for Android 27 | POM_URL=https://github.com/taoweiji/KVStorage 28 | POM_SCM_URL=https://github.com/taoweiji/KVStorage 29 | POM_SCM_CONNECTION=scm:git@github.com:taoweiji/KVStorage.git 30 | POM_SCM_DEV_CONNECTION=scm:git@github.com:taoweiji/KVStorage.git 31 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 32 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 33 | POM_LICENCE_DIST=repo -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taoweiji/KVStorage/d4aa603faf098d5837eb5c848ab80eb69455a61e/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Aug 31 16:30:45 CST 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.9-all.zip 7 | 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /kvstorage-gradle-plugin/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /kvstorage-gradle-plugin/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'groovy' 2 | apply plugin: 'maven' 3 | 4 | sourceCompatibility = JavaVersion.VERSION_1_8 5 | targetCompatibility = JavaVersion.VERSION_1_8 6 | 7 | dependencies { 8 | testImplementation 'junit:junit:4.12' 9 | implementation 'com.alibaba:fastjson:1.1.54.android' 10 | implementation 'org.yaml:snakeyaml:1.17' 11 | implementation 'com.squareup:javapoet:1.11.1' 12 | implementation 'androidx.annotation:annotation:1.2.0' 13 | implementation 'com.android.tools.build:gradle:2.3.3' 14 | implementation gradleApi() 15 | implementation localGroovy() 16 | } 17 | repositories { 18 | jcenter() 19 | google() 20 | mavenCentral() 21 | } 22 | 23 | apply from: '../maven_public.gradle' -------------------------------------------------------------------------------- /kvstorage-gradle-plugin/src/main/groovy/com/taoweiji/kvstorage/KVStorageExtension.groovy: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage 2 | 3 | class KVStorageExtension { 4 | public String[] yamlFiles = [] 5 | public String packageName = null 6 | public String outputDir = null 7 | public String[] configYamlFiles = [] 8 | } -------------------------------------------------------------------------------- /kvstorage-gradle-plugin/src/main/groovy/com/taoweiji/kvstorage/KVStoragePlugin.groovy: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage 2 | 3 | import org.gradle.api.Plugin 4 | import org.gradle.api.Project 5 | import org.gradle.api.Task 6 | 7 | class KVStoragePlugin implements Plugin { 8 | 9 | @Override 10 | void apply(Project project) { 11 | project.extensions.create("kvstorage", KVStorageExtension) 12 | Task task = project.tasks.create("kvstorage") { 13 | println("Creating configuration kvstorage") 14 | doLast { 15 | execute(project) 16 | } 17 | } 18 | // gradle 同步后执行 19 | project.afterEvaluate { 20 | println("kvstorage afterEvaluate") 21 | execute(project) 22 | } 23 | 24 | // project.dependencies { 25 | // api "io.github.taoweiji.kvstorage:kvstorage:1.0.0" 26 | // } 27 | // 28 | // 检查文件的md5是否 29 | } 30 | 31 | private static void execute(Project project) { 32 | if (project.kvstorage == null) { 33 | return 34 | } 35 | println("kvstorage start") 36 | if (project.kvstorage.packageName == null || project.kvstorage.packageName == "") { 37 | new Exception("kvstorage.packageName is empty").printStackTrace() 38 | return 39 | } 40 | def yamlFiles = project.kvstorage.yamlFiles 41 | def configYamlFiles = project.kvstorage.configYamlFiles 42 | def outputDir = project.kvstorage.outputDir 43 | if (outputDir == null) { 44 | outputDir = "src/main/java" 45 | } 46 | def outFile = project.file(outputDir) 47 | if (yamlFiles != null) { 48 | for (def yamlFile : yamlFiles) { 49 | if (yamlFile == "") { 50 | continue 51 | } 52 | def file = project.file(yamlFile) 53 | println("kvstorage execute ${file.getAbsolutePath()}") 54 | def className = new BuildJavaFile().build(file.getAbsolutePath(), project.kvstorage.packageName, outFile.getAbsolutePath()) 55 | println("kvstorage create ${className}") 56 | } 57 | } 58 | if (configYamlFiles != null) { 59 | for (def yamlFile : configYamlFiles) { 60 | if (yamlFile == "") { 61 | continue 62 | } 63 | def file = project.file(yamlFile) 64 | println("kvstorage execute config ${file.getAbsolutePath()}") 65 | def className = new ConfigBuilder().build(file.getAbsolutePath(), project.kvstorage.packageName, outFile.getAbsolutePath()) 66 | println("kvstorage create config ${className}") 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /kvstorage-gradle-plugin/src/main/java/com/taoweiji/kvstorage/BuildJavaFile.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.alibaba.fastjson.JSONObject; 5 | import com.squareup.javapoet.AnnotationSpec; 6 | import com.squareup.javapoet.ClassName; 7 | import com.squareup.javapoet.CodeBlock; 8 | import com.squareup.javapoet.JavaFile; 9 | import com.squareup.javapoet.MethodSpec; 10 | import com.squareup.javapoet.ParameterizedTypeName; 11 | import com.squareup.javapoet.TypeName; 12 | import com.squareup.javapoet.TypeSpec; 13 | 14 | import java.io.File; 15 | import java.io.IOException; 16 | import java.util.Set; 17 | 18 | import javax.lang.model.element.Modifier; 19 | 20 | public class BuildJavaFile { 21 | 22 | public String build(String yamlFile, String packageName, String outFile) throws IOException { 23 | File file = new File(yamlFile); 24 | JSONObject json = YamlParserHelper.parser(file.getAbsolutePath()); 25 | String fileName = file.getName().replace(".yaml", ""); 26 | TypeSpec.Builder typeSpecBuilder = buildTypeSpec(fileName, json, true); 27 | JavaFile javaFile = JavaFile.builder(packageName, typeSpecBuilder.build()).build(); 28 | javaFile.writeTo(new File(outFile)); 29 | String humpName = StringUtils.lineToHump(fileName); 30 | return String.format("%s.%s(%s.java:0)", packageName, humpName, humpName); 31 | } 32 | 33 | ClassName KVStorage = ClassName.get("com.taoweiji.kvstorage", "KVStorage"); 34 | // ClassName FileMetadata = ClassName.get("com.taoweiji.kvstorage", "FileMetadata"); 35 | ClassName Group = ClassName.get("com.taoweiji.kvstorage", "Group"); 36 | ClassName GroupData = ClassName.get("com.taoweiji.kvstorage", "GroupData"); 37 | ClassName ListMetadata = ClassName.get("com.taoweiji.kvstorage", "ListMetadata"); 38 | ClassName SetMetadata = ClassName.get("com.taoweiji.kvstorage", "SetMetadata"); 39 | ClassName Metadata = ClassName.get("com.taoweiji.kvstorage", "Metadata"); 40 | ClassName ObjectMetadata = ClassName.get("com.taoweiji.kvstorage", "ObjectMetadata"); 41 | ClassName ObjectListMetadata = ClassName.get("com.taoweiji.kvstorage", "ObjectListMetadata"); 42 | 43 | public TypeSpec.Builder buildTypeSpec(String name, JSONObject object, boolean root) { 44 | Set keys = object.keySet(); 45 | MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addParameter(GroupData, "data").addCode("super(data);\n"); 46 | TypeSpec.Builder node = TypeSpec.classBuilder(StringUtils.lineToHump(name)) 47 | .addModifiers(Modifier.PUBLIC).superclass(Group).addMethod(constructor.build()); 48 | if (root) { 49 | node.addMethod(MethodSpec.methodBuilder("get") 50 | .returns(ClassName.get("", StringUtils.lineToHump(name))) 51 | .addModifiers(Modifier.PUBLIC, Modifier.STATIC) 52 | .addCode("return new $T($T.getRootGroupData($S));\n", ClassName.get("", StringUtils.lineToHump(name)), KVStorage, name) 53 | .build()); 54 | // @SuppressWarnings("UnnecessaryLocalVariable") 55 | node.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "UnnecessaryLocalVariable").build()); 56 | } else { 57 | node.addModifiers(Modifier.STATIC); 58 | } 59 | CodeBlock.Builder clearCodeBlock = CodeBlock.builder(); 60 | 61 | for (String key : keys) { 62 | if (key.startsWith(":")) { 63 | String readName = key.substring(1); 64 | JSONObject jsonObject = object.getJSONObject(key); 65 | if (jsonObject == null) { 66 | throw new RuntimeException("yaml 异常," + readName + " 没有填写数据类型"); 67 | } 68 | TypeSpec.Builder typeSpecBuilder = buildTypeSpec(readName, (JSONObject) jsonObject, false); 69 | node.addType(typeSpecBuilder.build()); 70 | ClassName className = ClassName.get("", StringUtils.lineToHump(name), StringUtils.lineToHump(readName)); 71 | node.addMethod(MethodSpec.methodBuilder("get" + StringUtils.lineToHump(readName)) 72 | .returns(className) 73 | .addStatement("return new $T(createGroupData($S))", className, readName) 74 | .addModifiers(Modifier.PUBLIC) 75 | .build()); 76 | clearCodeBlock.addStatement("get$L().clear()", StringUtils.lineToHump(readName)); 77 | } else { 78 | 79 | JSONObject item = object.getJSONObject(key); 80 | MethodSpec get = createGetMethodSpec(key, item); 81 | if (get != null) { 82 | node.addMethod(get); 83 | } 84 | MethodSpec set = createSetMethodSpec(key, item); 85 | if (set != null) { 86 | node.addMethod(set); 87 | } 88 | } 89 | } 90 | if (!clearCodeBlock.isEmpty()) { 91 | node.addMethod(MethodSpec.methodBuilder("clear") 92 | .addModifiers(Modifier.PUBLIC) 93 | .addAnnotation(Override.class) 94 | .addCode(clearCodeBlock.addStatement("super.clear()").build()) 95 | .build()); 96 | } 97 | return node; 98 | } 99 | 100 | public MethodSpec createGetMethodSpec(String name, JSONObject item) { 101 | String humpName = StringUtils.lineToHump(name); 102 | String type = item.getString("type"); 103 | boolean encrypt = item.getBooleanValue("encrypt"); 104 | MethodSpec.Builder builder = MethodSpec.methodBuilder("get" + humpName); 105 | String codePart; 106 | if (encrypt) { 107 | codePart = "$T $L = get($S, true)."; 108 | } else { 109 | codePart = "$T $L = get($S)."; 110 | } 111 | TypeName listTypeArguments = null; 112 | switch (type) { 113 | case "int": 114 | int defInt = item.getIntValue("def"); 115 | builder.returns(int.class).addStatement(codePart + "getInt($L)", int.class, name, name, defInt); 116 | break; 117 | case "long": 118 | long defLong = item.getLongValue("def"); 119 | builder.returns(long.class).addStatement(codePart + "getLong($L)", long.class, name, name, defLong); 120 | break; 121 | case "float": 122 | case "double": 123 | float defFloat = item.getFloatValue("def"); 124 | builder.returns(float.class).addStatement(codePart + "getFloat($Lf)", float.class, name, name, defFloat); 125 | break; 126 | case "bool": 127 | case "boolean": 128 | boolean defBool = item.getBooleanValue("def"); 129 | builder = MethodSpec.methodBuilder("is" + humpName); 130 | builder.returns(boolean.class).addStatement(codePart + "getBool($L)", boolean.class, name, name, defBool); 131 | break; 132 | case "string": 133 | String defString = item.getString("def"); 134 | builder.returns(String.class).addStatement(codePart + "getString($S)", String.class, name, name, defString); 135 | break; 136 | case "object": 137 | builder.returns(ObjectMetadata); 138 | builder.addStatement("$T $L = createObjectMetadata($S,$L)", ObjectMetadata, name, name, encrypt); 139 | break; 140 | case "list": 141 | case "list": 142 | builder.returns(ObjectListMetadata); 143 | builder.addStatement("$T $L = createObjectListMetadata($S,$L)", ObjectListMetadata, name, name, encrypt); 144 | break; 145 | case "set": 146 | case "set": 147 | listTypeArguments = ClassName.get("org.json", "JSONObject"); 148 | break; 149 | case "list": 150 | case "set": 151 | listTypeArguments = ClassName.get(Integer.class); 152 | break; 153 | case "list": 154 | case "set": 155 | listTypeArguments = ClassName.get(Long.class); 156 | break; 157 | case "list": 158 | case "set": 159 | listTypeArguments = ClassName.get(Float.class); 160 | break; 161 | case "list": 162 | case "set": 163 | listTypeArguments = ClassName.get(Boolean.class); 164 | break; 165 | case "list": 166 | case "set": 167 | listTypeArguments = ClassName.get(String.class); 168 | break; 169 | 170 | // case "file": 171 | // builder.returns(FileMetadata).addCode("return new $T(get($S));\n", FileMetadata, name); 172 | // break; 173 | default: 174 | throw new RuntimeException("yaml 异常," + name + " 类型错误(" + type + "),仅支持 int、long、float、bool、string、object、list、list、list、list、list、list、set、set、set、set、set、set"); 175 | } 176 | if (listTypeArguments != null) { 177 | if (type.startsWith("set")) { 178 | ParameterizedTypeName typeNames = ParameterizedTypeName.get(SetMetadata, listTypeArguments); 179 | builder.returns(typeNames); 180 | builder.addStatement("$T $L = createSetMetadata($S,$T.class,$L)", typeNames, name, name, listTypeArguments, encrypt); 181 | } else { 182 | ParameterizedTypeName typeNames = ParameterizedTypeName.get(ListMetadata, listTypeArguments); 183 | builder.returns(typeNames); 184 | builder.addStatement("$T $L = createListMetadata($S,$T.class,$L)", typeNames, name, name, listTypeArguments, encrypt); 185 | } 186 | } 187 | return builder.addStatement("return $L", name).addModifiers(Modifier.PUBLIC).build(); 188 | } 189 | 190 | public MethodSpec createSetMethodSpec(String name, JSONObject item) { 191 | String humpName = StringUtils.lineToHump(name); 192 | String type = item.getString("type"); 193 | Object def = item.get("def"); 194 | boolean encrypt = item.getBooleanValue("encrypt"); 195 | MethodSpec.Builder builder = MethodSpec.methodBuilder("set" + humpName); 196 | switch (type) { 197 | case "int": 198 | builder.addParameter(int.class, "value"); 199 | break; 200 | case "long": 201 | builder.addParameter(long.class, "value"); 202 | break; 203 | case "float": 204 | case "double": 205 | builder.addParameter(float.class, "value"); 206 | break; 207 | case "bool": 208 | case "boolean": 209 | builder.addParameter(boolean.class, "value"); 210 | break; 211 | case "string": 212 | builder.addParameter(String.class, "value"); 213 | break; 214 | default: 215 | return null; 216 | } 217 | if (encrypt) { 218 | return builder.addModifiers(Modifier.PUBLIC).addStatement("get($S, true).set(value)", name).build(); 219 | } else { 220 | return builder.addModifiers(Modifier.PUBLIC).addStatement("get($S).set(value)", name).build(); 221 | } 222 | } 223 | } 224 | -------------------------------------------------------------------------------- /kvstorage-gradle-plugin/src/main/java/com/taoweiji/kvstorage/ConfigBuilder.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | import com.squareup.javapoet.AnnotationSpec; 5 | import com.squareup.javapoet.ClassName; 6 | import com.squareup.javapoet.CodeBlock; 7 | import com.squareup.javapoet.JavaFile; 8 | import com.squareup.javapoet.MethodSpec; 9 | import com.squareup.javapoet.ParameterizedTypeName; 10 | import com.squareup.javapoet.TypeName; 11 | import com.squareup.javapoet.TypeSpec; 12 | 13 | import java.io.File; 14 | import java.io.IOException; 15 | import java.util.Set; 16 | 17 | import javax.lang.model.element.Modifier; 18 | 19 | public class ConfigBuilder { 20 | 21 | public String build(String yamlFile, String packageName, String outFile) throws IOException { 22 | File file = new File(yamlFile); 23 | JSONObject json = YamlParserHelper.parser(file.getAbsolutePath()); 24 | String fileName = file.getName().replace(".yaml", ""); 25 | TypeSpec.Builder typeSpecBuilder = buildTypeSpec(fileName, json, true); 26 | JavaFile javaFile = JavaFile.builder(packageName, typeSpecBuilder.build()).build(); 27 | javaFile.writeTo(new File(outFile)); 28 | String humpName = StringUtils.lineToHump(fileName); 29 | return String.format("%s.%s(%s.java:0)", packageName, humpName, humpName); 30 | } 31 | 32 | 33 | ClassName ConfigGroup = ClassName.get("com.taoweiji.kvstorage", "ReadOnlyConfigGroup"); 34 | ClassName Config = ClassName.get("com.taoweiji.kvstorage", "ReadOnlyConfig"); 35 | 36 | public TypeSpec.Builder buildTypeSpec(String name, JSONObject object, boolean root) { 37 | Set keys = object.keySet(); 38 | MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addParameter(String.class, "data").addCode("super(data);\n"); 39 | TypeSpec.Builder node = TypeSpec.classBuilder(StringUtils.lineToHump(name)) 40 | .addModifiers(Modifier.PUBLIC).superclass(ConfigGroup).addMethod(constructor.build()); 41 | if (root) { 42 | node.addMethod(MethodSpec.methodBuilder("get") 43 | .returns(ClassName.get("", StringUtils.lineToHump(name))) 44 | .addModifiers(Modifier.PUBLIC, Modifier.STATIC) 45 | .addCode("return new $T($S);\n", ClassName.get("", StringUtils.lineToHump(name)), name) 46 | .build()); 47 | // @SuppressWarnings("UnnecessaryLocalVariable") 48 | node.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "UnnecessaryLocalVariable").build()); 49 | } else { 50 | node.addModifiers(Modifier.STATIC); 51 | } 52 | 53 | for (String key : keys) { 54 | if (key.startsWith(":")) { 55 | String readName = key.substring(1); 56 | JSONObject jsonObject = object.getJSONObject(key); 57 | if (jsonObject == null) { 58 | throw new RuntimeException("yaml 异常," + readName + " 没有填写数据类型"); 59 | } 60 | TypeSpec.Builder typeSpecBuilder = buildTypeSpec(readName, (JSONObject) jsonObject, false); 61 | node.addType(typeSpecBuilder.build()); 62 | ClassName className = ClassName.get("", StringUtils.lineToHump(name), StringUtils.lineToHump(readName)); 63 | node.addMethod(MethodSpec.methodBuilder("get" + StringUtils.lineToHump(readName)) 64 | .returns(className) 65 | .addStatement("return new $T(createGroup($S))", className, readName) 66 | .addModifiers(Modifier.PUBLIC) 67 | .build()); 68 | } else { 69 | JSONObject item = object.getJSONObject(key); 70 | MethodSpec get = createGetMethodSpec(key, item); 71 | if (get != null) { 72 | node.addMethod(get); 73 | } 74 | } 75 | } 76 | return node; 77 | } 78 | 79 | public MethodSpec createGetMethodSpec(String name, JSONObject item) { 80 | String humpName = StringUtils.lineToHump(name); 81 | String type = item.getString("type"); 82 | 83 | MethodSpec.Builder builder = MethodSpec.methodBuilder("get" + humpName); 84 | String codePart = "$T $L = get($S)."; 85 | 86 | TypeName listTypeArguments = null; 87 | switch (type) { 88 | case "int": 89 | int defInt = item.getIntValue("def"); 90 | builder.returns(int.class).addStatement(codePart + "getInt($L)", int.class, name, name, defInt); 91 | break; 92 | case "long": 93 | long defLong = item.getLongValue("def"); 94 | builder.returns(long.class).addStatement(codePart + "getLong($L)", long.class, name, name, defLong); 95 | break; 96 | case "float": 97 | case "double": 98 | float defFloat = item.getFloatValue("def"); 99 | builder.returns(float.class).addStatement(codePart + "getFloat($Lf)", float.class, name, name, defFloat); 100 | break; 101 | case "bool": 102 | case "boolean": 103 | boolean defBool = item.getBooleanValue("def"); 104 | builder = MethodSpec.methodBuilder("is" + humpName); 105 | builder.returns(boolean.class).addStatement(codePart + "getBool($L)", boolean.class, name, name, defBool); 106 | break; 107 | case "string": 108 | String defString = item.getString("def"); 109 | builder.returns(String.class).addStatement(codePart + "getString($S)", String.class, name, name, defString); 110 | break; 111 | // case "object": 112 | // builder.returns(ObjectMetadata); 113 | // builder.addStatement("return createObjectMetadata($S,$L)", name, encrypt); 114 | // break; 115 | // case "list": 116 | // case "list": 117 | // builder.returns(ObjectListMetadata); 118 | // builder.addStatement("return createObjectListMetadata($S,$L)", name, encrypt); 119 | // break; 120 | case "set": 121 | case "set": 122 | listTypeArguments = ClassName.get("org.json", "JSONObject"); 123 | break; 124 | case "list": 125 | case "set": 126 | listTypeArguments = ClassName.get(Integer.class); 127 | break; 128 | case "list": 129 | case "set": 130 | listTypeArguments = ClassName.get(Long.class); 131 | break; 132 | case "list": 133 | case "set": 134 | listTypeArguments = ClassName.get(Float.class); 135 | break; 136 | case "list": 137 | case "set": 138 | listTypeArguments = ClassName.get(Boolean.class); 139 | break; 140 | case "list": 141 | case "set": 142 | listTypeArguments = ClassName.get(String.class); 143 | break; 144 | 145 | default: 146 | throw new RuntimeException("yaml 异常," + name + " 类型错误(" + type + "),仅支持 int、long、float、bool、string"); 147 | } 148 | // if (listTypeArguments != null) { 149 | // if (type.startsWith("set")) { 150 | // builder.returns(ParameterizedTypeName.get(SetMetadata, listTypeArguments)); 151 | // builder.addStatement("return createSetMetadata($S,$T.class,$L)", name, listTypeArguments, encrypt); 152 | // } else { 153 | // builder.returns(ParameterizedTypeName.get(ListMetadata, listTypeArguments)); 154 | // builder.addStatement("return createListMetadata($S,$T.class,$L)", name, listTypeArguments, encrypt); 155 | // } 156 | // } 157 | return builder.addStatement("return $L", name).addModifiers(Modifier.PUBLIC).build(); 158 | } 159 | 160 | } 161 | -------------------------------------------------------------------------------- /kvstorage-gradle-plugin/src/main/java/com/taoweiji/kvstorage/StringUtils.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | class StringUtils { 7 | private static final Pattern linePattern = Pattern.compile("_(\\w)"); 8 | private static final Pattern humpPattern = Pattern.compile("[A-Z]"); 9 | 10 | /** 11 | * 下划线转驼峰 12 | */ 13 | public static String lineToHump(String str) { 14 | str = str.toLowerCase(); 15 | Matcher matcher = linePattern.matcher(str); 16 | StringBuffer sb = new StringBuffer(); 17 | while (matcher.find()) { 18 | matcher.appendReplacement(sb, matcher.group(1).toUpperCase()); 19 | } 20 | matcher.appendTail(sb); 21 | String result = sb.toString(); 22 | return result.substring(0, 1).toUpperCase() + result.substring(1); 23 | } 24 | public static String lowerLineToHump(String str) { 25 | str = str.toLowerCase(); 26 | Matcher matcher = linePattern.matcher(str); 27 | StringBuffer sb = new StringBuffer(); 28 | while (matcher.find()) { 29 | matcher.appendReplacement(sb, matcher.group(1).toUpperCase()); 30 | } 31 | matcher.appendTail(sb); 32 | String result = sb.toString(); 33 | return result; 34 | } 35 | 36 | /** 37 | * 驼峰转下划线 38 | */ 39 | public static String humpToLine(String str) { 40 | Matcher matcher = humpPattern.matcher(str); 41 | StringBuffer sb = new StringBuffer(); 42 | while (matcher.find()) { 43 | matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase()); 44 | } 45 | matcher.appendTail(sb); 46 | return sb.toString(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /kvstorage-gradle-plugin/src/main/java/com/taoweiji/kvstorage/YamlParserHelper.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import com.alibaba.fastjson.JSONObject; 4 | 5 | import org.yaml.snakeyaml.Yaml; 6 | 7 | import java.io.FileInputStream; 8 | import java.io.FileNotFoundException; 9 | import java.util.Map; 10 | import java.util.Set; 11 | 12 | public class YamlParserHelper { 13 | public static JSONObject parser(String filePath) throws FileNotFoundException { 14 | Yaml yaml = new Yaml(); 15 | Object result = yaml.load(new FileInputStream(filePath)); 16 | return parse(result); 17 | } 18 | 19 | public static JSONObject parse(Object input) { 20 | if (!(input instanceof Map)) { 21 | return null; 22 | } 23 | Map nodes = (Map) input; 24 | JSONObject configs = new JSONObject(); 25 | Set keys = nodes.keySet(); 26 | for (String key : keys) { 27 | if (key.contains("(") && key.contains(")")) { 28 | String name = key.substring(0, key.indexOf("(")); 29 | String argStr = key.substring(key.indexOf("(") + 1, key.indexOf(")")); 30 | String[] args = argStr.split(","); 31 | String type = args[0]; 32 | JSONObject item = new JSONObject(); 33 | // item.put("name", name); 34 | item.put("type", type); 35 | item.put("def", nodes.get(key)); 36 | if (argStr.contains("encrypt")) { 37 | item.put("encrypt", true); 38 | } 39 | configs.put(name, item); 40 | } else { 41 | configs.put(":" + key, parse(nodes.get(key))); 42 | } 43 | } 44 | return configs; 45 | } 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /kvstorage-gradle-plugin/src/main/resources/META-INF/gradle-plugins/kvstorage.properties: -------------------------------------------------------------------------------- 1 | implementation-class=com.taoweiji.kvstorage.KVStoragePlugin -------------------------------------------------------------------------------- /kvstorage-gradle-plugin/src/test/java/com/taoweiji/kvstorage/YamlParserHelperTest.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import org.junit.Test; 4 | 5 | public class YamlParserHelperTest { 6 | 7 | @Test 8 | public void parser() { 9 | } 10 | 11 | @Test 12 | public void parse() { 13 | } 14 | } -------------------------------------------------------------------------------- /kvstorage-gradle-plugin/src/test/java/com/taoweiji/kvstorage/YamlTest.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import org.junit.Test; 4 | 5 | import java.io.IOException; 6 | 7 | public class YamlTest { 8 | @Test 9 | public void parse() throws IOException { 10 | BuildJavaFile buildJavaFile = new BuildJavaFile(); 11 | String className = buildJavaFile.build("/Users/wiki/Documents/source/KVStorage/example/storage.yaml", 12 | "com.taoweiji.kvstorage.example", 13 | "/Users/wiki/Documents/source/KVStorage/example/src/main/java" 14 | ); 15 | System.out.println("创建 " + className); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /kvstorage-mmkv/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /kvstorage-mmkv/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.library' 3 | } 4 | 5 | android { 6 | compileSdkVersion 30 7 | 8 | defaultConfig { 9 | minSdkVersion 16 10 | targetSdkVersion 30 11 | versionCode 1 12 | versionName "1.0" 13 | 14 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 15 | consumerProguardFiles "consumer-rules.pro" 16 | } 17 | 18 | buildTypes { 19 | release { 20 | minifyEnabled false 21 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 22 | } 23 | } 24 | compileOptions { 25 | sourceCompatibility JavaVersion.VERSION_1_8 26 | targetCompatibility JavaVersion.VERSION_1_8 27 | } 28 | } 29 | 30 | dependencies { 31 | implementation 'androidx.appcompat:appcompat:1.3.1' 32 | implementation 'com.google.android.material:material:1.4.0' 33 | testImplementation 'junit:junit:4.+' 34 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 35 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 36 | implementation project(path: ':kvstorage') 37 | api 'com.tencent:mmkv-static:1.2.10' 38 | } 39 | apply from: '../maven_public.gradle' -------------------------------------------------------------------------------- /kvstorage-mmkv/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taoweiji/KVStorage/d4aa603faf098d5837eb5c848ab80eb69455a61e/kvstorage-mmkv/consumer-rules.pro -------------------------------------------------------------------------------- /kvstorage-mmkv/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /kvstorage-mmkv/src/androidTest/java/com/taoweiji/kvstorage/mmkv/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.mmkv; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.platform.app.InstrumentationRegistry; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | assertEquals("com.taoweiji.kvstorage.mmkv.test", appContext.getPackageName()); 25 | } 26 | } -------------------------------------------------------------------------------- /kvstorage-mmkv/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /kvstorage-mmkv/src/main/java/com/taoweiji/kvstorage/mmkv/MMKVPreferencesProvider.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.mmkv; 2 | 3 | import com.taoweiji.kvstorage.PreferencesProvider; 4 | import com.tencent.mmkv.MMKV; 5 | 6 | public class MMKVPreferencesProvider implements PreferencesProvider { 7 | MMKV preferences; 8 | 9 | public MMKVPreferencesProvider(String fileName) { 10 | preferences = MMKV.mmkvWithID(fileName); 11 | } 12 | 13 | @Override 14 | public float getFloat(String key, float def) { 15 | return preferences.getFloat(key, def); 16 | } 17 | 18 | @Override 19 | public boolean getBoolean(String key, boolean def) { 20 | return preferences.getBoolean(key, def); 21 | } 22 | 23 | @Override 24 | public long getLong(String key, long def) { 25 | return preferences.getLong(key, def); 26 | } 27 | 28 | @Override 29 | public int getInt(String key, int def) { 30 | return preferences.getInt(key, def); 31 | } 32 | 33 | @Override 34 | public String getString(String key, String def) { 35 | return preferences.getString(key, def); 36 | } 37 | 38 | @Override 39 | public void putString(String key, String value) { 40 | preferences.edit().putString(key, value).apply(); 41 | } 42 | 43 | @Override 44 | public void putBoolean(String key, boolean value) { 45 | preferences.edit().putBoolean(key, value).apply(); 46 | } 47 | 48 | @Override 49 | public void putFloat(String key, float value) { 50 | preferences.edit().putFloat(key, (float) value).apply(); 51 | } 52 | 53 | @Override 54 | public void putLong(String key, long value) { 55 | preferences.edit().putLong(key, value).apply(); 56 | } 57 | 58 | @Override 59 | public void putInt(String key, int value) { 60 | preferences.edit().putInt(key, value).apply(); 61 | } 62 | 63 | @Override 64 | public void remove(String key) { 65 | preferences.edit().remove(key).apply(); 66 | } 67 | 68 | @Override 69 | public void clear() { 70 | preferences.edit().clear().apply(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /kvstorage-mmkv/src/test/java/com/taoweiji/kvstorage/mmkv/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage.mmkv; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /kvstorage/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /kvstorage/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'maven' 3 | android { 4 | compileSdkVersion 30 5 | defaultConfig { 6 | minSdkVersion 16 7 | targetSdkVersion 30 8 | versionCode 1 9 | versionName "1.0" 10 | 11 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 12 | consumerProguardFiles "consumer-rules.pro" 13 | } 14 | 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 19 | } 20 | } 21 | compileOptions { 22 | sourceCompatibility JavaVersion.VERSION_1_8 23 | targetCompatibility JavaVersion.VERSION_1_8 24 | } 25 | } 26 | 27 | dependencies { 28 | testImplementation 'junit:junit:4.+' 29 | implementation 'androidx.annotation:annotation:1.2.0' 30 | implementation 'com.alibaba:fastjson:1.1.54.android' 31 | } 32 | 33 | apply from: '../maven_public.gradle' -------------------------------------------------------------------------------- /kvstorage/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taoweiji/KVStorage/d4aa603faf098d5837eb5c848ab80eb69455a61e/kvstorage/consumer-rules.pro -------------------------------------------------------------------------------- /kvstorage/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /kvstorage/src/androidTest/java/com/taoweiji/kvstorage/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.platform.app.InstrumentationRegistry; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | assertEquals("com.taoweiji.storage.test", appContext.getPackageName()); 25 | } 26 | } -------------------------------------------------------------------------------- /kvstorage/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /kvstorage/src/main/java/com/taoweiji/kvstorage/EncryptMetadata.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import android.text.TextUtils; 4 | 5 | public class EncryptMetadata extends Metadata { 6 | 7 | protected EncryptMetadata(PreferencesProvider preferences, String name) { 8 | super(preferences, name, false); 9 | } 10 | 11 | private void setEncryptData(Object value) { 12 | if (value == null) { 13 | preferences.remove(key); 14 | return; 15 | } 16 | String data = value.toString(); 17 | String after = KVStorage.encryption(data); 18 | preferences.putString(key, after); 19 | } 20 | 21 | private String getDecryption() { 22 | try { 23 | String data = preferences.getString(key, null); 24 | if (TextUtils.isEmpty(data)) return null; 25 | return KVStorage.decryption(data); 26 | } catch (Exception e) { 27 | e.printStackTrace(); 28 | } 29 | return null; 30 | } 31 | 32 | @Override 33 | public void set(int value) { 34 | setEncryptData(value); 35 | } 36 | 37 | @Override 38 | public void set(long value) { 39 | setEncryptData(value); 40 | } 41 | 42 | @Override 43 | public void set(float value) { 44 | setEncryptData(value); 45 | } 46 | 47 | @Override 48 | public void set(double value) { 49 | setEncryptData(value); 50 | } 51 | 52 | @Override 53 | public void set(boolean value) { 54 | setEncryptData(value); 55 | } 56 | 57 | @Override 58 | public void set(String value) { 59 | setEncryptData(value); 60 | } 61 | 62 | @Override 63 | public String getString(String def) { 64 | String res = getDecryption(); 65 | if (res == null) { 66 | return def; 67 | } else { 68 | return res; 69 | } 70 | } 71 | 72 | @Override 73 | public int getInt(int def) { 74 | String res = getDecryption(); 75 | if (res == null) { 76 | return def; 77 | } 78 | try { 79 | return Integer.parseInt(res); 80 | } catch (Exception e) { 81 | e.printStackTrace(); 82 | } 83 | return def; 84 | } 85 | 86 | @Override 87 | public long getLong(long def) { 88 | String res = getDecryption(); 89 | if (res == null) { 90 | return def; 91 | } 92 | try { 93 | return Long.parseLong(res); 94 | } catch (Exception e) { 95 | e.printStackTrace(); 96 | } 97 | return def; 98 | } 99 | 100 | @Override 101 | public boolean getBool(boolean def) { 102 | String res = getDecryption(); 103 | if (res == null) { 104 | return def; 105 | } 106 | try { 107 | return Boolean.parseBoolean(res); 108 | } catch (Exception e) { 109 | e.printStackTrace(); 110 | } 111 | return def; 112 | } 113 | 114 | @Override 115 | public float getFloat(float def) { 116 | String res = getDecryption(); 117 | if (res == null) { 118 | return def; 119 | } 120 | try { 121 | return Float.parseFloat(res); 122 | } catch (Exception e) { 123 | e.printStackTrace(); 124 | } 125 | return def; 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /kvstorage/src/main/java/com/taoweiji/kvstorage/FileMetadata.java: -------------------------------------------------------------------------------- 1 | //package com.taoweiji.kvstorage; 2 | // 3 | //import java.io.File; 4 | //import java.io.FileInputStream; 5 | //import java.io.FileNotFoundException; 6 | //import java.io.FileOutputStream; 7 | //import java.io.InputStream; 8 | //import java.io.OutputStream; 9 | // 10 | //public class FileMetadata { 11 | // 12 | // private final Metadata metadata; 13 | // private File file; 14 | // 15 | // public FileMetadata(Metadata metadata) { 16 | // this.metadata = metadata; 17 | // } 18 | // 19 | // public void write(String text) { 20 | // 21 | // } 22 | // 23 | // public String readString() { 24 | // return null; 25 | // } 26 | // 27 | // public void write(InputStream is) { 28 | // 29 | // } 30 | // 31 | // public boolean exists() { 32 | // return file.exists(); 33 | // } 34 | // 35 | // public long length() { 36 | // return file.length(); 37 | // } 38 | // 39 | // 40 | // public InputStream getInputStream() throws FileNotFoundException { 41 | // return new FileInputStream(file); 42 | // } 43 | // 44 | // public OutputStream getOutputStream() throws FileNotFoundException { 45 | // return new FileOutputStream(file); 46 | // } 47 | //} -------------------------------------------------------------------------------- /kvstorage/src/main/java/com/taoweiji/kvstorage/Group.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | public class Group { 4 | private final GroupData groupData; 5 | 6 | protected Group(GroupData groupData) { 7 | this.groupData = groupData; 8 | } 9 | 10 | public Metadata get(String key) { 11 | return groupData.get(key, false); 12 | } 13 | 14 | public Metadata get(String key, boolean encrypt) { 15 | return groupData.get(key, encrypt); 16 | } 17 | 18 | protected ListMetadata createListMetadata(String key, Class type, boolean encrypt) { 19 | return groupData.getListMetadata(key, type, encrypt); 20 | } 21 | 22 | protected SetMetadata createSetMetadata(String key, Class type, boolean encrypt) { 23 | return groupData.getSetMetadata(key, type, encrypt); 24 | } 25 | 26 | protected ObjectListMetadata createObjectListMetadata(String key, boolean encrypt) { 27 | return groupData.getObjectListMetadata(key, encrypt); 28 | } 29 | 30 | protected ObjectMetadata createObjectMetadata(String key, boolean encrypt) { 31 | return groupData.getObjectMetadata(key, encrypt); 32 | } 33 | 34 | protected GroupData createGroupData(String key) { 35 | return KVStorage.getGroupData(groupData.name + "." + key); 36 | } 37 | 38 | public void clear() { 39 | groupData.clear(); 40 | } 41 | } -------------------------------------------------------------------------------- /kvstorage/src/main/java/com/taoweiji/kvstorage/GroupData.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import android.util.Log; 4 | import android.util.LruCache; 5 | 6 | public class GroupData { 7 | final String name; 8 | private final PreferencesProvider preferences; 9 | private final LruCache children = new LruCache<>(100); 10 | private final LruCache listMetadataLruCache = new LruCache<>(100); 11 | private final LruCache setMetadataLruCache = new LruCache<>(100); 12 | private final LruCache objectMetadataLruCache = new LruCache<>(100); 13 | 14 | GroupData(String name, String fileName) { 15 | this.name = name; 16 | preferences = KVStorage.createPreferencesAdapter(fileName); 17 | } 18 | 19 | Metadata get(String key, boolean encrypt) { 20 | Metadata result = children.get(key); 21 | if (result == null) { 22 | result = new Metadata(preferences, key, encrypt); 23 | children.put(key, result); 24 | } 25 | return result; 26 | } 27 | 28 | ListMetadata getListMetadata(String key, Class type, boolean encrypt) { 29 | ListMetadata result = listMetadataLruCache.get(key); 30 | if (result == null) { 31 | result = new ListMetadata<>(get(key, encrypt), type); 32 | listMetadataLruCache.put(key, result); 33 | } 34 | return result; 35 | } 36 | 37 | SetMetadata getSetMetadata(String key, Class type, boolean encrypt) { 38 | SetMetadata result = setMetadataLruCache.get(key); 39 | if (result == null) { 40 | result = new SetMetadata<>(get(key, encrypt), type); 41 | setMetadataLruCache.put(key, result); 42 | } 43 | return result; 44 | } 45 | 46 | 47 | ObjectMetadata getObjectMetadata(String key, boolean encrypt) { 48 | ObjectMetadata result = objectMetadataLruCache.get(key); 49 | if (result == null) { 50 | result = new ObjectMetadata(get(key, encrypt)); 51 | objectMetadataLruCache.put(key, result); 52 | } 53 | return result; 54 | } 55 | 56 | public void clear() { 57 | Log.e("KVStorage", name + " clear"); 58 | preferences.clear(); 59 | } 60 | 61 | public ObjectListMetadata getObjectListMetadata(String key, boolean encrypt) { 62 | Object result = listMetadataLruCache.get(key); 63 | if (result instanceof ObjectListMetadata) { 64 | return (ObjectListMetadata) result; 65 | } 66 | ObjectListMetadata objectListMetadata = new ObjectListMetadata(get(key, encrypt)); 67 | listMetadataLruCache.put(key, objectListMetadata); 68 | return objectListMetadata; 69 | } 70 | } -------------------------------------------------------------------------------- /kvstorage/src/main/java/com/taoweiji/kvstorage/KVStorage.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import android.app.Activity; 4 | import android.app.Application; 5 | import android.content.Context; 6 | import android.os.Bundle; 7 | import android.util.Base64; 8 | import android.util.LruCache; 9 | 10 | import androidx.annotation.NonNull; 11 | import androidx.annotation.Nullable; 12 | 13 | import com.alibaba.fastjson.JSON; 14 | 15 | import java.util.List; 16 | 17 | public class KVStorage { 18 | static Application sContext; 19 | static LruCache groupDataMap = new LruCache<>(10); 20 | static Interceptor sInterceptor; 21 | private static ReadOnlyConfigProvider sReadOnlyConfigProvider; 22 | 23 | public static GroupData getRootGroupData(String name) { 24 | return getGroupData(name); 25 | } 26 | 27 | static GroupData getGroupData(String name) { 28 | String fileName = sInterceptor.customFileName(name); 29 | GroupData groupData = groupDataMap.get(fileName); 30 | if (groupData == null) { 31 | groupData = new GroupData(name, fileName); 32 | groupDataMap.put(fileName, groupData); 33 | } 34 | return groupData; 35 | } 36 | 37 | 38 | public static void flush() { 39 | 40 | } 41 | 42 | static Application getContext() { 43 | return sContext; 44 | } 45 | 46 | static T parseObject(String text, Class clazz) { 47 | return sInterceptor.parseObject(text, clazz); 48 | } 49 | 50 | static List parseArray(String text, Class clazz) { 51 | return sInterceptor.parseArray(text, clazz); 52 | } 53 | 54 | static String toJSONString(Object object) { 55 | return sInterceptor.toJSONString(object); 56 | } 57 | 58 | static String encryption(String data) { 59 | return sInterceptor.encryption(data); 60 | } 61 | 62 | static String decryption(String data) { 63 | return sInterceptor.decryption(data); 64 | } 65 | 66 | public static void init(Context context) { 67 | init(context, null); 68 | } 69 | 70 | public static void init(Context context, Interceptor interceptor) { 71 | if (interceptor != null) { 72 | sInterceptor = interceptor; 73 | } 74 | if (sContext != null) { 75 | return; 76 | } 77 | sContext = (Application) context.getApplicationContext(); 78 | sContext.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() { 79 | @Override 80 | public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) { 81 | 82 | } 83 | 84 | @Override 85 | public void onActivityStarted(@NonNull Activity activity) { 86 | 87 | } 88 | 89 | @Override 90 | public void onActivityResumed(@NonNull Activity activity) { 91 | 92 | } 93 | 94 | @Override 95 | public void onActivityPaused(@NonNull Activity activity) { 96 | // 自动保存 97 | KVStorage.flush(); 98 | } 99 | 100 | @Override 101 | public void onActivityStopped(@NonNull Activity activity) { 102 | 103 | } 104 | 105 | @Override 106 | public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) { 107 | 108 | } 109 | 110 | @Override 111 | public void onActivityDestroyed(@NonNull Activity activity) { 112 | 113 | } 114 | }); 115 | } 116 | 117 | static PreferencesProvider createPreferencesAdapter(String fileName) { 118 | return sInterceptor.createPreferencesProvider(fileName); 119 | } 120 | 121 | static ReadOnlyConfigProvider getReadOnlyConfigProvider() { 122 | return sReadOnlyConfigProvider; 123 | } 124 | 125 | public static void setReadOnlyConfigProvider(ReadOnlyConfigProvider readOnlyConfigProvider) { 126 | KVStorage.sReadOnlyConfigProvider = readOnlyConfigProvider; 127 | } 128 | 129 | public interface ReadOnlyConfigProvider { 130 | int getInt(String groupName, String key, int def); 131 | 132 | float getFloat(String groupName, String key, float def); 133 | 134 | long getLong(String groupName, String key, long def); 135 | 136 | boolean getBool(String groupName, String key, boolean def); 137 | 138 | String getString(String groupName, String key, String def); 139 | } 140 | 141 | public static class Interceptor { 142 | 143 | public String encryption(@NonNull String data) { 144 | return Base64.encodeToString(data.getBytes(), Base64.DEFAULT); 145 | } 146 | 147 | public String decryption(@NonNull String data) { 148 | return new String(Base64.decode(data, Base64.DEFAULT)); 149 | } 150 | 151 | /** 152 | * 可以实现多用户隔离数据 153 | */ 154 | @NonNull 155 | public String customFileName(@NonNull String name) { 156 | // return "userId_" + name; 157 | return name; 158 | } 159 | 160 | public T parseObject(@NonNull String text, Class clazz) { 161 | return JSON.parseObject(text, clazz); 162 | } 163 | 164 | public List parseArray(@NonNull String text, Class clazz) { 165 | return JSON.parseArray(text, clazz); 166 | } 167 | 168 | public String toJSONString(@NonNull Object object) { 169 | return JSON.toJSONString(object); 170 | } 171 | 172 | public PreferencesProvider createPreferencesProvider(String fileName) { 173 | return new SharedPreferencesProvider(fileName); 174 | } 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /kvstorage/src/main/java/com/taoweiji/kvstorage/ListMetadata.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import android.text.TextUtils; 4 | 5 | import androidx.annotation.Nullable; 6 | 7 | import org.json.JSONArray; 8 | import org.json.JSONException; 9 | import org.json.JSONObject; 10 | 11 | import java.util.ArrayList; 12 | import java.util.Collection; 13 | import java.util.List; 14 | 15 | public class ListMetadata { 16 | 17 | final Metadata metadata; 18 | private final Class type; 19 | private List data; 20 | 21 | ListMetadata(Metadata metadata, Class type) { 22 | this.metadata = metadata; 23 | this.type = type; 24 | String text = metadata.getString(null); 25 | data = new ArrayList<>(); 26 | if (!TextUtils.isEmpty(text)) { 27 | try { 28 | JSONArray array = new JSONArray(text); 29 | for (int i = 0; i < array.length(); i++) { 30 | if (type == Integer.class) { 31 | data.add((T) Integer.valueOf(array.getInt(i))); 32 | } else if (type == Long.class) { 33 | data.add((T) Long.valueOf(array.getLong(i))); 34 | } else if (type == Float.class) { 35 | data.add((T) Float.valueOf((float) array.getDouble(i))); 36 | } else if (type == Boolean.class) { 37 | data.add((T) Boolean.valueOf(array.getBoolean(i))); 38 | } else if (type == String.class) { 39 | data.add((T) array.getString(i)); 40 | } else if (type == JSONObject.class) { 41 | data.add((T) array.getJSONObject(i)); 42 | } 43 | } 44 | } catch (Exception e) { 45 | e.printStackTrace(); 46 | } 47 | } 48 | } 49 | 50 | public List getData() { 51 | if (data == null) { 52 | data = new ArrayList<>(); 53 | } 54 | return data; 55 | } 56 | 57 | public void setData(List data) { 58 | this.data = data; 59 | flush(); 60 | } 61 | 62 | public void flush() { 63 | if (type == JSONObject.class) { 64 | JSONArray array = new JSONArray(); 65 | for (int i = 0; i < getData().size(); i++) { 66 | JSONObject item = (JSONObject) getData().get(i); 67 | array.put(item); 68 | } 69 | metadata.set(array.toString()); 70 | } else { 71 | metadata.set(KVStorage.toJSONString(getData())); 72 | } 73 | } 74 | 75 | public int size() { 76 | return getData().size(); 77 | } 78 | 79 | public boolean isEmpty() { 80 | return getData().isEmpty(); 81 | } 82 | 83 | public boolean contains(T value) { 84 | return getData().contains(value); 85 | } 86 | 87 | public Object[] toArray() { 88 | return getData().toArray(); 89 | } 90 | 91 | public boolean add(T value) { 92 | boolean res = getData().add(value); 93 | flush(); 94 | return res; 95 | } 96 | 97 | public boolean remove(T value) { 98 | return getData().remove(value); 99 | } 100 | 101 | public boolean addAll(Collection c) { 102 | boolean res = getData().addAll(c); 103 | flush(); 104 | return res; 105 | } 106 | 107 | public boolean addAll(int index, Collection c) { 108 | boolean res = getData().addAll(index, c); 109 | flush(); 110 | return res; 111 | } 112 | 113 | public void clear() { 114 | getData().clear(); 115 | flush(); 116 | } 117 | 118 | public T get(int index) { 119 | return getData().get(index); 120 | } 121 | 122 | public T set(int index, T element) { 123 | T res = getData().set(index, element); 124 | flush(); 125 | return res; 126 | } 127 | 128 | public void add(int index, T element) { 129 | getData().add(index, element); 130 | flush(); 131 | } 132 | 133 | public T remove(int index) { 134 | T res = getData().remove(index); 135 | flush(); 136 | return res; 137 | } 138 | } -------------------------------------------------------------------------------- /kvstorage/src/main/java/com/taoweiji/kvstorage/Metadata.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | public class Metadata { 4 | protected final String key; 5 | private final boolean encrypt; 6 | protected final PreferencesProvider preferences; 7 | protected EncryptMetadata encryptMetadata; 8 | 9 | protected Metadata(PreferencesProvider preferences, String key, boolean encrypt) { 10 | this.preferences = preferences; 11 | this.key = key; 12 | this.encrypt = encrypt; 13 | if (encrypt) { 14 | encryptMetadata = new EncryptMetadata(preferences, key); 15 | } 16 | } 17 | 18 | public void set(int value) { 19 | if (encrypt) { 20 | encryptMetadata.set(value); 21 | return; 22 | } 23 | preferences.putInt(key, value); 24 | } 25 | 26 | public void set(long value) { 27 | if (encrypt) { 28 | encryptMetadata.set(value); 29 | return; 30 | } 31 | preferences.putLong(key, value); 32 | } 33 | 34 | public void set(float value) { 35 | if (encrypt) { 36 | encryptMetadata.set(value); 37 | return; 38 | } 39 | preferences.putFloat(key, value); 40 | } 41 | 42 | public void set(double value) { 43 | if (encrypt) { 44 | encryptMetadata.set(value); 45 | return; 46 | } 47 | preferences.putFloat(key, (float) value); 48 | } 49 | 50 | public void set(boolean value) { 51 | if (encrypt) { 52 | encryptMetadata.set(value); 53 | return; 54 | } 55 | preferences.putBoolean(key, value); 56 | 57 | } 58 | 59 | public void set(String value) { 60 | if (encrypt) { 61 | encryptMetadata.set(value); 62 | return; 63 | } 64 | preferences.putString(key, value); 65 | } 66 | 67 | public String getString(String def) { 68 | if (encrypt) { 69 | return encryptMetadata.getString(def); 70 | } 71 | try { 72 | return preferences.getString(key, def); 73 | } catch (Exception e) { 74 | e.printStackTrace(); 75 | } 76 | return def; 77 | } 78 | 79 | public int getInt(int def) { 80 | if (encrypt) { 81 | return encryptMetadata.getInt(def); 82 | } 83 | try { 84 | return preferences.getInt(key, def); 85 | } catch (Exception e) { 86 | e.printStackTrace(); 87 | } 88 | return def; 89 | } 90 | 91 | public long getLong(long def) { 92 | if (encrypt) { 93 | return encryptMetadata.getLong(def); 94 | } 95 | try { 96 | return preferences.getLong(key, def); 97 | } catch (Exception e) { 98 | e.printStackTrace(); 99 | } 100 | return def; 101 | } 102 | 103 | public boolean getBool(boolean def) { 104 | if (encrypt) { 105 | return encryptMetadata.getBool(def); 106 | } 107 | try { 108 | return preferences.getBoolean(key, def); 109 | } catch (Exception e) { 110 | e.printStackTrace(); 111 | } 112 | return def; 113 | } 114 | 115 | public float getFloat(float def) { 116 | if (encrypt) { 117 | return encryptMetadata.getFloat(def); 118 | } 119 | try { 120 | return preferences.getFloat(key, def); 121 | } catch (Exception e) { 122 | e.printStackTrace(); 123 | } 124 | return def; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /kvstorage/src/main/java/com/taoweiji/kvstorage/ObjectListMetadata.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import androidx.annotation.Nullable; 4 | 5 | import org.json.JSONArray; 6 | import org.json.JSONException; 7 | import org.json.JSONObject; 8 | 9 | import java.util.ArrayList; 10 | import java.util.Iterator; 11 | import java.util.List; 12 | 13 | public class ObjectListMetadata extends ListMetadata { 14 | ObjectListMetadata(Metadata metadata) { 15 | super(metadata, JSONObject.class); 16 | } 17 | 18 | public void addObject(Object element) { 19 | if (element == null) { 20 | return; 21 | } 22 | try { 23 | add(new JSONObject(KVStorage.toJSONString(element))); 24 | } catch (JSONException e) { 25 | e.printStackTrace(); 26 | } 27 | } 28 | 29 | @Nullable 30 | public

List

convert(Class

clazz) { 31 | return KVStorage.parseArray(metadata.getString("[]"), clazz); 32 | } 33 | 34 | public JSONArray findByProperty(String propertyName, Object value) { 35 | JSONArray result = new JSONArray(); 36 | List data = getData(); 37 | for (int i = 0; i < data.size(); i++) { 38 | JSONObject item = data.get(i); 39 | try { 40 | if (value.equals(item.get(propertyName))) { 41 | result.put(item); 42 | } 43 | } catch (JSONException e) { 44 | e.printStackTrace(); 45 | } 46 | } 47 | return result; 48 | } 49 | 50 | public List removeByProperty(String propertyName, Object value) { 51 | List result = new ArrayList<>(); 52 | List data = getData(); 53 | Iterator iterator = data.iterator(); 54 | while (iterator.hasNext()) { 55 | JSONObject item = iterator.next(); 56 | try { 57 | if (value.equals(item.get(propertyName))) { 58 | result.add(item); 59 | iterator.remove(); 60 | } 61 | } catch (JSONException e) { 62 | e.printStackTrace(); 63 | } 64 | } 65 | flush(); 66 | return result; 67 | } 68 | 69 | boolean updateByProperty(JSONObject value) { 70 | return false; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /kvstorage/src/main/java/com/taoweiji/kvstorage/ObjectMetadata.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.annotation.Nullable; 5 | 6 | 7 | import org.json.JSONArray; 8 | import org.json.JSONException; 9 | import org.json.JSONObject; 10 | 11 | 12 | /** 13 | * 如果操作 json 修改字段,框架会自动检查内容是否发生了改变,检查Activity的变化情况自动保存 14 | */ 15 | public class ObjectMetadata { 16 | 17 | private final Metadata metadata; 18 | private JSONObject json; 19 | 20 | ObjectMetadata(Metadata metadata) { 21 | this.metadata = metadata; 22 | } 23 | 24 | public boolean exists() { 25 | return getData().length() > 0; 26 | } 27 | 28 | @NonNull 29 | public JSONObject getData() { 30 | if (json == null) { 31 | String str = metadata.getString("{}"); 32 | try { 33 | json = new JSONObject(str); 34 | } catch (JSONException e) { 35 | e.printStackTrace(); 36 | json = new JSONObject(); 37 | } 38 | } 39 | return json; 40 | } 41 | 42 | public void setData(JSONObject json) { 43 | this.json = json; 44 | flush(); 45 | } 46 | 47 | public void setObject(Object object) { 48 | json = null; 49 | metadata.set(KVStorage.toJSONString(object)); 50 | } 51 | 52 | public void flush() { 53 | metadata.set(getData().toString()); 54 | } 55 | 56 | public void clear() { 57 | json = null; 58 | flush(); 59 | } 60 | 61 | 62 | @NonNull 63 | public ObjectMetadata set(@NonNull String name, Object value) { 64 | try { 65 | getData().putOpt(name, value); 66 | } catch (JSONException e) { 67 | e.printStackTrace(); 68 | } 69 | flush(); 70 | return this; 71 | } 72 | 73 | @Nullable 74 | public Object remove(@Nullable String name) { 75 | return getData().remove(name); 76 | } 77 | 78 | public int getInt(@NonNull String name, int def) { 79 | return getData().optInt(name, def); 80 | } 81 | 82 | public long getLong(@NonNull String name, long def) { 83 | return getData().optLong(name, def); 84 | } 85 | 86 | public double getDouble(@NonNull String name, double def) { 87 | return getData().optDouble(name, def); 88 | } 89 | 90 | public boolean getBool(@NonNull String name, boolean def) { 91 | return getData().optBoolean(name, def); 92 | } 93 | 94 | public String getString(@NonNull String name, String def) { 95 | return getData().optString(name, def); 96 | } 97 | 98 | @Nullable 99 | public JSONArray getJSONArray(@NonNull String name) { 100 | return getData().optJSONArray(name); 101 | } 102 | 103 | @Nullable 104 | public JSONObject getJSONObject(@NonNull String name) { 105 | return getData().optJSONObject(name); 106 | } 107 | 108 | @Nullable 109 | public T convert(Class clazz) { 110 | if (!exists()) { 111 | return null; 112 | } 113 | return KVStorage.parseObject(getData().toString(), clazz); 114 | } 115 | } -------------------------------------------------------------------------------- /kvstorage/src/main/java/com/taoweiji/kvstorage/PreferencesProvider.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | public interface PreferencesProvider { 4 | 5 | float getFloat(String key, float def); 6 | 7 | boolean getBoolean(String key, boolean def); 8 | 9 | long getLong(String key, long def); 10 | 11 | int getInt(String key, int def); 12 | 13 | String getString(String key, String def); 14 | 15 | void putString(String key, String value); 16 | 17 | void putBoolean(String key, boolean value); 18 | 19 | void putFloat(String key, float value); 20 | 21 | void putLong(String key, long value); 22 | 23 | void putInt(String key, int value); 24 | 25 | void remove(String key); 26 | 27 | void clear(); 28 | } 29 | -------------------------------------------------------------------------------- /kvstorage/src/main/java/com/taoweiji/kvstorage/ReadOnlyConfigGroup.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | public class ReadOnlyConfigGroup { 4 | private final String groupName; 5 | 6 | public ReadOnlyConfigGroup(String groupName) { 7 | this.groupName = groupName; 8 | } 9 | 10 | protected String createGroup(String name) { 11 | return groupName + "." + name; 12 | } 13 | 14 | protected ReadOnlyMetadata get(String name) { 15 | return new ReadOnlyMetadata(this.groupName, name); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /kvstorage/src/main/java/com/taoweiji/kvstorage/ReadOnlyMetadata.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | public class ReadOnlyMetadata { 4 | private final String groupName; 5 | private final String key; 6 | 7 | public ReadOnlyMetadata(String groupName, String key) { 8 | this.groupName = groupName; 9 | this.key = key; 10 | } 11 | 12 | public String getString(String def) { 13 | return KVStorage.getReadOnlyConfigProvider().getString(groupName, key, def); 14 | } 15 | 16 | public int getInt(int def) { 17 | return KVStorage.getReadOnlyConfigProvider().getInt(groupName, key, def); 18 | } 19 | 20 | public long getLong(long def) { 21 | return KVStorage.getReadOnlyConfigProvider().getLong(groupName, key, def); 22 | } 23 | 24 | public float getFloat(float def) { 25 | return KVStorage.getReadOnlyConfigProvider().getFloat(groupName, key, def); 26 | } 27 | 28 | public boolean getBool(boolean def) { 29 | return KVStorage.getReadOnlyConfigProvider().getBool(groupName, key, def); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /kvstorage/src/main/java/com/taoweiji/kvstorage/SetMetadata.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import android.os.Build; 4 | import android.text.TextUtils; 5 | 6 | import androidx.annotation.NonNull; 7 | import androidx.annotation.RequiresApi; 8 | 9 | import org.json.JSONArray; 10 | import org.json.JSONObject; 11 | 12 | import java.util.Collection; 13 | import java.util.HashSet; 14 | import java.util.Iterator; 15 | import java.util.Set; 16 | import java.util.function.Consumer; 17 | 18 | public class SetMetadata { 19 | 20 | final Metadata metadata; 21 | private final Class type; 22 | private Set data; 23 | 24 | SetMetadata(Metadata metadata, Class type) { 25 | this.metadata = metadata; 26 | this.type = type; 27 | String text = metadata.getString(null); 28 | data = new HashSet<>(); 29 | if (!TextUtils.isEmpty(text)) { 30 | try { 31 | JSONArray array = new JSONArray(text); 32 | for (int i = 0; i < array.length(); i++) { 33 | if (type == Integer.class) { 34 | data.add((T) Integer.valueOf(array.getInt(i))); 35 | } else if (type == Long.class) { 36 | data.add((T) Long.valueOf(array.getLong(i))); 37 | } else if (type == Float.class) { 38 | data.add((T) Float.valueOf((float) array.getDouble(i))); 39 | } else if (type == Boolean.class) { 40 | data.add((T) Boolean.valueOf(array.getBoolean(i))); 41 | } else if (type == String.class) { 42 | data.add((T) array.getString(i)); 43 | } else if (type == JSONObject.class) { 44 | data.add((T) array.getJSONObject(i)); 45 | } 46 | } 47 | } catch (Exception e) { 48 | e.printStackTrace(); 49 | } 50 | } 51 | } 52 | 53 | public Set getData() { 54 | if (data == null) { 55 | data = new HashSet<>(); 56 | } 57 | return data; 58 | } 59 | 60 | public void setData(Set data) { 61 | this.data = data; 62 | flush(); 63 | } 64 | 65 | public void flush() { 66 | if (type == JSONObject.class) { 67 | JSONArray array = new JSONArray(); 68 | Iterator it = (Iterator) getData().iterator(); 69 | while (it.hasNext()) { 70 | array.put(it.next()); 71 | } 72 | metadata.set(array.toString()); 73 | } else { 74 | metadata.set(KVStorage.toJSONString(getData())); 75 | } 76 | } 77 | 78 | public int size() { 79 | return getData().size(); 80 | } 81 | 82 | public boolean isEmpty() { 83 | return getData().isEmpty(); 84 | } 85 | 86 | public boolean contains(T value) { 87 | return getData().contains(value); 88 | } 89 | 90 | public Object[] toArray() { 91 | return getData().toArray(); 92 | } 93 | 94 | public boolean add(T value) { 95 | boolean res = getData().add(value); 96 | flush(); 97 | return res; 98 | } 99 | 100 | public boolean remove(T value) { 101 | boolean res = getData().remove(value); 102 | flush(); 103 | return res; 104 | } 105 | 106 | 107 | public void clear() { 108 | getData().clear(); 109 | flush(); 110 | } 111 | 112 | @NonNull 113 | public Iterator iterator() { 114 | return getData().iterator(); 115 | } 116 | 117 | @NonNull 118 | public T1[] toArray(@NonNull T1[] a) { 119 | return getData().toArray(a); 120 | } 121 | 122 | public boolean containsAll(@NonNull Collection c) { 123 | return getData().containsAll(c); 124 | } 125 | 126 | public boolean addAll(@NonNull Collection c) { 127 | boolean res = getData().addAll(c); 128 | flush(); 129 | return res; 130 | } 131 | 132 | public boolean removeAll(@NonNull Collection c) { 133 | boolean res = getData().removeAll(c); 134 | flush(); 135 | return res; 136 | } 137 | 138 | @RequiresApi(api = Build.VERSION_CODES.N) 139 | public void forEach(@NonNull Consumer action) { 140 | getData().forEach(action); 141 | } 142 | } -------------------------------------------------------------------------------- /kvstorage/src/main/java/com/taoweiji/kvstorage/SharedPreferencesProvider.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import android.content.Context; 4 | import android.content.SharedPreferences; 5 | 6 | public class SharedPreferencesProvider implements PreferencesProvider { 7 | private final SharedPreferences preferences; 8 | 9 | public SharedPreferencesProvider(String fileName) { 10 | preferences = KVStorage.getContext().getSharedPreferences(fileName, Context.MODE_PRIVATE); 11 | } 12 | 13 | @Override 14 | public float getFloat(String key, float def) { 15 | return preferences.getFloat(key, def); 16 | } 17 | 18 | @Override 19 | public boolean getBoolean(String key, boolean def) { 20 | return preferences.getBoolean(key, def); 21 | } 22 | 23 | @Override 24 | public long getLong(String key, long def) { 25 | return preferences.getLong(key, def); 26 | } 27 | 28 | @Override 29 | public int getInt(String key, int def) { 30 | return preferences.getInt(key, def); 31 | } 32 | 33 | @Override 34 | public String getString(String key, String def) { 35 | return preferences.getString(key, def); 36 | } 37 | 38 | @Override 39 | public void putString(String key, String value) { 40 | preferences.edit().putString(key, value).apply(); 41 | } 42 | 43 | @Override 44 | public void putBoolean(String key, boolean value) { 45 | preferences.edit().putBoolean(key, value).apply(); 46 | } 47 | 48 | @Override 49 | public void putFloat(String key, float value) { 50 | preferences.edit().putFloat(key, (float) value).apply(); 51 | } 52 | 53 | @Override 54 | public void putLong(String key, long value) { 55 | preferences.edit().putLong(key, value).apply(); 56 | } 57 | 58 | @Override 59 | public void putInt(String key, int value) { 60 | preferences.edit().putInt(key, value).apply(); 61 | } 62 | 63 | @Override 64 | public void remove(String key) { 65 | preferences.edit().remove(key).apply(); 66 | } 67 | 68 | @Override 69 | public void clear() { 70 | preferences.edit().clear().apply(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /kvstorage/src/test/java/com/taoweiji/kvstorage/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.taoweiji.kvstorage; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /maven_public.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'maven' 2 | group = GROUP_ID 3 | version = VERSION_NAME 4 | 5 | // 发布到本地仓库,方便测试 6 | uploadArchives { 7 | repositories { 8 | mavenDeployer { 9 | repository(url: uri('../repo')) 10 | } 11 | } 12 | } 13 | return 14 | 15 | apply plugin: 'signing' 16 | signing { 17 | sign configurations.archives 18 | } 19 | boolean isAndroid = project.getPlugins().hasPlugin('com.android.library') 20 | if (isAndroid) { 21 | task androidJavadocs(type: Javadoc) { 22 | source = android.sourceSets.main.java.source 23 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 24 | excludes = ['**/*.kt'] 25 | } 26 | task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { 27 | classifier = 'javadoc' 28 | from androidJavadocs.destinationDir 29 | } 30 | task androidSourcesJar(type: Jar) { 31 | classifier = 'sources' 32 | from android.sourceSets.main.java.source 33 | } 34 | } else { 35 | task javadocJar(type: Jar) { 36 | classifier = 'javadoc' 37 | from javadoc 38 | } 39 | task sourcesJar(type: Jar) { 40 | classifier = 'sources' 41 | from sourceSets.main.allSource 42 | } 43 | artifacts { 44 | archives javadocJar, sourcesJar 45 | } 46 | } 47 | 48 | signing { 49 | // keyId = "0945148C" 50 | // password = "Tao408191243." 51 | // secretKeyRingFile = "/Users/wiki/.gnupg/secring.gpg" 52 | } 53 | 54 | 55 | uploadArchives { 56 | repositories { 57 | mavenDeployer { 58 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 59 | repository(url: "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/") { 60 | authentication(userName: OSSRH_USERNAME, password: OSSRH_PASSWORD) 61 | } 62 | snapshotRepository(url: "https://s01.oss.sonatype.org/content/repositories/snapshots/") { 63 | authentication(userName: OSSRH_USERNAME, password: OSSRH_PASSWORD) 64 | } 65 | pom.project { 66 | name POM_NAME 67 | packaging isAndroid ? 'jar' : 'aar' 68 | description POM_DESCRIPTION 69 | url POM_URL 70 | scm { 71 | connection POM_SCM_CONNECTION 72 | developerConnection POM_SCM_DEV_CONNECTION 73 | url POM_SCM_URL 74 | } 75 | licenses { 76 | license { 77 | name POM_LICENCE_NAME 78 | url POM_LICENCE_URL 79 | } 80 | } 81 | developers { 82 | developer { 83 | id POM_DEVELOPER_ID 84 | name POM_DEVELOPER_NAME 85 | email POM_DEVELOPER_EMAIL 86 | } 87 | } 88 | } 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | //dependencyResolutionManagement { 2 | // repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 3 | // repositories { 4 | // google() 5 | // mavenCentral() 6 | // jcenter() // Warning: this repository is going to shut down soon 7 | // } 8 | //} 9 | rootProject.name = "KVStorage" 10 | include ':example' 11 | include ':kvstorage-gradle-plugin' 12 | include ':kvstorage' 13 | include ':kvstorage-mmkv' 14 | --------------------------------------------------------------------------------