├── .gitignore
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── aranandroid
│ │ └── mvvm
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── assets
│ │ └── litepal.xml
│ ├── java
│ │ └── com
│ │ │ └── aranandroid
│ │ │ └── mvvm
│ │ │ ├── BaseApplication.kt
│ │ │ ├── data
│ │ │ ├── PlaceRepository.kt
│ │ │ ├── Resource.kt
│ │ │ ├── WeatherRepository.kt
│ │ │ ├── db
│ │ │ │ ├── ExampleDatabase.kt
│ │ │ │ ├── PlaceDao.kt
│ │ │ │ └── WeatherDao.kt
│ │ │ ├── model
│ │ │ │ ├── place
│ │ │ │ │ ├── City.kt
│ │ │ │ │ ├── County.kt
│ │ │ │ │ └── Province.kt
│ │ │ │ └── weather
│ │ │ │ │ ├── AQI.kt
│ │ │ │ │ ├── Basic.kt
│ │ │ │ │ ├── Forecast.kt
│ │ │ │ │ ├── HeWeather.kt
│ │ │ │ │ ├── Now.kt
│ │ │ │ │ ├── Suggestion.kt
│ │ │ │ │ └── Weather.kt
│ │ │ └── network
│ │ │ │ ├── ExampleNetwork.kt
│ │ │ │ └── api
│ │ │ │ ├── PlaceService.kt
│ │ │ │ └── WeatherService.kt
│ │ │ ├── ui
│ │ │ ├── MainActivity.kt
│ │ │ ├── MainViewModel.kt
│ │ │ ├── area
│ │ │ │ ├── ChooseAreaAdapter.kt
│ │ │ │ ├── ChooseAreaFragment.kt
│ │ │ │ └── ChooseAreaViewModel.kt
│ │ │ └── weather
│ │ │ │ ├── WeatherActivity.kt
│ │ │ │ └── WeatherViewModel.kt
│ │ │ └── util
│ │ │ └── BindingAdapters.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable-xxhdpi
│ │ ├── ic_back.png
│ │ └── ic_home.png
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ ├── activity_weather.xml
│ │ ├── aqi.xml
│ │ ├── choose_area.xml
│ │ ├── forecast.xml
│ │ ├── forecast_item.xml
│ │ ├── now.xml
│ │ ├── simple_item.xml
│ │ ├── suggestion.xml
│ │ └── title.xml
│ │ ├── mipmap-hdpi
│ │ └── logo.png
│ │ ├── mipmap-mdpi
│ │ └── logo.png
│ │ ├── mipmap-xhdpi
│ │ └── logo.png
│ │ ├── mipmap-xxhdpi
│ │ └── logo.png
│ │ ├── mipmap-xxxhdpi
│ │ └── logo.png
│ │ ├── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ │ └── xml
│ │ └── network_security_config.xml
│ └── test
│ └── java
│ └── com
│ └── aranandroid
│ └── mvvm
│ └── ExampleUnitTest.kt
├── build.gradle
├── frist.patch
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── images
├── Screenshot_1.png
├── Screenshot_2.png
└── architecture.jpg
├── mvvm
├── .gitignore
├── build.gradle
├── consumer-rules.pro
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── aranandroid
│ │ └── mvvm
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── aranandroid
│ │ │ └── mvvm
│ │ │ ├── MvvmApplication.kt
│ │ │ ├── base
│ │ │ ├── factory
│ │ │ │ └── BaseRepository.kt
│ │ │ ├── m
│ │ │ │ └── BaseViewModel.kt
│ │ │ └── vm
│ │ │ │ ├── BaseActivity.kt
│ │ │ │ ├── BaseFragment.kt
│ │ │ │ └── BaseFragmentActivity.kt
│ │ │ ├── live
│ │ │ ├── AliveManager.kt
│ │ │ ├── AliveReceiver.kt
│ │ │ ├── AliveScreenActivity.kt
│ │ │ ├── EmptyActivity.kt
│ │ │ └── ForgroundService.kt
│ │ │ ├── network
│ │ │ ├── BaseNetwork.kt
│ │ │ └── ServiceCreator.kt
│ │ │ ├── permission
│ │ │ └── PermissonDialog.kt
│ │ │ └── util
│ │ │ ├── ActivityLifeCycleCallBackIml.java
│ │ │ ├── AppManager.java
│ │ │ └── BaseExecutors.kt
│ └── res
│ │ ├── anim
│ │ ├── slide_in_left.xml
│ │ ├── slide_in_right.xml
│ │ ├── slide_in_zoom.xml
│ │ ├── slide_out_left.xml
│ │ ├── slide_out_right.xml
│ │ └── slide_out_zoom.xml
│ │ ├── drawable
│ │ ├── custom_dialog_bg.xml
│ │ ├── negative_button_bg.xml
│ │ └── positive_button_bg.xml
│ │ ├── layout
│ │ ├── custom_dialog_layout.xml
│ │ └── permissions_item.xml
│ │ ├── mipmap
│ │ └── ic_launcher.png
│ │ └── values
│ │ ├── styles.xml
│ │ └── themes.xml
│ └── test
│ └── java
│ └── com
│ └── aranandroid
│ └── mvvm
│ └── ExampleUnitTest.kt
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | # IntelliJ
36 | *.iml
37 | .idea/workspace.xml
38 | .idea/tasks.xml
39 | .idea/gradle.xml
40 | .idea/assetWizardSettings.xml
41 | .idea/dictionaries
42 | .idea/libraries
43 | .idea/caches
44 |
45 | # Keystore files
46 | # Uncomment the following line if you do not want to check your keystore files in.
47 | #*.jks
48 |
49 | # External native build folder generated in Android Studio 2.2 and later
50 | .externalNativeBuild
51 |
52 | # Google Services (e.g. APIs or Firebase)
53 | google-services.json
54 |
55 | # Freeline
56 | freeline.py
57 | freeline/
58 | freeline_project_description.json
59 |
60 | # fastlane
61 | fastlane/report.xml
62 | fastlane/Preview.html
63 | fastlane/screenshots
64 | fastlane/test_output
65 | fastlane/readme.md
66 |
67 | /.idea
--------------------------------------------------------------------------------
/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 | # 酷欧天气Jetpack版
2 | 酷欧天气的Jetpack版本实现,采用了MVVM架构。
3 |
4 | ## mvvm使用(mvvm被封装成框架包)
5 |
6 | *build.gradle(主项目):
7 |
8 | maven { url 'https://jitpack.io' }
9 |
10 | *build.gradle(app):
11 |
12 | implementation 'com.github.AranAndroid009:Mvvm:1.0.1'
13 |
14 | *网络初始化用:
15 |
16 | 继承 MvvmApplication 然后 ServiceCreator.init("http://guolin.tech/")
17 |
18 | *数据库使用:
19 |
20 | assets文件下创建xml
21 |
22 | 案例:
23 | ```
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 | ```
33 | #mvvm三部曲:
34 |
35 | *m:
36 |
37 | class ExampleModel : BaseViewModel()
38 |
39 | *v:
40 | ```
41 |
43 |
44 |
45 |
46 |
47 |
50 |
51 |
52 | ```
53 | *mv:
54 | ```
55 | class ExampleActivity :
56 | BaseActivity(R.layout.activity_example) {
57 | override fun onCreate(savedInstanceState: Bundle?) {
58 | super.onCreate(savedInstanceState)
59 | // 必写
60 | binding.viewModel = viewModel
61 | // 必写
62 | binding.lifecycleOwner = this
63 | }
64 | }
65 |
66 | 注意:
67 | app的build.gradle中android {}里边
68 | dataBinding {
69 | enabled true
70 | }
71 | ```
72 |
73 | 这里我先给出一张酷欧天气Jetpack版的架构设计图,这张图是模仿Google Codelabs的Sunshine项目画出来的。拥有良好架构设计的项目都是可以用简洁清晰的架构图表示出来的,而一个杂乱无章没有架构设计的项目则很难用架构图表示出来。
74 |
75 |
76 |
77 | 上述架构图可能一开始看你会找不着重点,其实这张架构图非常清晰,我来带大家解读一下。
78 |
79 | 首先我们通过这张架构图成功将程序分为了若干层。
80 |
81 | 绿色部分表示的是UI控制层,这部分就是我们平时写的Activity和Fragment。
82 |
83 | 蓝色部分表示的是ViewModel层,ViewModel用于持有和UI元素相关的数据,以保证这些数据在屏幕旋转时不会丢失,以及负责和仓库之间进行通讯。
84 |
85 | 黄色部分表示的是仓库层,仓库层要做的工作是自主判断接口请求的数据应该是从数据库中读取还是从网络中获取,并将数据返回给调用方。如果是从网络中获取的话还要将这些数据存入到数据库当中,以避免下次重复从网络中获取。简而言之,仓库的工作就是在本地和网络数据之间做一个分配和调度的工作,调用方不管你的数据是从何而来的,我只是要从你仓库这里获取数据而已,而仓库则要自主分配如何更好更快地将数据提供给调用方。
86 |
87 | 接下来灰色部分表示是的本地数据层,实现方式并不固定,我使用了LitePal来进行数据持久化处理,你也可以使用别的框架。
88 |
89 | 最后红色部分表示的是网络数据层,这里使用了Retrofit从web服务接口获取数据。
90 |
91 | 借助这张架构图,我想会在很大程度上便于大家理解酷欧天气Jetpack版这个开源项目,而如果你自己编写的项目也能尝试画出这样一张架构图,那么你的代码结构一定是非常不错的。
92 |
93 | 另外对于这张架构图我还有必要再解释一下,图中所有的箭头都是单向的,比方说WeatherActivity指向了WeatherViewModel,表示WeatherActivity持有WeatherViewModel的引用,但是反过来WeatherViewModel不能持有WeatherActivity的引用。其他的几层也是一样的道理,一个箭头就表示持有一个引用。
94 |
95 | 还有,引用不能跨层持有,就比方说UI控制层不能持有仓库层的引用,每一层的组件都只能和它的相邻层交互。
96 |
97 | 大概就介绍这么多吧,剩下的就靠大家自己去阅读源码进行学习了。
98 |
99 | 项目运行截图如下:
100 |
101 |
102 |
103 | 最后,希望这个项目能够帮助大家更好地学习Jetpack,更好地学习MVVM架构。
104 |
105 |
106 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | apply plugin: 'kotlin-android'
4 |
5 | apply plugin: 'kotlin-android-extensions'
6 |
7 | apply plugin: 'kotlin-kapt'
8 |
9 | android {
10 | compileSdkVersion 28
11 | defaultConfig {
12 | applicationId "com.aranandroid.mvvm"
13 | minSdkVersion 21
14 | targetSdkVersion 28
15 | versionCode 1
16 | versionName "1.0"
17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
18 | }
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 | dataBinding {
26 | enabled true
27 | }
28 | }
29 |
30 | dependencies {
31 | implementation fileTree(dir: 'libs', include: ['*.jar'])
32 | implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
33 |
34 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1'
35 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1'
36 |
37 | implementation 'androidx.appcompat:appcompat:1.1.0-alpha03'
38 | implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha3'
39 | implementation project(path: ':mvvm')
40 | implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.0.0'
41 | testImplementation 'junit:junit:4.12'
42 | androidTestImplementation 'androidx.test:runner:1.1.1'
43 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
44 |
45 | implementation 'com.github.bumptech.glide:glide:3.7.0'
46 |
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/app/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
22 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/aranandroid/mvvm/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm
2 |
3 | import androidx.test.InstrumentationRegistry
4 | import androidx.test.runner.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.getTargetContext()
22 | assertEquals("com.coolweather.coolweatherjetpack", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/assets/litepal.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/BaseApplication.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm
2 |
3 | import android.annotation.SuppressLint
4 | import android.content.Context
5 | import com.aranandroid.mvvm.data.network.ServiceCreator
6 |
7 | class BaseApplication : MvvmApplication() {
8 |
9 | override fun onCreate() {
10 | super.onCreate()
11 | context = this
12 | // 初始化网络
13 | ServiceCreator.init("http://guolin.tech/")
14 |
15 | }
16 |
17 | companion object {
18 | @SuppressLint("StaticFieldLeak")
19 | lateinit var context: Context
20 | }
21 |
22 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/PlaceRepository.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data
2 |
3 | import com.aranandroid.mvvm.data.db.PlaceDao
4 | import com.aranandroid.mvvm.data.network.ExampleNetwork
5 | import kotlinx.coroutines.Dispatchers
6 | import kotlinx.coroutines.withContext
7 |
8 | /**
9 | * 地方厂库
10 | * 先获取数据库数据 获取不到获取网络数据
11 | */
12 | class PlaceRepository private constructor(private val placeDao: PlaceDao, private val network: ExampleNetwork) {
13 |
14 | suspend fun getProvinceList() = withContext(Dispatchers.IO) {
15 | var list = placeDao.getProvinceList()
16 | if (list.isEmpty()) {
17 | list = network.fetchProvinceList()
18 | placeDao.saveProvinceList(list)
19 | }
20 | list
21 | }
22 |
23 | suspend fun getCityList(provinceId: Int) = withContext(Dispatchers.IO) {
24 | var list = placeDao.getCityList(provinceId)
25 | if (list.isEmpty()) {
26 | list = network.fetchCityList(provinceId)
27 | list.forEach { it.provinceId = provinceId }
28 | placeDao.saveCityList(list)
29 | }
30 | list
31 | }
32 |
33 | suspend fun getCountyList(provinceId: Int, cityId: Int) = withContext(Dispatchers.IO) {
34 | var list = placeDao.getCountyList(cityId)
35 | if (list.isEmpty()) {
36 | list = network.fetchCountyList(provinceId, cityId)
37 | list.forEach { it.cityId = cityId }
38 | placeDao.saveCountyList(list)
39 | }
40 | list
41 | }
42 |
43 | companion object {
44 |
45 | private var instance: PlaceRepository? = null
46 |
47 | fun getInstance(placeDao: PlaceDao, network: ExampleNetwork): PlaceRepository {
48 | if (instance == null) {
49 | synchronized(PlaceRepository::class.java) {
50 | if (instance == null) {
51 | instance = PlaceRepository(placeDao, network)
52 | }
53 | }
54 | }
55 | return instance!!
56 | }
57 |
58 | }
59 |
60 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/Resource.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.aranandroid.mvvm.data
18 |
19 | /**
20 | * A generic class that holds a value with its loading status.
21 | * @param
22 | */
23 | data class Resource(val status: Int, val data: T?, val message: String?) {
24 | // 伴生类 静态变量使用
25 | companion object {
26 | const val SUCCESS = 0
27 | const val ERROR = 1
28 | const val LOADING = 2
29 |
30 | fun success(data: T?) = Resource(SUCCESS, data, null)
31 |
32 | fun error(msg: String, data: T?) = Resource(ERROR, data, msg)
33 |
34 | fun loading(data: T?) = Resource(LOADING, data, null)
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/WeatherRepository.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data
2 |
3 | import com.aranandroid.mvvm.data.db.WeatherDao
4 | import com.aranandroid.mvvm.data.model.weather.Weather
5 | import com.aranandroid.mvvm.data.network.ExampleNetwork
6 | import com.aranandroid.mvvm.base.factory.BaseRepository
7 | import com.aranandroid.mvvm.ui.weather.WeatherViewModel
8 | import kotlinx.coroutines.Dispatchers
9 | import kotlinx.coroutines.withContext
10 |
11 | /**
12 | * 天气数据工厂类
13 | * 先获取数据库数据 获取不到获取网络数据
14 | */
15 | class WeatherRepository private constructor(private val weatherDao: WeatherDao, private val network: ExampleNetwork):
16 | BaseRepository() {
17 |
18 | suspend fun getWeather(weatherId: String): Weather {
19 | var weather = weatherDao.getCachedWeatherInfo()
20 | if (weather == null) weather = requestWeather(weatherId)
21 | return weather
22 | }
23 |
24 | suspend fun refreshWeather(weatherId: String) = requestWeather(weatherId)
25 |
26 | suspend fun getBingPic(): String {
27 | var url = weatherDao.getCachedBingPic()
28 | if (url == null) url = requestBingPic()
29 | return url
30 | }
31 | // suspend 声明挂起函数
32 | suspend fun refreshBingPic() = requestBingPic()
33 |
34 | fun isWeatherCached() = weatherDao.getCachedWeatherInfo() != null
35 |
36 | fun getCachedWeather() = weatherDao.getCachedWeatherInfo()!!
37 |
38 | private suspend fun requestWeather(weatherId: String) = withContext(Dispatchers.IO) {
39 | val heWeather = network.fetchWeather(weatherId)
40 | val weather = heWeather.weather!![0]
41 | weatherDao.cacheWeatherInfo(weather)
42 | weather
43 | }
44 |
45 |
46 | /**
47 | * suspend 声明挂起函数
48 | * withContext(Dispatchers.IO) 切换耗时线程
49 | * 四类协程
50 | * runBlocking 阻塞 无返回值
51 | * launch 非阻塞 无返回值
52 | * withContext 串行 返回值
53 | * async 并行 返回值
54 | */
55 |
56 | private suspend fun requestBingPic() = withContext(Dispatchers.IO) {
57 | val url = network.fetchBingPic()
58 | // 保存到数据库
59 | weatherDao.cacheBingPic(url)
60 | url
61 | }
62 |
63 | companion object {
64 |
65 | private lateinit var instance: WeatherRepository
66 |
67 | fun getInstance(weatherDao: WeatherDao, network: ExampleNetwork): WeatherRepository {
68 | if (!::instance.isInitialized) {
69 | synchronized(WeatherRepository::class.java) {
70 | if (!::instance.isInitialized) {
71 | instance = WeatherRepository(weatherDao, network)
72 | }
73 | }
74 | }
75 | return instance
76 | }
77 |
78 | }
79 |
80 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/db/ExampleDatabase.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.db
2 |
3 | /**
4 | * 案例
5 | */
6 | object ExampleDatabase {
7 |
8 | private var placeDao: PlaceDao? = null
9 |
10 | private var weatherDao: WeatherDao? = null
11 |
12 | fun getPlaceDao(): PlaceDao {
13 | if (placeDao == null) {
14 | placeDao = PlaceDao()
15 | }
16 | return placeDao!!
17 | }
18 |
19 | fun getWeatherDao(): WeatherDao {
20 | if (weatherDao == null) weatherDao = WeatherDao()
21 | return weatherDao!!
22 | }
23 |
24 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/db/PlaceDao.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.db
2 |
3 | import com.aranandroid.mvvm.data.model.place.City
4 | import com.aranandroid.mvvm.data.model.place.County
5 | import com.aranandroid.mvvm.data.model.place.Province
6 | import org.litepal.LitePal
7 |
8 | class PlaceDao {
9 |
10 | fun getProvinceList(): MutableList = LitePal.findAll(Province::class.java)
11 |
12 | fun getCityList(provinceId: Int): MutableList = LitePal.where("provinceId = ?", provinceId.toString()).find(City::class.java)
13 |
14 | fun getCountyList(cityId: Int): MutableList = LitePal.where("cityId = ?", cityId.toString()).find(County::class.java)
15 |
16 | fun saveProvinceList(provinceList: List?) {
17 | if (provinceList != null && provinceList.isNotEmpty()) {
18 | LitePal.saveAll(provinceList)
19 | }
20 | }
21 |
22 | fun saveCityList(cityList: List?) {
23 | if (cityList != null && cityList.isNotEmpty()) {
24 | LitePal.saveAll(cityList)
25 | }
26 | }
27 |
28 | fun saveCountyList(countyList: List?) {
29 | if (countyList != null && countyList.isNotEmpty()) {
30 | LitePal.saveAll(countyList)
31 | }
32 | }
33 |
34 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/db/WeatherDao.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.db
2 |
3 | import android.content.SharedPreferences
4 | import android.preference.PreferenceManager
5 | import com.aranandroid.mvvm.BaseApplication
6 | import com.aranandroid.mvvm.data.model.weather.Weather
7 | import com.google.gson.Gson
8 |
9 | class WeatherDao {
10 |
11 | fun cacheWeatherInfo(weather: Weather?) {
12 | if (weather == null) return
13 | PreferenceManager.getDefaultSharedPreferences(BaseApplication.context).edit {
14 | val weatherInfo = Gson().toJson(weather)
15 | putString("weather", weatherInfo)
16 | }
17 | }
18 |
19 | fun getCachedWeatherInfo(): Weather? {
20 | val weatherInfo = PreferenceManager.getDefaultSharedPreferences(BaseApplication.context).getString("weather", null)
21 | if (weatherInfo != null) {
22 | return Gson().fromJson(weatherInfo, Weather::class.java)
23 | }
24 | return null
25 | }
26 |
27 | fun cacheBingPic(bingPic: String?) {
28 | if (bingPic == null) return
29 | // SharedPreferences 保存数据
30 | PreferenceManager.getDefaultSharedPreferences(BaseApplication.context).edit {
31 | putString("bing_pic", bingPic)
32 | }
33 | }
34 |
35 | fun getCachedBingPic(): String? = PreferenceManager.getDefaultSharedPreferences(BaseApplication.context).getString("bing_pic", null)
36 |
37 | private fun SharedPreferences.edit(action: SharedPreferences.Editor.() -> Unit) {
38 | val editor = edit()
39 | action(editor)
40 | editor.apply()
41 | }
42 |
43 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/model/place/City.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.model.place
2 |
3 | import com.google.gson.annotations.SerializedName
4 | import org.litepal.crud.LitePalSupport
5 |
6 | class City ( @SerializedName("name") val cityName: String, @SerializedName("id") val cityCode: Int) : LitePalSupport() {
7 | @Transient val id = 0
8 | var provinceId = 0
9 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/model/place/County.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.model.place
2 |
3 | import com.google.gson.annotations.SerializedName
4 | import org.litepal.crud.LitePalSupport
5 |
6 | class County (@SerializedName("name") val countyName: String, @SerializedName("weather_id") val weatherId: String) : LitePalSupport() {
7 | @Transient val id = 0
8 | var cityId = 0
9 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/model/place/Province.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.model.place
2 |
3 | import com.google.gson.annotations.SerializedName
4 | import org.litepal.crud.LitePalSupport
5 |
6 | class Province (@SerializedName("name") val provinceName: String, @SerializedName("id") val provinceCode: Int) : LitePalSupport() {
7 | @Transient val id = 0
8 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/model/weather/AQI.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.model.weather
2 |
3 | class AQI {
4 | lateinit var city: AQICity
5 |
6 | inner class AQICity {
7 | var aqi = ""
8 | var pm25 = ""
9 | }
10 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/model/weather/Basic.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.model.weather
2 |
3 | import com.google.gson.annotations.SerializedName
4 |
5 | class Basic {
6 | @SerializedName("city")
7 | var cityName = ""
8 | @SerializedName("id")
9 | var weatherId = ""
10 | lateinit var update: Update
11 |
12 | inner class Update {
13 | @SerializedName("loc")
14 | var updateTime = ""
15 |
16 | fun time() = updateTime.split(" ")[1]
17 | }
18 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/model/weather/Forecast.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.model.weather
2 |
3 | import com.google.gson.annotations.SerializedName
4 |
5 | class Forecast {
6 | var date: String = ""
7 | @SerializedName("tmp")
8 | lateinit var temperature: Temperature
9 | @SerializedName("cond")
10 | lateinit var more: More
11 |
12 | inner class Temperature {
13 | var max = ""
14 | var min = ""
15 | }
16 |
17 | inner class More {
18 | @SerializedName("txt_d")
19 | var info = ""
20 | }
21 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/model/weather/HeWeather.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.model.weather
2 |
3 | import com.google.gson.annotations.SerializedName
4 |
5 | class HeWeather {
6 |
7 | @SerializedName("HeWeather")
8 | var weather: List? = null
9 |
10 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/model/weather/Now.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.model.weather
2 |
3 | import com.google.gson.annotations.SerializedName
4 |
5 | class Now {
6 | @SerializedName("tmp")
7 | var temperature = ""
8 | @SerializedName("cond")
9 | lateinit var more: More
10 |
11 | fun degree() = "$temperature℃"
12 |
13 | inner class More {
14 | @SerializedName("txt")
15 | var info = ""
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/model/weather/Suggestion.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.model.weather
2 |
3 | import com.google.gson.annotations.SerializedName
4 |
5 | class Suggestion {
6 | @SerializedName("comf")
7 | lateinit var comfort: Comfort
8 | @SerializedName("cw")
9 | lateinit var carWash: CarWash
10 | lateinit var sport: Sport
11 |
12 | inner class Comfort {
13 | @SerializedName("txt")
14 | var info = ""
15 | }
16 |
17 | inner class CarWash {
18 | @SerializedName("txt")
19 | var info = ""
20 | }
21 |
22 | inner class Sport {
23 | @SerializedName("txt")
24 | var info = ""
25 | }
26 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/model/weather/Weather.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.model.weather
2 |
3 | import com.google.gson.annotations.SerializedName
4 |
5 | class Weather {
6 | var status = ""
7 | lateinit var basic: Basic
8 | lateinit var aqi: AQI
9 | lateinit var now: Now
10 | lateinit var suggestion: Suggestion
11 | @SerializedName("daily_forecast")
12 | lateinit var forecastList: List
13 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/network/ExampleNetwork.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.network
2 |
3 | import com.aranandroid.mvvm.data.network.api.PlaceService
4 | import com.aranandroid.mvvm.data.network.api.WeatherService
5 |
6 | class ExampleNetwork : BaseNetwork() {
7 |
8 | private val placeService = ServiceCreator.create(PlaceService::class.java)
9 |
10 | private val weatherService = ServiceCreator.create(WeatherService::class.java)
11 |
12 | suspend fun fetchProvinceList() = placeService.getProvinces().await()
13 |
14 | suspend fun fetchCityList(provinceId: Int) = placeService.getCities(provinceId).await()
15 |
16 | suspend fun fetchCountyList(provinceId: Int, cityId: Int) = placeService.getCounties(provinceId, cityId).await()
17 |
18 | suspend fun fetchWeather(weatherId: String) = weatherService.getWeather(weatherId).await()
19 |
20 | suspend fun fetchBingPic() = weatherService.getBingPic().await()
21 |
22 | // 伴生类 静态方法 单列
23 | companion object {
24 |
25 | private var network: ExampleNetwork? = null
26 |
27 | fun getInstance(): ExampleNetwork {
28 | if (network == null) {
29 | synchronized(BaseNetwork::class.java) {
30 | if (network == null) {
31 | network = ExampleNetwork()
32 | }
33 | }
34 | }
35 | return network!!
36 | }
37 |
38 | }
39 |
40 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/network/api/PlaceService.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.network.api
2 |
3 | import com.aranandroid.mvvm.data.model.place.City
4 | import com.aranandroid.mvvm.data.model.place.County
5 | import com.aranandroid.mvvm.data.model.place.Province
6 | import retrofit2.Call
7 | import retrofit2.http.GET
8 | import retrofit2.http.Path
9 |
10 | interface PlaceService {
11 |
12 | @GET("api/china")
13 | fun getProvinces(): Call>
14 |
15 | @GET("api/china/{provinceId}")
16 | fun getCities(@Path("provinceId") provinceId: Int): Call>
17 |
18 | @GET("api/china/{provinceId}/{cityId}")
19 | fun getCounties(@Path("provinceId") provinceId: Int, @Path("cityId") cityId: Int): Call>
20 |
21 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/data/network/api/WeatherService.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.network.api
2 |
3 | import com.aranandroid.mvvm.data.model.weather.HeWeather
4 | import retrofit2.Call
5 | import retrofit2.http.GET
6 | import retrofit2.http.Query
7 |
8 | interface WeatherService {
9 |
10 | @GET("api/weather")
11 | fun getWeather(@Query("cityid") weatherId: String): Call
12 | // 网络请求返回一个 Call对象
13 | @GET("api/bing_pic")
14 | fun getBingPic(): Call
15 |
16 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/ui/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.ui
2 |
3 | import android.Manifest
4 | import android.os.Bundle
5 | import com.aranandroid.mvvm.R
6 | import com.aranandroid.mvvm.ui.weather.WeatherActivity
7 | import android.content.Intent
8 | import android.widget.Toast
9 | import com.aranandroid.mvvm.base.vm.BaseActivity
10 | import com.aranandroid.mvvm.databinding.ActivityMainBinding
11 | import com.aranandroid.mvvm.permission.PermissonDialog
12 | import com.aranandroid.mvvm.ui.area.ChooseAreaFragment
13 | import com.permissionx.guolindev.PermissionX
14 |
15 |
16 | class MainActivity : BaseActivity(R.layout.activity_main) {
17 |
18 | //测试
19 | override fun onCreate(savedInstanceState: Bundle?) {
20 | super.onCreate(savedInstanceState)
21 | //请求权限
22 | registerPermissions()
23 | if (viewModel.isWeatherCached()) {
24 | val intent = Intent(this, WeatherActivity::class.java)
25 | startActivity(intent)
26 | finish()
27 | } else {
28 | supportFragmentManager.beginTransaction().replace(binding.container.id, ChooseAreaFragment()).commit()
29 | }
30 |
31 | }
32 |
33 | private fun registerPermissions() {
34 | PermissionX.init(this).permissions(
35 | Manifest.permission.WRITE_EXTERNAL_STORAGE,
36 | Manifest.permission.READ_EXTERNAL_STORAGE
37 | )
38 | .onExplainRequestReason { scope, deniedList, beforeRequest ->
39 | val message = "PermissionX需要您同意以下权限才能正常使用"
40 | val dialog = PermissonDialog(this, message, deniedList)
41 | scope.showRequestReasonDialog(dialog)
42 | }.onForwardToSettings { scope, deniedList ->
43 | val message = "您需要去设置中手动开启以下权限"
44 | val dialog = PermissonDialog(this, message, deniedList)
45 | scope.showForwardToSettingsDialog(dialog)
46 | }.request { allGranted, grantedList, deniedList ->
47 | if (allGranted) {
48 | Toast.makeText(this, "所有申请的权限都已通过", Toast.LENGTH_SHORT).show()
49 | } else {
50 | Toast.makeText(this, "您拒绝了如下权限:$deniedList", Toast.LENGTH_SHORT).show()
51 | }
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/ui/MainViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.ui
2 |
3 | import com.aranandroid.mvvm.base.m.BaseViewModel
4 | import com.aranandroid.mvvm.data.WeatherRepository
5 | import com.aranandroid.mvvm.data.db.ExampleDatabase
6 | import com.aranandroid.mvvm.data.network.ExampleNetwork
7 |
8 | class MainViewModel() : BaseViewModel() {
9 | private val repository: WeatherRepository = WeatherRepository.getInstance(ExampleDatabase.getWeatherDao(), ExampleNetwork.getInstance())
10 |
11 | fun isWeatherCached() = repository.isWeatherCached()
12 |
13 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/ui/area/ChooseAreaAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.ui.area
2 |
3 | import android.content.Context
4 | import android.view.LayoutInflater
5 | import android.view.View
6 | import android.view.ViewGroup
7 | import android.widget.ArrayAdapter
8 | import androidx.databinding.DataBindingUtil
9 | import com.aranandroid.mvvm.databinding.SimpleItemBinding
10 |
11 | class ChooseAreaAdapter(context: Context, private val resId: Int, private val dataList: List) : ArrayAdapter(context, resId, dataList) {
12 |
13 | override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
14 | val bind: SimpleItemBinding?
15 | val view = if (convertView == null) {
16 | val v = LayoutInflater.from(context).inflate(resId, parent, false)
17 | bind = DataBindingUtil.bind(v)
18 | v.tag = bind
19 | v
20 | } else {
21 | bind = convertView.tag as SimpleItemBinding
22 | convertView
23 | }
24 | bind?.data = dataList[position]
25 | return view
26 | }
27 |
28 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/ui/area/ChooseAreaFragment.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.ui.area
2 |
3 | import android.app.ProgressDialog
4 | import android.content.Intent
5 | import android.os.Bundle
6 | import android.view.View
7 | import android.widget.*
8 | import androidx.lifecycle.Observer
9 | import com.aranandroid.mvvm.R
10 | import com.aranandroid.mvvm.databinding.ChooseAreaBindingImpl
11 | import com.aranandroid.mvvm.ui.MainActivity
12 | import com.aranandroid.mvvm.base.vm.BaseFragment
13 | import com.aranandroid.mvvm.ui.weather.WeatherActivity
14 | import kotlinx.android.synthetic.main.activity_weather.*
15 | import kotlinx.android.synthetic.main.choose_area.*
16 |
17 | class ChooseAreaFragment :
18 | BaseFragment(R.layout.choose_area) {
19 | private var progressDialog: ProgressDialog? = null
20 | private lateinit var adapter: ArrayAdapter
21 |
22 |
23 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
24 | super.onViewCreated(view, savedInstanceState)
25 | binding?.viewModel = viewModel
26 | binding?.lifecycleOwner = this
27 | }
28 |
29 |
30 | override fun onActivityCreated(savedInstanceState: Bundle?) {
31 | super.onActivityCreated(savedInstanceState)
32 | adapter = ChooseAreaAdapter(context!!, R.layout.simple_item, viewModel.dataList)
33 | listView.adapter = adapter
34 | observe()
35 | }
36 |
37 | private fun observe() {
38 | // 通过观察当前水平的值 决定title的样式 (livedata)
39 | viewModel.currentLevel.observe(this, Observer { level ->
40 | when (level) {
41 | LEVEL_PROVINCE -> {
42 | viewModel.title.value = "中国"
43 | backButton.visibility = View.GONE
44 | }
45 | LEVEL_CITY -> {
46 | viewModel.title.value = viewModel.selectedProvince?.provinceName
47 | backButton.visibility = View.VISIBLE
48 | }
49 | LEVEL_COUNTY -> {
50 | viewModel.title.value = viewModel.selectedCity?.cityName
51 | backButton.visibility = View.VISIBLE
52 | }
53 | }
54 | })
55 | viewModel.dataChanged.observe(this, Observer {
56 | adapter.notifyDataSetChanged()
57 | listView.setSelection(0)
58 | closeProgressDialog()
59 | })
60 | viewModel.isLoading.observe(this, Observer { isLoading ->
61 | if (isLoading) showProgressDialog()
62 | else closeProgressDialog()
63 | })
64 | viewModel.areaSelected.observe(this, Observer { selected ->
65 | if (selected && viewModel.selectedCounty != null) {
66 | if (activity is MainActivity) {
67 | val intent = Intent(activity, WeatherActivity::class.java)
68 | intent.putExtra("weather_id", viewModel.selectedCounty!!.weatherId)
69 | startActivity(intent)
70 | activity?.finish()
71 | } else if (activity is WeatherActivity) {
72 | val weatherActivity = activity as WeatherActivity
73 | weatherActivity.drawerLayout.closeDrawers()
74 | weatherActivity.viewModel.weatherId = viewModel.selectedCounty!!.weatherId
75 | weatherActivity.viewModel.refreshWeather()
76 | }
77 | viewModel.areaSelected.value = false
78 | }
79 | })
80 | if (viewModel.dataList.isEmpty()) {
81 | viewModel.getProvinces()
82 | }
83 | }
84 |
85 | /**
86 | * 显示进度对话框
87 | */
88 | private fun showProgressDialog() {
89 | if (progressDialog == null) {
90 | progressDialog = ProgressDialog(activity)
91 | progressDialog?.setMessage("正在加载...")
92 | progressDialog?.setCanceledOnTouchOutside(false)
93 | }
94 | progressDialog?.show()
95 | }
96 |
97 | /**
98 | * 关闭进度对话框
99 | */
100 | private fun closeProgressDialog() {
101 | progressDialog?.dismiss()
102 | }
103 |
104 | // 伴生对象
105 | companion object {
106 | // 省 市 县
107 | const val LEVEL_PROVINCE = 0
108 | const val LEVEL_CITY = 1
109 | const val LEVEL_COUNTY = 2
110 | }
111 |
112 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/ui/area/ChooseAreaViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.ui.area
2 |
3 | import android.view.View
4 | import android.widget.AdapterView
5 | import android.widget.Toast
6 | import androidx.lifecycle.MutableLiveData
7 | import androidx.lifecycle.viewModelScope
8 | import com.aranandroid.mvvm.BaseApplication
9 | import com.aranandroid.mvvm.data.PlaceRepository
10 | import com.aranandroid.mvvm.data.model.place.City
11 | import com.aranandroid.mvvm.data.model.place.County
12 | import com.aranandroid.mvvm.data.model.place.Province
13 | import com.aranandroid.mvvm.ui.area.ChooseAreaFragment.Companion.LEVEL_CITY
14 | import com.aranandroid.mvvm.ui.area.ChooseAreaFragment.Companion.LEVEL_COUNTY
15 | import com.aranandroid.mvvm.ui.area.ChooseAreaFragment.Companion.LEVEL_PROVINCE
16 | import com.aranandroid.mvvm.base.m.BaseViewModel
17 | import com.aranandroid.mvvm.data.db.ExampleDatabase
18 | import com.aranandroid.mvvm.data.network.ExampleNetwork
19 | import kotlinx.coroutines.launch
20 | import java.util.*
21 |
22 | class ChooseAreaViewModel() : BaseViewModel() {
23 |
24 | private val repository: PlaceRepository = PlaceRepository.getInstance(ExampleDatabase.getPlaceDao(), ExampleNetwork.getInstance())
25 |
26 | var title = MutableLiveData()
27 |
28 | // 当前水平
29 | var currentLevel = MutableLiveData()
30 |
31 | var dataChanged = MutableLiveData()
32 |
33 | var isLoading = MutableLiveData()
34 |
35 | var areaSelected = MutableLiveData()
36 |
37 | var selectedProvince: Province? = null
38 |
39 | var selectedCity: City? = null
40 |
41 | var selectedCounty: County? = null
42 |
43 | lateinit var provinces: MutableList
44 |
45 | lateinit var cities: MutableList
46 |
47 | lateinit var counties: MutableList
48 |
49 | val dataList = ArrayList()
50 |
51 | fun getProvinces() {
52 | currentLevel.value = LEVEL_PROVINCE
53 | launch {
54 | provinces = repository.getProvinceList()
55 | dataList.addAll(provinces.map { it.provinceName })
56 | }
57 | }
58 |
59 | private fun getCities() = selectedProvince?.let {
60 | currentLevel.value = LEVEL_CITY
61 | launch {
62 | cities = repository.getCityList(it.provinceCode)
63 | dataList.addAll(cities.map { it.cityName })
64 | }
65 | }
66 |
67 | private fun getCounties() = selectedCity?.let {
68 | currentLevel.value = LEVEL_COUNTY
69 | launch {
70 | counties = repository.getCountyList(it.provinceId, it.cityCode)
71 | dataList.addAll(counties.map { it.countyName })
72 | }
73 | }
74 |
75 | fun onListViewItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
76 | when {
77 | currentLevel.value == LEVEL_PROVINCE -> {
78 | selectedProvince = provinces[position]
79 | getCities()
80 | }
81 | currentLevel.value == LEVEL_CITY -> {
82 | selectedCity = cities[position]
83 | getCounties()
84 | }
85 | currentLevel.value == LEVEL_COUNTY -> {
86 | selectedCounty = counties[position]
87 | areaSelected.value = true
88 | }
89 | }
90 | }
91 |
92 | fun onBack() {
93 | if (currentLevel.value == LEVEL_COUNTY) {
94 | getCities()
95 | } else if (currentLevel.value == LEVEL_CITY) {
96 | getProvinces()
97 | }
98 | }
99 |
100 | private fun launch(block: suspend () -> Unit) = viewModelScope.launch {
101 | try {
102 | isLoading.value = true
103 | dataList.clear()
104 | block()
105 | dataChanged.value = dataChanged.value?.plus(1)
106 | isLoading.value = false
107 | } catch (t: Throwable) {
108 | t.printStackTrace()
109 | Toast.makeText(BaseApplication.context, t.message, Toast.LENGTH_SHORT).show()
110 | dataChanged.value = dataChanged.value?.plus(1)
111 | isLoading.value = false
112 | }
113 | }
114 |
115 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/ui/weather/WeatherActivity.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.ui.weather
2 |
3 | import android.graphics.Color
4 | import android.os.Build
5 | import android.os.Bundle
6 | import android.view.View
7 | import androidx.core.view.GravityCompat
8 | import com.aranandroid.mvvm.R
9 | import com.aranandroid.mvvm.databinding.ActivityWeatherBinding
10 | import com.aranandroid.mvvm.base.vm.BaseActivity
11 | import kotlinx.android.synthetic.main.activity_weather.*
12 | import kotlinx.android.synthetic.main.title.*
13 |
14 | class WeatherActivity : BaseActivity(R.layout.activity_weather) {
15 | override fun onCreate(savedInstanceState: Bundle?) {
16 | super.onCreate(savedInstanceState)
17 | if (Build.VERSION.SDK_INT >= 21) {
18 | val decorView = window.decorView
19 | decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
20 | window.statusBarColor = Color.TRANSPARENT
21 | }
22 | binding.viewModel = viewModel
23 | binding.resId = R.color.colorPrimary
24 | binding.lifecycleOwner = this
25 | viewModel.weatherId = if (viewModel.isWeatherCached()) {
26 | viewModel.getCachedWeather().basic.weatherId
27 | } else {
28 | intent.getStringExtra("weather_id")
29 | }
30 | navButton.setOnClickListener {
31 | drawerLayout.openDrawer(GravityCompat.START)
32 | }
33 | viewModel.getWeather()
34 | }
35 |
36 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/ui/weather/WeatherViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.ui.weather
2 |
3 | import android.widget.Toast
4 | import androidx.lifecycle.MutableLiveData
5 | import androidx.lifecycle.viewModelScope
6 | import com.aranandroid.mvvm.BaseApplication
7 | import com.aranandroid.mvvm.data.WeatherRepository
8 | import com.aranandroid.mvvm.data.model.weather.Weather
9 | import com.aranandroid.mvvm.base.m.BaseViewModel
10 | import com.aranandroid.mvvm.data.db.ExampleDatabase
11 | import com.aranandroid.mvvm.data.network.ExampleNetwork
12 | import kotlinx.coroutines.launch
13 |
14 | class WeatherViewModel() : BaseViewModel() {
15 | private val repository: WeatherRepository = WeatherRepository.getInstance(ExampleDatabase.getWeatherDao(), ExampleNetwork.getInstance())
16 | var weather = MutableLiveData()
17 |
18 | var bingPicUrl = MutableLiveData()
19 |
20 | var refreshing = MutableLiveData()
21 |
22 | var weatherInitialized = MutableLiveData()
23 |
24 | var weatherId = ""
25 |
26 | fun getWeather() {
27 |
28 | launch ({
29 | weather.value = repository.getWeather(weatherId)
30 | weatherInitialized.value = true
31 | }, {
32 | Toast.makeText(BaseApplication.context, it.message, Toast.LENGTH_SHORT).show()
33 | })
34 | getBingPic(false)
35 | }
36 |
37 | fun refreshWeather() {
38 | refreshing.value = true
39 | launch ({
40 | weather.value = repository.refreshWeather(weatherId)
41 | refreshing.value = false
42 | weatherInitialized.value = true
43 | }, {
44 | Toast.makeText(BaseApplication.context, it.message, Toast.LENGTH_SHORT).show()
45 | refreshing.value = false
46 | })
47 | getBingPic(true)
48 | }
49 |
50 | fun isWeatherCached() = repository.isWeatherCached()
51 |
52 | fun getCachedWeather() = repository.getCachedWeather()
53 |
54 | fun onRefresh() {
55 | refreshWeather()
56 | }
57 |
58 | private fun getBingPic(refresh: Boolean) {
59 | // viewModelScope.launch 开启协程方法
60 | launch({
61 | bingPicUrl.value = if (refresh) repository.refreshBingPic() else repository.getBingPic()
62 | }, {
63 | Toast.makeText(BaseApplication.context, it.message, Toast.LENGTH_SHORT).show()
64 | })
65 | }
66 |
67 | /**
68 | * 自定义一个launch方法
69 | * 高阶函数:(参数或者返回值有方法的函数)
70 | */
71 | private fun launch(block: suspend () -> Unit, error: suspend (Throwable) -> Unit) = viewModelScope.launch {
72 | try {
73 | block()
74 | } catch (e: Throwable) {
75 | error(e)
76 | }
77 | }
78 |
79 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/aranandroid/mvvm/util/BindingAdapters.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.util
2 |
3 | import android.view.LayoutInflater
4 | import android.widget.ImageView
5 | import android.widget.LinearLayout
6 | import androidx.databinding.BindingAdapter
7 | import androidx.databinding.DataBindingUtil
8 | import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
9 | import com.bumptech.glide.Glide
10 | import com.aranandroid.mvvm.R
11 | import com.aranandroid.mvvm.data.model.weather.Weather
12 | import com.aranandroid.mvvm.databinding.ForecastItemBinding
13 |
14 | @BindingAdapter("bind:loadBingPic")
15 | fun ImageView.loadBingPic(url: String?) {
16 | if (url != null) Glide.with(context).load(url).into(this)
17 | }
18 |
19 | @BindingAdapter("bind:colorSchemeResources")
20 | fun SwipeRefreshLayout.colorSchemeResources(resId: Int) {
21 | setColorSchemeResources(resId)
22 | }
23 |
24 | @BindingAdapter("bind:showForecast")
25 | fun LinearLayout.showForecast(weather: Weather?) = weather?.let {
26 | removeAllViews()
27 | for (forecast in it.forecastList) {
28 | val view = LayoutInflater.from(context).inflate(R.layout.forecast_item, this, false)
29 | DataBindingUtil.bind(view)?.forecast = forecast
30 | addView(view)
31 | }
32 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_back.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AranAndroid009/Mvvm/94e887210b10d23982f5907cd96b3470f8425c9c/app/src/main/res/drawable-xxhdpi/ic_back.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_home.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AranAndroid009/Mvvm/94e887210b10d23982f5907cd96b3470f8425c9c/app/src/main/res/drawable-xxhdpi/ic_home.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
10 |
12 |
14 |
16 |
18 |
20 |
22 |
24 |
26 |
28 |
30 |
32 |
34 |
36 |
38 |
40 |
42 |
44 |
46 |
48 |
50 |
52 |
54 |
56 |
58 |
60 |
62 |
64 |
66 |
68 |
70 |
72 |
74 |
75 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_weather.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
13 |
14 |
21 |
22 |
26 |
27 |
35 |
36 |
43 |
44 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/aqi.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
11 |
12 |
20 |
21 |
25 |
26 |
30 |
31 |
36 |
37 |
46 |
47 |
53 |
54 |
55 |
56 |
57 |
58 |
62 |
67 |
76 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/choose_area.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
11 |
15 |
16 |
24 |
25 |
35 |
36 |
37 |
43 |
44 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/forecast.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
12 |
13 |
21 |
22 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/forecast_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
9 |
10 |
18 |
19 |
28 |
29 |
38 |
39 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/now.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
10 |
11 |
19 |
20 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/simple_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/suggestion.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
11 |
12 |
20 |
21 |
28 |
29 |
36 |
37 |
44 |
45 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/title.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
8 |
9 |
17 |
18 |
26 |
27 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AranAndroid009/Mvvm/94e887210b10d23982f5907cd96b3470f8425c9c/app/src/main/res/mipmap-hdpi/logo.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AranAndroid009/Mvvm/94e887210b10d23982f5907cd96b3470f8425c9c/app/src/main/res/mipmap-mdpi/logo.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AranAndroid009/Mvvm/94e887210b10d23982f5907cd96b3470f8425c9c/app/src/main/res/mipmap-xhdpi/logo.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AranAndroid009/Mvvm/94e887210b10d23982f5907cd96b3470f8425c9c/app/src/main/res/mipmap-xxhdpi/logo.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AranAndroid009/Mvvm/94e887210b10d23982f5907cd96b3470f8425c9c/app/src/main/res/mipmap-xxxhdpi/logo.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | CoolWeatherJetPack
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/network_security_config.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/app/src/test/java/com/aranandroid/mvvm/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext.kotlin_version = '1.3.50'
5 | repositories {
6 | google()
7 | jcenter()
8 | maven{
9 | url 'https://jitpack.io'
10 | }
11 | }
12 | dependencies {
13 | classpath 'com.android.tools.build:gradle:3.4.0'
14 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
15 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
16 |
17 | // NOTE: Do not place your application dependencies here; they belong
18 | // in the individual module build.gradle files
19 | }
20 | }
21 |
22 | allprojects {
23 | repositories {
24 | google()
25 | jcenter()
26 | maven{
27 | url 'https://jitpack.io'
28 | }
29 | }
30 | }
31 |
32 | task clean(type: Delete) {
33 | delete rootProject.buildDir
34 | }
35 |
--------------------------------------------------------------------------------
/frist.patch:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AranAndroid009/Mvvm/94e887210b10d23982f5907cd96b3470f8425c9c/frist.patch
--------------------------------------------------------------------------------
/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=-Xmx1536m
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 | # Kotlin code style for this project: "official" or "obsolete":
15 | kotlin.code.style=official
16 | android.useAndroidX=true
17 | android.enableJetifier=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AranAndroid009/Mvvm/94e887210b10d23982f5907cd96b3470f8425c9c/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Apr 18 14:34:14 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-5.1.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/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 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
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 Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/images/Screenshot_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AranAndroid009/Mvvm/94e887210b10d23982f5907cd96b3470f8425c9c/images/Screenshot_1.png
--------------------------------------------------------------------------------
/images/Screenshot_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AranAndroid009/Mvvm/94e887210b10d23982f5907cd96b3470f8425c9c/images/Screenshot_2.png
--------------------------------------------------------------------------------
/images/architecture.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AranAndroid009/Mvvm/94e887210b10d23982f5907cd96b3470f8425c9c/images/architecture.jpg
--------------------------------------------------------------------------------
/mvvm/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/mvvm/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'com.github.dcendents.android-maven'
4 | id 'kotlin-android'
5 | }
6 |
7 |
8 | group = 'com.github.AranAndroid009'
9 |
10 | android {
11 | compileSdkVersion 30
12 | buildToolsVersion "30.0.3"
13 |
14 | defaultConfig {
15 | minSdkVersion 21
16 | targetSdkVersion 30
17 | versionCode 1
18 | versionName "1.0"
19 |
20 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
21 | consumerProguardFiles "consumer-rules.pro"
22 | }
23 |
24 | buildTypes {
25 | release {
26 | minifyEnabled false
27 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
28 | }
29 | }
30 | compileOptions {
31 | sourceCompatibility JavaVersion.VERSION_1_8
32 | targetCompatibility JavaVersion.VERSION_1_8
33 | }
34 | kotlinOptions {
35 | jvmTarget = '1.8'
36 | }
37 | dataBinding {
38 | enabled true
39 | }
40 | }
41 |
42 | dependencies {
43 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
44 | implementation 'androidx.core:core-ktx:1.3.2'
45 | implementation 'androidx.appcompat:appcompat:1.2.0'
46 | implementation 'com.google.android.material:material:1.2.1'
47 | testImplementation 'junit:junit:4.+'
48 | androidTestImplementation 'androidx.test.ext:junit:1.1.2'
49 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
50 |
51 | api 'com.blankj:utilcodex:1.30.6'
52 |
53 | api 'com.squareup.retrofit2:retrofit:2.3.0'
54 | api 'com.squareup.retrofit2:converter-gson:2.3.0'
55 | api 'com.squareup.retrofit2:converter-scalars:2.5.0'
56 |
57 | def lifecycle_version = "2.0.0"
58 | // ViewModel and LiveData
59 | api "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
60 | api "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0-alpha03"
61 |
62 | api 'org.litepal.android:kotlin:3.0.0'
63 | api 'com.permissionx.guolindev:permissionx:1.4.0'
64 |
65 | }
--------------------------------------------------------------------------------
/mvvm/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AranAndroid009/Mvvm/94e887210b10d23982f5907cd96b3470f8425c9c/mvvm/consumer-rules.pro
--------------------------------------------------------------------------------
/mvvm/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
--------------------------------------------------------------------------------
/mvvm/src/androidTest/java/com/aranandroid/mvvm/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm
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.aranandroid.mvvm.test", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/mvvm/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/MvvmApplication.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm
2 |
3 | import android.annotation.SuppressLint
4 | import android.app.Application
5 | import android.content.Context
6 | import com.aranandroid.mvvm.util.ActivityLifeCycleCallBackIml
7 | import com.blankj.utilcode.util.CrashUtils
8 | import org.litepal.LitePal
9 |
10 | open class MvvmApplication : Application() {
11 |
12 | override fun onCreate() {
13 | super.onCreate()
14 | // 数据库
15 | LitePal.initialize(this)
16 | context = this
17 | // 崩溃日志
18 | CrashUtils.init(object : CrashUtils.OnCrashListener {
19 | override fun onCrash(crashInfo: CrashUtils.CrashInfo) {
20 | crashInfo.addExtraHead("extraKey", "extraValue")
21 | }
22 | })
23 |
24 | // 管理Activity生命周期
25 | registerActivityLifecycleCallbacks(ActivityLifeCycleCallBackIml())
26 | }
27 |
28 | companion object {
29 | @SuppressLint("StaticFieldLeak")
30 | lateinit var context: Context
31 | }
32 |
33 | }
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/base/factory/BaseRepository.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.base.factory
2 |
3 | import androidx.lifecycle.ViewModel
4 |
5 | open class BaseRepository {
6 | }
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/base/m/BaseViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.base.m
2 |
3 | import androidx.lifecycle.ViewModel
4 |
5 | open class BaseViewModel: ViewModel() {
6 | }
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/base/vm/BaseActivity.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.base.vm
2 |
3 |
4 | import androidx.appcompat.app.AppCompatActivity
5 | import androidx.databinding.DataBindingUtil
6 | import androidx.lifecycle.ViewModelProviders
7 | import com.aranandroid.mvvm.base.m.BaseViewModel
8 | import java.lang.reflect.ParameterizedType
9 | import java.lang.reflect.Type
10 |
11 |
12 | open class BaseActivity(
13 | layoutId: Int
14 | ) : AppCompatActivity() {
15 | val viewModel by lazy {
16 | ViewModelProviders.of(this)
17 | .get(getClass() as Class)
18 | }
19 |
20 | val binding by lazy {
21 | DataBindingUtil.setContentView(
22 | this,
23 | layoutId
24 | )
25 | }
26 |
27 |
28 |
29 | fun getClass(): Type? {
30 | return (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class
31 | }
32 |
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/base/vm/BaseFragment.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.base.vm
2 |
3 | import android.os.Bundle
4 | import android.view.LayoutInflater
5 | import android.view.View
6 | import android.view.ViewGroup
7 | import androidx.databinding.DataBindingUtil
8 | import androidx.fragment.app.Fragment
9 | import androidx.lifecycle.ViewModelProviders
10 | import com.aranandroid.mvvm.base.m.BaseViewModel
11 | import java.lang.reflect.ParameterizedType
12 | import java.lang.reflect.Type
13 |
14 | open class BaseFragment(
15 | private val layoutId : Int) : Fragment(){
16 | // lifecycle
17 | val viewModel by lazy {
18 | ViewModelProviders.of(this).get(
19 | getClass() as Class) }
20 |
21 | var binding : ViewDataBinding? = null
22 |
23 |
24 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
25 | val view = inflater.inflate(layoutId, container, false)
26 | binding = DataBindingUtil.bind(view)
27 | return view
28 | }
29 |
30 | fun getClass(): Type? {
31 | return (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class
32 | }
33 |
34 |
35 | }
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/base/vm/BaseFragmentActivity.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.base.vm
2 |
3 |
4 | import androidx.databinding.DataBindingUtil
5 | import androidx.fragment.app.FragmentActivity
6 | import androidx.lifecycle.ViewModelProviders
7 | import com.aranandroid.mvvm.base.m.BaseViewModel
8 | import java.lang.reflect.ParameterizedType
9 | import java.lang.reflect.Type
10 |
11 |
12 | open class BaseFragmentActivity(
13 | layoutId: Int
14 | ) : FragmentActivity() {
15 | val viewModel by lazy {
16 | ViewModelProviders.of(this)
17 | .get(getClass() as Class)
18 | }
19 |
20 | val binding by lazy {
21 | DataBindingUtil.setContentView(
22 | this,
23 | layoutId
24 | )
25 | }
26 |
27 | fun getClass(): Type? {
28 | return (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class
29 | }
30 |
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/live/AliveManager.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.live
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import android.content.Intent
6 | import android.content.IntentFilter
7 | import java.lang.ref.WeakReference
8 |
9 | /**
10 | * 创建人:zhipeng.liu
11 | * 创建时间:2019/4/9 0009 19:46
12 | */
13 | class AliveManager private constructor() {
14 | private var mKeepAct: WeakReference? = null
15 | private var keepReceiver: AliveReceiver? = null
16 |
17 | /**
18 | * 注册 开屏 关屏关公
19 | *
20 | * @param context
21 | */
22 | fun registerKeep(context: Context) {
23 | val filter = IntentFilter()
24 | filter.addAction(Intent.ACTION_SCREEN_OFF)
25 | filter.addAction(Intent.ACTION_SCREEN_ON)
26 | keepReceiver = AliveReceiver()
27 | context.registerReceiver(keepReceiver, filter)
28 | }
29 |
30 | /**
31 | * 反注册广播接收者
32 | *
33 | * @param context
34 | */
35 | fun unregisterKeep(context: Context) {
36 | if (null != keepReceiver) {
37 | context.unregisterReceiver(keepReceiver)
38 | }
39 | }
40 |
41 | /**
42 | * 开启Activity
43 | * @param context
44 | */
45 | fun startKeep(context: Context) {
46 | val intent =
47 | Intent(context, AliveScreenActivity::class.java)
48 | intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
49 | context.startActivity(intent)
50 | }
51 |
52 | fun finishKeep() {
53 | if (null != mKeepAct) {
54 | val activity = mKeepAct!!.get()
55 | activity?.finish()
56 | mKeepAct = null
57 | }
58 | }
59 |
60 | fun setKeep(keep: AliveScreenActivity) {
61 | mKeepAct = WeakReference(keep)
62 | }
63 |
64 | companion object {
65 | val instance = AliveManager()
66 | }
67 | }
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/live/AliveReceiver.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.live
2 |
3 | import android.content.BroadcastReceiver
4 | import android.content.Context
5 | import android.content.Intent
6 | import android.text.TextUtils
7 | import android.util.Log
8 |
9 | /**
10 | * 创建人:zhipeng.liu
11 | * 创建时间:2019/4/9 0009 19:46
12 | */
13 | class AliveReceiver : BroadcastReceiver() {
14 | override fun onReceive(
15 | context: Context,
16 | intent: Intent
17 | ) {
18 | val action = intent.action
19 | Log.e(TAG, "receive:$action")
20 | if (TextUtils.equals(action, Intent.ACTION_SCREEN_OFF)) {
21 | //关屏 开启1px activity
22 | AliveManager.Companion.instance.startKeep(context)
23 | } else if (TextUtils.equals(action, Intent.ACTION_SCREEN_ON)) {
24 | AliveManager.Companion.instance.finishKeep()
25 | }
26 | }
27 |
28 | companion object {
29 | private const val TAG = "AliveReceiver"
30 | }
31 | }
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/live/AliveScreenActivity.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.live
2 |
3 | import android.app.Activity
4 | import android.os.Bundle
5 | import android.util.Log
6 | import android.view.Gravity
7 |
8 | /**
9 | * 创建人:zhipeng.liu
10 | * 创建时间:2019/4/9 0009 19:46
11 | */
12 | class AliveScreenActivity : Activity() {
13 | override fun onCreate(savedInstanceState: Bundle?) {
14 | super.onCreate(savedInstanceState)
15 | Log.e(TAG, "启动包活界面")
16 | val window = window
17 | //设置这个act 左上角
18 | window.setGravity(Gravity.START or Gravity.TOP)
19 | //宽 高都为1
20 | val attributes = window.attributes
21 | attributes.width = 1
22 | attributes.height = 1
23 | attributes.x = 0
24 | attributes.y = 0
25 | window.attributes = attributes
26 | AliveManager.Companion.instance.setKeep(this)
27 | }
28 |
29 | override fun onDestroy() {
30 | super.onDestroy()
31 | Log.e(TAG, "关闭启动包活界面")
32 | }
33 |
34 | companion object {
35 | private const val TAG = "AliveScreenActivity"
36 | }
37 | }
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/live/EmptyActivity.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.live
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import androidx.appcompat.app.AppCompatActivity
6 |
7 | /**
8 | * 创建人:zhipeng.liu
9 | * 创建时间:2019/4/9 0009 19:46
10 | */
11 | class EmptyActivity : AppCompatActivity() {
12 | override fun onCreate(savedInstanceState: Bundle?) {
13 | super.onCreate(savedInstanceState)
14 | startService(Intent(this, ForgroundService::class.java))
15 | finish()
16 | }
17 | }
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/live/ForgroundService.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.live
2 |
3 | import android.app.NotificationChannel
4 | import android.app.NotificationManager
5 | import android.app.PendingIntent
6 | import android.app.Service
7 | import android.content.Context
8 | import android.content.Intent
9 | import android.os.Build
10 | import android.os.IBinder
11 | import android.os.SystemClock
12 | import android.util.Log
13 | import androidx.core.app.NotificationCompat
14 | import com.aranandroid.mvvm.R
15 | import com.aranandroid.mvvm.live.ForgroundService.InnnerService
16 | import java.util.*
17 |
18 | /**
19 | * 创建人:zhipeng.liu
20 | * 创建时间:2019/4/9 0009 19:46
21 | */
22 | class ForgroundService : Service() {
23 | override fun onBind(intent: Intent): IBinder? {
24 | return null
25 | }
26 |
27 | override fun onCreate() {
28 | super.onCreate()
29 | Log.d("Debug_service", "开始提权")
30 | InnnerService.startForegroundSelf(this, this)
31 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
32 | startService(Intent(this, InnnerService::class.java))
33 | }
34 | object : Thread() {
35 | override fun run() {
36 | while (true) {
37 | SystemClock.sleep(5000)
38 | Log.d("Debug_run", "" + Date().time)
39 | }
40 | }
41 | }.start()
42 | }
43 |
44 | class InnnerService : Service() {
45 | override fun onCreate() {
46 | super.onCreate()
47 | startForegroundSelf(this, this)
48 | stopSelf()
49 | }
50 |
51 | override fun onBind(intent: Intent): IBinder? {
52 | return null
53 | }
54 |
55 | companion object {
56 | fun startForegroundSelf(
57 | context: Context,
58 | service: Service
59 | ) {
60 | val builder =
61 | NotificationCompat.Builder(context, "default")
62 | builder.setSmallIcon(R.mipmap.ic_launcher)
63 | builder.setContentTitle(null)
64 | builder.setContentText(null)
65 | val notificationIntent = Intent(
66 | context,
67 | EmptyActivity::class.java
68 | )
69 | val pendingIntent =
70 | PendingIntent.getActivity(context, 0, notificationIntent, 0)
71 | builder.setContentIntent(pendingIntent)
72 | val manager =
73 | context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
74 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
75 | manager.createNotificationChannel(
76 | NotificationChannel(
77 | "default",
78 | "",
79 | NotificationManager.IMPORTANCE_DEFAULT
80 | )
81 | )
82 | }
83 | val notification = builder.build()
84 | service.startForeground(10, notification)
85 | }
86 | }
87 | }
88 | }
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/network/BaseNetwork.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.network
2 |
3 | import retrofit2.Call
4 | import retrofit2.Callback
5 | import retrofit2.Response
6 | import kotlin.coroutines.resume
7 | import kotlin.coroutines.resumeWithException
8 | import kotlin.coroutines.suspendCoroutine
9 |
10 | open class BaseNetwork {
11 |
12 | /**
13 | * enqueue 是retrofit2网络请求的回调方法
14 | * 添加suspendCoroutine添加协程作用域(将回调函数 转换 协程/挂起函数)
15 | */
16 | suspend fun Call.await(): T {
17 | return suspendCoroutine { continuation ->
18 | enqueue(object : Callback {
19 | override fun onFailure(call: Call, t: Throwable) {
20 | // 异常返回值 continuation.resumeWithException
21 | continuation.resumeWithException(t)
22 | }
23 |
24 | override fun onResponse(call: Call, response: Response) {
25 | val body = response.body()
26 | // 正常返回值 continuation.resume
27 | if (body != null) continuation.resume(body)
28 | else continuation.resumeWithException(RuntimeException("response body is null"))
29 | }
30 | })
31 | }
32 | }
33 |
34 | }
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/network/ServiceCreator.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.data.network
2 |
3 | import okhttp3.OkHttpClient
4 | import retrofit2.Retrofit
5 | import retrofit2.converter.gson.GsonConverterFactory
6 | import retrofit2.converter.scalars.ScalarsConverterFactory
7 |
8 | object ServiceCreator {
9 |
10 | private lateinit var retrofit:Retrofit
11 |
12 | fun init(url:String){
13 | val httpClient = OkHttpClient.Builder()
14 |
15 | val builder = Retrofit.Builder()
16 | .baseUrl(url)
17 | .client(httpClient.build())
18 | .addConverterFactory(ScalarsConverterFactory.create())
19 | .addConverterFactory(GsonConverterFactory.create())
20 |
21 | retrofit = builder.build()
22 | }
23 |
24 | fun create(serviceClass: Class): T = retrofit.create(serviceClass)
25 |
26 | }
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/permission/PermissonDialog.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.permission
2 |
3 | import android.Manifest
4 | import android.content.Context
5 | import android.os.Bundle
6 | import android.view.LayoutInflater
7 | import android.view.View
8 | import android.widget.TextView
9 | import androidx.databinding.DataBindingUtil
10 | import com.aranandroid.mvvm.R
11 | import com.aranandroid.mvvm.databinding.CustomDialogLayoutBinding
12 | import com.permissionx.guolindev.dialog.RationaleDialog
13 |
14 | class PermissonDialog(context: Context, val message: String, val permissions: List) :
15 | RationaleDialog(context, R.style.CustomDialog) {
16 | private var binding: CustomDialogLayoutBinding? = null
17 |
18 |
19 | private val permissionMap = mapOf(
20 | Manifest.permission.READ_CALENDAR to Manifest.permission_group.CALENDAR,
21 | Manifest.permission.WRITE_CALENDAR to Manifest.permission_group.CALENDAR,
22 | Manifest.permission.READ_CALL_LOG to Manifest.permission_group.CALL_LOG,
23 | Manifest.permission.WRITE_CALL_LOG to Manifest.permission_group.CALL_LOG,
24 | Manifest.permission.PROCESS_OUTGOING_CALLS to Manifest.permission_group.CALL_LOG,
25 | Manifest.permission.CAMERA to Manifest.permission_group.CAMERA,
26 | Manifest.permission.READ_CONTACTS to Manifest.permission_group.CONTACTS,
27 | Manifest.permission.WRITE_CONTACTS to Manifest.permission_group.CONTACTS,
28 | Manifest.permission.GET_ACCOUNTS to Manifest.permission_group.CONTACTS,
29 | Manifest.permission.ACCESS_FINE_LOCATION to Manifest.permission_group.LOCATION,
30 | Manifest.permission.ACCESS_COARSE_LOCATION to Manifest.permission_group.LOCATION,
31 | Manifest.permission.ACCESS_BACKGROUND_LOCATION to Manifest.permission_group.LOCATION,
32 | Manifest.permission.RECORD_AUDIO to Manifest.permission_group.MICROPHONE,
33 | Manifest.permission.READ_PHONE_STATE to Manifest.permission_group.PHONE,
34 | Manifest.permission.READ_PHONE_NUMBERS to Manifest.permission_group.PHONE,
35 | Manifest.permission.CALL_PHONE to Manifest.permission_group.PHONE,
36 | Manifest.permission.ANSWER_PHONE_CALLS to Manifest.permission_group.PHONE,
37 | Manifest.permission.ADD_VOICEMAIL to Manifest.permission_group.PHONE,
38 | Manifest.permission.USE_SIP to Manifest.permission_group.PHONE,
39 | Manifest.permission.ACCEPT_HANDOVER to Manifest.permission_group.PHONE,
40 | Manifest.permission.BODY_SENSORS to Manifest.permission_group.SENSORS,
41 | Manifest.permission.ACTIVITY_RECOGNITION to Manifest.permission_group.ACTIVITY_RECOGNITION,
42 | Manifest.permission.SEND_SMS to Manifest.permission_group.SMS,
43 | Manifest.permission.RECEIVE_SMS to Manifest.permission_group.SMS,
44 | Manifest.permission.READ_SMS to Manifest.permission_group.SMS,
45 | Manifest.permission.RECEIVE_WAP_PUSH to Manifest.permission_group.SMS,
46 | Manifest.permission.RECEIVE_MMS to Manifest.permission_group.SMS,
47 | Manifest.permission.READ_EXTERNAL_STORAGE to Manifest.permission_group.STORAGE,
48 | Manifest.permission.WRITE_EXTERNAL_STORAGE to Manifest.permission_group.STORAGE,
49 | Manifest.permission.ACCESS_MEDIA_LOCATION to Manifest.permission_group.STORAGE
50 | )
51 |
52 | private val groupSet = HashSet()
53 | override fun onCreate(savedInstanceState: Bundle?) {
54 | super.onCreate(savedInstanceState)
55 | binding = DataBindingUtil.inflate(
56 | LayoutInflater.from(getContext()),
57 | R.layout.custom_dialog_layout, null, false
58 | )
59 | binding!!.dialog = this
60 | setContentView(binding!!.root)
61 | buildPermissionsLayout()
62 | window?.let {
63 | val param = it.attributes
64 | val width = (context.resources.displayMetrics.widthPixels * 0.8).toInt()
65 | val height = param.height
66 | it.setLayout(width, height)
67 | }
68 | }
69 |
70 | private fun buildPermissionsLayout() {
71 | for (permission in permissions) {
72 | val permissionGroup = permissionMap[permission]
73 | if (permissionGroup != null && !groupSet.contains(permissionGroup)) {
74 | val textView = LayoutInflater.from(context)
75 | .inflate(R.layout.permissions_item,binding?.permissionsLayout, false) as TextView
76 | textView.text = context.packageManager.getPermissionGroupInfo(permissionGroup, 0)
77 | .loadLabel(context.packageManager)
78 | binding?.permissionsLayout?.addView(textView)
79 | groupSet.add(permissionGroup)
80 | }
81 | }
82 | }
83 |
84 |
85 | override fun getNegativeButton(): View? {
86 | return binding?.negativeBtn
87 | }
88 |
89 | override fun getPositiveButton(): View {
90 | return binding!!.positiveBtn
91 | }
92 |
93 | override fun getPermissionsToRequest(): List {
94 | return permissions;
95 | }
96 | }
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/util/ActivityLifeCycleCallBackIml.java:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.util;
2 |
3 | import android.app.Activity;
4 | import android.app.Application;
5 | import android.os.Bundle;
6 | import android.util.Log;
7 |
8 |
9 | /**
10 | * activity生命周期管理类
11 | * 你想象力有多丰富,这里就有多强大,
12 | * 以前放到BaseActivity的操作都可以放到这里
13 | * 使用:registerActivityLifecycleCallbacks(new ActivityLifeCycleCallBackIml());
14 | *
15 | * @author SouShin
16 | * @time 2018/12/10 15:38
17 | */
18 | public class ActivityLifeCycleCallBackIml implements Application.ActivityLifecycleCallbacks {
19 |
20 | @Override
21 | public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
22 | Log.i("activity生命周期管理类", activity.getLocalClassName());
23 | AppManager.getAppManager().addActivity(activity);
24 |
25 | }
26 |
27 | @Override
28 | public void onActivityStarted(final Activity activity) {
29 | // ALog.i("activity生命周期管理类", "onActivityStarted");
30 | }
31 |
32 | @Override
33 | public void onActivityResumed(Activity activity) {
34 | // ALog.i("activity生命周期管理类", "onActivityResumed");
35 | }
36 |
37 | @Override
38 | public void onActivityPaused(Activity activity) {
39 | // ALog.i("activity生命周期管理类", "onActivityPaused");
40 | }
41 |
42 | @Override
43 | public void onActivityStopped(Activity activity) {
44 | // ALog.i("activity生命周期管理类", "onActivityStopped");
45 | }
46 |
47 | @Override
48 | public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
49 | // ALog.i("activity生命周期管理类", "onActivitySaveInstanceState");
50 | }
51 |
52 | @Override
53 | public void onActivityDestroyed(Activity activity) {
54 | Log.i("activity生命周期管理类", "onActivityDestroyed");
55 | AppManager.getAppManager().finishActivity(activity);
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/util/AppManager.java:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.util;
2 |
3 | import android.app.Activity;
4 | import android.app.ActivityManager;
5 | import android.content.Context;
6 |
7 | import java.util.Stack;
8 |
9 | /**
10 | * 应用程序Activity管理类:用于Activity管理和应用程序退出
11 | *
12 | * @version 1.0 zhf
13 | */
14 | public class AppManager {
15 |
16 | private static Stack activityStack;
17 | private static AppManager instance;
18 |
19 | private AppManager() {
20 | }
21 |
22 | /**
23 | * 单一实例
24 | */
25 | public static AppManager getAppManager() {
26 | if (instance == null) {
27 | instance = new AppManager();
28 | }
29 | return instance;
30 | }
31 |
32 | /**
33 | * 添加Activity到堆栈
34 | */
35 | public void addActivity(Activity activity) {
36 | if (activityStack == null) {
37 | activityStack = new Stack();
38 | }
39 | activityStack.add(activity);
40 | }
41 |
42 | /**
43 | * 获取当前Activity(堆栈中最后一个压入的)
44 | */
45 | public Activity currentActivity() {
46 | Activity activity = activityStack.lastElement();
47 | return activity;
48 | }
49 |
50 | /**
51 | * 获取当前Activity(堆栈中最后一个压入的)
52 | */
53 | public Activity getActivity(Class clz) {
54 | for (Activity activity : activityStack) {
55 | if (activity.getClass() == clz) {
56 | return activity;
57 | }
58 | }
59 | return null;
60 | }
61 |
62 | /**
63 | * 结束当前Activity(堆栈中最后一个压入的)
64 | */
65 | public void finishActivity() {
66 | Activity activity = activityStack.lastElement();
67 | finishActivity(activity);
68 | }
69 |
70 | /**
71 | * 结束指定的Activity
72 | */
73 | public void finishActivity(Activity activity) {
74 | if (activity != null) {
75 | activityStack.remove(activity);
76 | activity.finish();
77 | activity = null;
78 | }
79 | }
80 |
81 | /**
82 | * 结束指定类名的Activity
83 | */
84 | public void finishActivity(Class> cls) {
85 | for (Activity activity : activityStack) {
86 | if (activity.getClass().equals(cls)) {
87 | finishActivity(activity);
88 | }
89 | }
90 | }
91 |
92 | /**
93 | * 结束所有Activity
94 | */
95 | public void finishAllActivity() {
96 | for (int i = 0, size = activityStack.size(); i < size; i++) {
97 | if (null != activityStack.get(i)) {
98 | activityStack.get(i).finish();
99 | }
100 | }
101 | activityStack.clear();
102 | }
103 |
104 | /**
105 | * 结束N-1个Activity
106 | */
107 | public void finishN1Activity() {
108 | for (int i = 0, size = activityStack.size(); i < size - 1; i++) {
109 | if (null != activityStack.get(i)) {
110 | activityStack.get(i).finish();
111 | }
112 | }
113 | activityStack.clear();
114 | }
115 |
116 | /**
117 | * 退出应用程序
118 | */
119 |
120 | public void AppExit(Context context) {
121 | try {
122 | finishAllActivity();
123 | ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
124 | activityMgr.restartPackage(context.getPackageName());
125 | android.os.Process.killProcess(android.os.Process.myPid());
126 | System.exit(0);
127 | } catch (Exception e) {
128 |
129 | }
130 | }
131 | }
--------------------------------------------------------------------------------
/mvvm/src/main/java/com/aranandroid/mvvm/util/BaseExecutors.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm.util
2 |
3 | import android.os.Handler
4 | import android.os.Looper
5 | import java.util.concurrent.Executor
6 | import java.util.concurrent.Executors
7 |
8 | object BaseExecutors {
9 |
10 | val diskIO = Executors.newSingleThreadExecutor()
11 |
12 | val networkIO = Executors.newFixedThreadPool(3)
13 |
14 | val mainThread = MainThreadExecutor()
15 |
16 | class MainThreadExecutor : Executor {
17 | val handler = Handler(Looper.getMainLooper())
18 | override fun execute(command: Runnable) {
19 | handler.post(command)
20 | }
21 | }
22 |
23 | }
--------------------------------------------------------------------------------
/mvvm/src/main/res/anim/slide_in_left.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
--------------------------------------------------------------------------------
/mvvm/src/main/res/anim/slide_in_right.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
--------------------------------------------------------------------------------
/mvvm/src/main/res/anim/slide_in_zoom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
11 |
15 |
--------------------------------------------------------------------------------
/mvvm/src/main/res/anim/slide_out_left.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
--------------------------------------------------------------------------------
/mvvm/src/main/res/anim/slide_out_right.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
--------------------------------------------------------------------------------
/mvvm/src/main/res/anim/slide_out_zoom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
11 |
15 |
--------------------------------------------------------------------------------
/mvvm/src/main/res/drawable/custom_dialog_bg.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/mvvm/src/main/res/drawable/negative_button_bg.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/mvvm/src/main/res/drawable/positive_button_bg.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/mvvm/src/main/res/layout/custom_dialog_layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
14 |
15 |
25 |
26 |
32 |
33 |
38 |
39 |
40 |
41 |
48 |
49 |
56 |
57 |
66 |
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/mvvm/src/main/res/layout/permissions_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
--------------------------------------------------------------------------------
/mvvm/src/main/res/mipmap/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AranAndroid009/Mvvm/94e887210b10d23982f5907cd96b3470f8425c9c/mvvm/src/main/res/mipmap/ic_launcher.png
--------------------------------------------------------------------------------
/mvvm/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
16 |
17 |
--------------------------------------------------------------------------------
/mvvm/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
20 |
21 |
--------------------------------------------------------------------------------
/mvvm/src/test/java/com/aranandroid/mvvm/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.aranandroid.mvvm
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':mvvm'
2 | include ':app'
3 | rootProject.name='Mvvm'
4 |
--------------------------------------------------------------------------------