├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── me │ │ └── jessyan │ │ └── lifecyclemodel │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── me │ │ │ └── jessyan │ │ │ └── lifecyclemodel │ │ │ └── demo │ │ │ ├── AFragment.java │ │ │ ├── BFragment.java │ │ │ ├── MainActivity.java │ │ │ └── UserLifecycleModel.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── me │ └── jessyan │ └── lifecyclemodel │ └── ExampleUnitTest.java ├── art └── Lifecyclemodel-lifecycle.jpg ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── lifecyclemodel ├── .gitignore ├── bintray.gradle ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── me │ │ └── jessyan │ │ └── lifecyclemodel │ │ ├── EmptyActivityLifecycleCallbacks.java │ │ ├── HolderFragment.java │ │ ├── LifecycleModel.java │ │ ├── LifecycleModelProviders.java │ │ ├── LifecycleModelStore.java │ │ ├── LifecycleModelStores.java │ │ └── cache │ │ ├── Cache.java │ │ └── LruCache.java │ └── res │ └── values │ └── strings.xml └── 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 38 | 39 | # Keystore files 40 | *.jks 41 | 42 | # External native build folder generated in Android Studio 2.2 and later 43 | .externalNativeBuild 44 | 45 | # Google Services (e.g. APIs or Firebase) 46 | google-services.json 47 | 48 | # Freeline 49 | freeline.py 50 | freeline/ 51 | freeline_project_description.json 52 | 53 | # MacOS 54 | .DS_Store 55 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | jdk: oraclejdk8 3 | 4 | env: 5 | global: 6 | - ANDROID_API_LEVEL=26 7 | - ANDROID_BUILD_TOOLS_VERSION=26.0.2 8 | - TRAVIS_SECURE_ENV_VARS=true 9 | 10 | android: 11 | components: 12 | # The BuildTools version used by your project 13 | - tools 14 | - platform-tools 15 | - build-tools-$ANDROID_BUILD_TOOLS_VERSION 16 | - extra-android-m2repository 17 | - extra-google-android-support 18 | 19 | # The SDK version used to compile your project 20 | - android-$ANDROID_API_LEVEL 21 | licenses: 22 | - '.+' 23 | 24 | script: 25 | - ./gradlew clean 26 | - ./gradlew assembleDebug 27 | -------------------------------------------------------------------------------- /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 | # LifecycleModel 2 | [ ![Jcenter](https://img.shields.io/badge/Jcenter-v1.0.1-brightgreen.svg?style=flat-square) ](https://bintray.com/jessyancoding/maven/lifecyclemodel/1.0.1/link) 3 | [ ![Build Status](https://travis-ci.org/JessYanCoding/LifecycleModel.svg?branch=master) ](https://travis-ci.org/JessYanCoding/LifecycleModel) 4 | [ ![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-LifecycleModel-brightgreen.svg?style=flat-square) ](https://android-arsenal.com/details/1/6545) 5 | [ ![API](https://img.shields.io/badge/API-14%2B-blue.svg?style=flat-square) ](https://developer.android.com/about/versions/android-4.0.html) 6 | [ ![License](http://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat-square) ](http://www.apache.org/licenses/LICENSE-2.0) 7 | [ ![Author](https://img.shields.io/badge/Author-JessYan-orange.svg?style=flat-square) ](https://www.jianshu.com/u/1d0c0bc634db) 8 | [ ![QQ-Group](https://img.shields.io/badge/QQ%E7%BE%A4-455850365%20%7C%20301733278-orange.svg?style=flat-square) ](https://shang.qq.com/wpa/qunwpa?idkey=7e59e59145e6c7c68932ace10f52790636451f01d1ecadb6a652b1df234df753) 9 | 10 | ## The LifecycleModel class is designed to store and manage UI-related data in a lifecycle conscious way, the LifecycleModel class allows data to survive configuration changes such as screen rotations, it also handles the communication of the Activity / Fragment with the rest of the application, base on [ViewModel](https://developer.android.google.cn/topic/libraries/architecture/viewmodel.html) 11 | 12 | ## Introduction 13 | **LifecycleModel** 基于 Google 在 2017 年 I/O 大会上发布的 Android 架构组件中的 [**ViewModel**](https://developer.android.google.cn/topic/libraries/architecture/viewmodel.html), 可以帮助 **Activity** 和 **Fragment** 储存和管理一些与 UI 相关以及他们必需的数据, 避免数据在屏幕旋转或配置更改时发生的数据丢失, 还可以帮助开发者轻易实现 **Fragment** 与 **Fragment** 之间, **Activity** 与 **Fragment** 之间的通讯以及共享数据, 因为我看到 Google 让 **MVVM** 框架中的 **ViewModel** 具有了这些功能, 所以我也想让 **MVP** 框架中的 **Presenter**, 乃至其他更多的模块都具有这些功能, 所以 **LifecycleModel** 诞生了 14 | 15 | > [**框架的分析和思路**](https://juejin.im/post/5a31f6b951882503eb4b4b21) 16 | 17 | ## Lifecycle 18 | ![lifecycle](https://raw.githubusercontent.com/JessYanCoding/LifecycleModel/master/art/Lifecyclemodel-lifecycle.jpg) 19 | 20 | ## Download 21 | ``` gradle 22 | implementation 'me.jessyan:lifecyclemodel:1.0.1' 23 | ``` 24 | 25 | ## Usage 26 | ### Step 1 27 | ```java 28 | public class UserLifecycleModel implements LifecycleModel { 29 | private int id; 30 | 31 | public UserLifecycleModel(int id) { 32 | this.id = id; 33 | } 34 | 35 | void doAction() { 36 | 37 | } 38 | 39 | @Override 40 | public void onCleared() { 41 | //release resources 42 | } 43 | } 44 | ``` 45 | 46 | ### Step 2 47 | ```java 48 | //Put data 49 | LifecycleModelProviders.of(activity/fragment).put(UserLifecycleModel.class.getName(), new UserLifecycleModel(1)); 50 | 51 | //Get data 52 | LifecycleModelProviders.of(activity/fragment).get(UserLifecycleModel.class.getName()); 53 | 54 | //Remove data 55 | LifecycleModelProviders.of(activity/fragment).remove(UserLifecycleModel.class.getName()); 56 | ``` 57 | 58 | ### Communication of the Activity / Fragment 59 | ```java 60 | public class UserLifecycleModel implements LifecycleModel { 61 | private Subject mSubject = PublishSubject.create(); 62 | 63 | public void doAction(String s) { 64 | mSubject.onNext(s); 65 | } 66 | 67 | public void addAction(Action1 action) { 68 | mSubject.subscribe(action); 69 | } 70 | } 71 | 72 | public class AFragment extends Fragment { 73 | @Override 74 | public void onCreate(@Nullable Bundle savedInstanceState) { 75 | super.onCreate(savedInstanceState); 76 | UserLifecycleModel lifecycleModel = LifecycleModelProviders.of(getActivity()).get(UserLifecycleModel.class.getName()); 77 | lifecycleModel.addAction(new Action1() { 78 | @Override 79 | public void call(String s) { 80 | // Update the UI. 81 | } 82 | }); 83 | } 84 | } 85 | 86 | public class BFragment extends Fragment { 87 | @Override 88 | public void onStart() { 89 | super.onStart(); 90 | UserLifecycleModel lifecycleModel = LifecycleModelProviders.of(getActivity()).get(UserLifecycleModel.class.getName()); 91 | lifecycleModel.doAction("JessYan"); 92 | } 93 | } 94 | ``` 95 | 96 | 97 | ## About Me 98 | * **Email**: 99 | * **Home**: 100 | * **掘金**: 101 | * **简书**: 102 | 103 | ## License 104 | ``` 105 | Copyright 2017, jessyan 106 | 107 | Licensed under the Apache License, Version 2.0 (the "License"); 108 | you may not use this file except in compliance with the License. 109 | You may obtain a copy of the License at 110 | 111 | http://www.apache.org/licenses/LICENSE-2.0 112 | 113 | Unless required by applicable law or agreed to in writing, software 114 | distributed under the License is distributed on an "AS IS" BASIS, 115 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 116 | See the License for the specific language governing permissions and 117 | limitations under the License. 118 | ``` 119 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion rootProject.compileSdkVersion 5 | buildToolsVersion rootProject.buildToolsVersion 6 | defaultConfig { 7 | applicationId "me.jessyan.lifecyclemodel.demo" 8 | minSdkVersion rootProject.minSdkVersion 9 | targetSdkVersion rootProject.targetSdkVersion 10 | versionCode rootProject.versionCode 11 | versionName rootProject.versionName 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | implementation fileTree(dir: 'libs', include: ['*.jar']) 24 | implementation 'com.android.support:appcompat-v7:26.1.0' 25 | implementation 'io.reactivex:rxjava:1.3.0' 26 | testImplementation 'junit:junit:4.12' 27 | androidTestImplementation 'com.android.support.test:runner:1.0.1' 28 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' 29 | // implementation 'me.jessyan:lifecyclemodel:1.0.1' 30 | implementation project(':lifecyclemodel') 31 | } 32 | -------------------------------------------------------------------------------- /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/me/jessyan/lifecyclemodel/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package me.jessyan.lifecyclemodel; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumented test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("me.jessyan.lifecyclemodel", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /app/src/main/java/me/jessyan/lifecyclemodel/demo/AFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 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 me.jessyan.lifecyclemodel.demo; 18 | 19 | import android.os.Bundle; 20 | import android.support.annotation.Nullable; 21 | import android.support.v4.app.Fragment; 22 | import android.support.v4.app.FragmentManager; 23 | import android.util.Log; 24 | 25 | import me.jessyan.lifecyclemodel.LifecycleModelProviders; 26 | import rx.functions.Action1; 27 | 28 | /** 29 | * ================================================ 30 | * AFragment 通过 {@link UserLifecycleModel#addAction(Action1)} 注册需要与其他组件通讯的事件以及逻辑 31 | * 32 | * Created by JessYan on 09/12/2017 15:31 33 | * Contact me 34 | * Follow me 35 | * ================================================ 36 | */ 37 | 38 | public class AFragment extends Fragment { 39 | 40 | public static AFragment createAFragment(FragmentManager fragmentManager) { 41 | AFragment fragment = new AFragment(); 42 | fragmentManager.beginTransaction().add(fragment, AFragment.class.getName()).commit(); 43 | return fragment; 44 | } 45 | 46 | @Override 47 | public void onCreate(@Nullable Bundle savedInstanceState) { 48 | super.onCreate(savedInstanceState); 49 | UserLifecycleModel lifecycleModel = LifecycleModelProviders.of(getActivity()).get(UserLifecycleModel.class.getName()); 50 | lifecycleModel.addAction(new Action1() { 51 | @Override 52 | public void call(String s) { 53 | // Update the UI. 54 | Log.d("AFragment", s); 55 | } 56 | }); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /app/src/main/java/me/jessyan/lifecyclemodel/demo/BFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 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 me.jessyan.lifecyclemodel.demo; 18 | 19 | import android.support.v4.app.Fragment; 20 | import android.support.v4.app.FragmentManager; 21 | 22 | import me.jessyan.lifecyclemodel.LifecycleModelProviders; 23 | 24 | /** 25 | * ================================================ 26 | * BFragment 通过 {@link UserLifecycleModel#doAction(String)} 与其他组件开始通讯, (AFragment 与 BFragment 不存在耦合关系即可通讯以及共享数据) 27 | * 28 | * Created by JessYan on 09/12/2017 15:31 29 | * Contact me 30 | * Follow me 31 | * ================================================ 32 | */ 33 | 34 | public class BFragment extends Fragment { 35 | 36 | public static BFragment createBFragment(FragmentManager fragmentManager) { 37 | BFragment fragment = new BFragment(); 38 | fragmentManager.beginTransaction().add(fragment, BFragment.class.getName()).commit(); 39 | return fragment; 40 | } 41 | 42 | @Override 43 | public void onStart() { 44 | super.onStart(); 45 | UserLifecycleModel lifecycleModel = LifecycleModelProviders.of(getActivity()).get(UserLifecycleModel.class.getName()); 46 | lifecycleModel.doAction("JessYan"); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /app/src/main/java/me/jessyan/lifecyclemodel/demo/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 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 me.jessyan.lifecyclemodel.demo; 18 | 19 | import android.os.Bundle; 20 | import android.support.v7.app.AppCompatActivity; 21 | 22 | import java.util.HashMap; 23 | 24 | import me.jessyan.lifecyclemodel.LifecycleModelProviders; 25 | 26 | /** 27 | * ================================================ 28 | * 此框架的主要功能是帮助 Activity / Fragment 存储和管理与 UI 相关的数据, 并且可以避免 Activity 重建时导致的数据丢失 29 | * 使用方式与向 {@link HashMap} 中 {@link HashMap#put(Object, Object)}, {@link HashMap#get(Object)} 数据一致 30 | * Demo 中就不再做过多展示 31 | *

32 | * Demo 中主要展示两个 Fragment 之间的通讯 33 | *

34 | * Created by JessYan on 09/12/2017 11:17 35 | * Contact me 36 | * Follow me 37 | * ================================================ 38 | */ 39 | 40 | public class MainActivity extends AppCompatActivity { 41 | 42 | @Override 43 | protected void onCreate(Bundle savedInstanceState) { 44 | super.onCreate(savedInstanceState); 45 | setContentView(R.layout.activity_main); 46 | //在 Fragment 获取 UserLifecycleModel 之前, 需要将它初始化以及存储起来 47 | LifecycleModelProviders.of(this).put(UserLifecycleModel.class.getName(), new UserLifecycleModel()); 48 | AFragment.createAFragment(getSupportFragmentManager()); 49 | BFragment.createBFragment(getSupportFragmentManager()); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /app/src/main/java/me/jessyan/lifecyclemodel/demo/UserLifecycleModel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 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 me.jessyan.lifecyclemodel.demo; 18 | 19 | import me.jessyan.lifecyclemodel.LifecycleModel; 20 | import rx.functions.Action1; 21 | import rx.subjects.PublishSubject; 22 | import rx.subjects.Subject; 23 | 24 | /** 25 | * ================================================ 26 | * {@link LifecycleModel} 可以用来存储以及管理数据, 也可以作为 MVP 模式中的 Presenter (只要实现 {@link LifecycleModel} 即可) 27 | * 或者 MVVM 模式中的 ViewModel (只要实现 {@link LifecycleModel} 即可) 用来管理业务逻辑, 更多使用方式等着你去发现 28 | *

29 | * 这里可以使用 Rxjava, LiveData, 或者 {@link java.util.Observable} 乃至自己定义的监听器实现组件之间的通讯 30 | * 本质就是使用观察者模式, 使用什么方式实现, 看你的心情 31 | *

32 | * Created by JessYan on 09/12/2017 11:17 33 | * Contact me 34 | * Follow me 35 | * ================================================ 36 | */ 37 | 38 | public class UserLifecycleModel implements LifecycleModel { 39 | private Subject mSubject = PublishSubject.create(); 40 | 41 | public void doAction(String s) { 42 | mSubject.onNext(s); 43 | } 44 | 45 | public void addAction(Action1 action) { 46 | mSubject.subscribe(action); 47 | } 48 | 49 | @Override 50 | public void onCleared() { 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /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/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 11 | 16 | 21 | 26 | 31 | 36 | 41 | 46 | 51 | 56 | 61 | 66 | 71 | 76 | 81 | 86 | 91 | 96 | 101 | 106 | 111 | 116 | 121 | 126 | 131 | 136 | 141 | 146 | 151 | 156 | 161 | 166 | 171 | 172 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JessYanCoding/LifecycleModel/4ea64839552e21af75c26b74981998da824c9ec8/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JessYanCoding/LifecycleModel/4ea64839552e21af75c26b74981998da824c9ec8/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JessYanCoding/LifecycleModel/4ea64839552e21af75c26b74981998da824c9ec8/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JessYanCoding/LifecycleModel/4ea64839552e21af75c26b74981998da824c9ec8/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JessYanCoding/LifecycleModel/4ea64839552e21af75c26b74981998da824c9ec8/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JessYanCoding/LifecycleModel/4ea64839552e21af75c26b74981998da824c9ec8/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JessYanCoding/LifecycleModel/4ea64839552e21af75c26b74981998da824c9ec8/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JessYanCoding/LifecycleModel/4ea64839552e21af75c26b74981998da824c9ec8/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JessYanCoding/LifecycleModel/4ea64839552e21af75c26b74981998da824c9ec8/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JessYanCoding/LifecycleModel/4ea64839552e21af75c26b74981998da824c9ec8/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | LifecycleModel 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/me/jessyan/lifecyclemodel/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package me.jessyan.lifecyclemodel; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.assertEquals; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /art/Lifecyclemodel-lifecycle.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JessYanCoding/LifecycleModel/4ea64839552e21af75c26b74981998da824c9ec8/art/Lifecyclemodel-lifecycle.jpg -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | 5 | repositories { 6 | google() 7 | jcenter() 8 | } 9 | dependencies { 10 | classpath 'com.android.tools.build:gradle:3.0.0' 11 | classpath 'com.novoda:bintray-release:0.8.0' 12 | 13 | // NOTE: Do not place your application dependencies here; they belong 14 | // in the individual module build.gradle files 15 | } 16 | } 17 | 18 | allprojects { 19 | repositories { 20 | google() 21 | jcenter() 22 | } 23 | } 24 | 25 | task clean(type: Delete) { 26 | delete rootProject.buildDir 27 | } 28 | 29 | 30 | ext { 31 | minSdkVersion = 14 32 | targetSdkVersion = 26 33 | compileSdkVersion = 26 34 | buildToolsVersion = "26.0.2" 35 | versionCode = 3 36 | versionName = "1.0.1" 37 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | 19 | android.enableBuildCache=true 20 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JessYanCoding/LifecycleModel/4ea64839552e21af75c26b74981998da824c9ec8/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Dec 07 11:49:57 CST 2017 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-4.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /lifecyclemodel/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /lifecyclemodel/bintray.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.novoda.bintray-release' 2 | 3 | allprojects { 4 | repositories { 5 | jcenter() 6 | } 7 | tasks.withType(Javadoc) { 8 | options{ 9 | encoding "UTF-8" 10 | charSet 'UTF-8' 11 | links "http://docs.oracle.com/javase/7/docs/api" 12 | } 13 | options.addStringOption('Xdoclint:none', '-quiet') 14 | } 15 | } 16 | 17 | 18 | def siteUrl = 'https://github.com/JessYanCoding/LifecycleModel' // 项目的主页 19 | 20 | publish { 21 | userOrg = 'jessyancoding' //bintray注册的用户名 22 | groupId = 'me.jessyan' //compile引用时的第1部分groupId 23 | artifactId = 'lifecyclemodel' //compile引用时的第2部分项目名 24 | publishVersion = rootProject.versionName //compile引用时的第3部分版本号 25 | desc = 'The LifecycleModel class is designed to store and manage UI-related data in a lifecycle conscious way, The LifecycleModel class allows data to survive configuration changes such as screen rotations, It also handles the communication of the Activity / Fragment with the rest of the application.' 26 | website = siteUrl 27 | } -------------------------------------------------------------------------------- /lifecyclemodel/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion rootProject.compileSdkVersion 5 | buildToolsVersion rootProject.buildToolsVersion 6 | 7 | defaultConfig { 8 | minSdkVersion rootProject.minSdkVersion 9 | targetSdkVersion rootProject.targetSdkVersion 10 | versionCode rootProject.versionCode 11 | versionName rootProject.versionName 12 | consumerProguardFiles 'proguard-rules.pro' 13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 14 | } 15 | 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | lintOptions { 23 | abortOnError false 24 | warning 'InvalidPackage' 25 | } 26 | } 27 | 28 | dependencies { 29 | provided 'com.android.support:appcompat-v7:26.1.0' 30 | } 31 | 32 | apply from: 'bintray.gradle' -------------------------------------------------------------------------------- /lifecyclemodel/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 | 23 | -keep class me.jessyan.lifecyclemodel.** { *; } 24 | -keep interface me.jessyan.lifecyclemodel.** { *; } -------------------------------------------------------------------------------- /lifecyclemodel/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | -------------------------------------------------------------------------------- /lifecyclemodel/src/main/java/me/jessyan/lifecyclemodel/EmptyActivityLifecycleCallbacks.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 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 me.jessyan.lifecyclemodel; 18 | 19 | import android.app.Activity; 20 | import android.app.Application; 21 | import android.os.Bundle; 22 | 23 | /** 24 | * Created by JessYan on 21/11/2017 16:57 25 | * Contact me 26 | * Follow me 27 | */ 28 | class EmptyActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks { 29 | @Override 30 | public void onActivityCreated(Activity activity, Bundle savedInstanceState) { 31 | } 32 | 33 | @Override 34 | public void onActivityStarted(Activity activity) { 35 | } 36 | 37 | @Override 38 | public void onActivityResumed(Activity activity) { 39 | } 40 | 41 | @Override 42 | public void onActivityPaused(Activity activity) { 43 | } 44 | 45 | @Override 46 | public void onActivityStopped(Activity activity) { 47 | } 48 | 49 | @Override 50 | public void onActivitySaveInstanceState(Activity activity, Bundle outState) { 51 | } 52 | 53 | @Override 54 | public void onActivityDestroyed(Activity activity) { 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /lifecyclemodel/src/main/java/me/jessyan/lifecyclemodel/HolderFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 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 me.jessyan.lifecyclemodel; 18 | 19 | import android.app.Activity; 20 | import android.app.Application.ActivityLifecycleCallbacks; 21 | import android.os.Bundle; 22 | import android.support.annotation.Nullable; 23 | import android.support.annotation.RestrictTo; 24 | import android.support.v4.app.Fragment; 25 | import android.support.v4.app.FragmentActivity; 26 | import android.support.v4.app.FragmentManager; 27 | import android.support.v4.app.FragmentManager.FragmentLifecycleCallbacks; 28 | import android.util.Log; 29 | 30 | import java.util.HashMap; 31 | import java.util.Map; 32 | 33 | /** 34 | * @hide 此类为实现 {@link LifecycleModel} 的核心类 35 | *

36 | * Created by JessYan on 21/11/2017 16:57 37 | * Contact me 38 | * Follow me 39 | */ 40 | @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) 41 | public class HolderFragment extends Fragment { 42 | private static final String LOG_TAG = "LifecycleModelStores"; 43 | 44 | private static final HolderFragmentManager sHolderFragmentManager = new HolderFragmentManager(); 45 | 46 | /** 47 | * @hide 48 | */ 49 | @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) 50 | public static final String HOLDER_TAG = 51 | "me.jessyan.lifecyclemodel.state.StateProviderHolderFragment"; 52 | 53 | private final LifecycleModelStore mLifecycleModelStore = new LifecycleModelStore(); 54 | 55 | public HolderFragment() { 56 | setRetainInstance(true); 57 | } 58 | 59 | @Override 60 | public void onCreate(@Nullable Bundle savedInstanceState) { 61 | super.onCreate(savedInstanceState); 62 | sHolderFragmentManager.holderFragmentCreated(this); 63 | } 64 | 65 | @Override 66 | public void onSaveInstanceState(Bundle outState) { 67 | super.onSaveInstanceState(outState); 68 | } 69 | 70 | @Override 71 | public void onDestroy() { 72 | super.onDestroy(); 73 | mLifecycleModelStore.clear(); 74 | } 75 | 76 | public LifecycleModelStore getLifecycleModelStore() { 77 | return mLifecycleModelStore; 78 | } 79 | 80 | /** 81 | * @hide 82 | */ 83 | @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) 84 | public static HolderFragment holderFragmentFor(FragmentActivity activity) { 85 | return sHolderFragmentManager.holderFragmentFor(activity); 86 | } 87 | 88 | /** 89 | * @hide 90 | */ 91 | @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) 92 | public static HolderFragment holderFragmentFor(Fragment fragment) { 93 | return sHolderFragmentManager.holderFragmentFor(fragment); 94 | } 95 | 96 | @SuppressWarnings("WeakerAccess") 97 | static class HolderFragmentManager { 98 | private Map mNotCommittedActivityHolders = new HashMap<>(); 99 | private Map mNotCommittedFragmentHolders = new HashMap<>(); 100 | 101 | private ActivityLifecycleCallbacks mActivityCallbacks = 102 | new EmptyActivityLifecycleCallbacks() { 103 | @Override 104 | public void onActivityDestroyed(Activity activity) { 105 | HolderFragment fragment = mNotCommittedActivityHolders.remove(activity); 106 | if (fragment != null) { 107 | Log.e(LOG_TAG, "Failed to save a LifecycleModel for " + activity); 108 | } 109 | } 110 | }; 111 | 112 | private boolean mActivityCallbacksIsAdded = false; 113 | 114 | private FragmentLifecycleCallbacks mParentDestroyedCallback = 115 | new FragmentLifecycleCallbacks() { 116 | @Override 117 | public void onFragmentDestroyed(FragmentManager fm, Fragment parentFragment) { 118 | super.onFragmentDestroyed(fm, parentFragment); 119 | HolderFragment fragment = mNotCommittedFragmentHolders.remove( 120 | parentFragment); 121 | if (fragment != null) { 122 | Log.e(LOG_TAG, "Failed to save a LifecycleModel for " + parentFragment); 123 | } 124 | } 125 | }; 126 | 127 | void holderFragmentCreated(Fragment holderFragment) { 128 | Fragment parentFragment = holderFragment.getParentFragment(); 129 | if (parentFragment != null) { 130 | mNotCommittedFragmentHolders.remove(parentFragment); 131 | parentFragment.getFragmentManager().unregisterFragmentLifecycleCallbacks( 132 | mParentDestroyedCallback); 133 | } else { 134 | mNotCommittedActivityHolders.remove(holderFragment.getActivity()); 135 | } 136 | } 137 | 138 | private static HolderFragment findHolderFragment(FragmentManager manager) { 139 | if (manager.isDestroyed()) { 140 | throw new IllegalStateException("Can't access LifecycleModels from onDestroy"); 141 | } 142 | 143 | Fragment fragmentByTag = manager.findFragmentByTag(HOLDER_TAG); 144 | if (fragmentByTag != null && !(fragmentByTag instanceof HolderFragment)) { 145 | throw new IllegalStateException("Unexpected " 146 | + "fragment instance was returned by HOLDER_TAG"); 147 | } 148 | return (HolderFragment) fragmentByTag; 149 | } 150 | 151 | private static HolderFragment createHolderFragment(FragmentManager fragmentManager) { 152 | HolderFragment holder = new HolderFragment(); 153 | fragmentManager.beginTransaction().add(holder, HOLDER_TAG).commitAllowingStateLoss(); 154 | return holder; 155 | } 156 | 157 | HolderFragment holderFragmentFor(FragmentActivity activity) { 158 | FragmentManager fm = activity.getSupportFragmentManager(); 159 | HolderFragment holder = findHolderFragment(fm); 160 | if (holder != null) { 161 | return holder; 162 | } 163 | holder = mNotCommittedActivityHolders.get(activity); 164 | if (holder != null) { 165 | return holder; 166 | } 167 | 168 | if (!mActivityCallbacksIsAdded) { 169 | mActivityCallbacksIsAdded = true; 170 | activity.getApplication().registerActivityLifecycleCallbacks(mActivityCallbacks); 171 | } 172 | holder = createHolderFragment(fm); 173 | mNotCommittedActivityHolders.put(activity, holder); 174 | return holder; 175 | } 176 | 177 | HolderFragment holderFragmentFor(Fragment parentFragment) { 178 | FragmentManager fm = parentFragment.getChildFragmentManager(); 179 | HolderFragment holder = findHolderFragment(fm); 180 | if (holder != null) { 181 | return holder; 182 | } 183 | holder = mNotCommittedFragmentHolders.get(parentFragment); 184 | if (holder != null) { 185 | return holder; 186 | } 187 | 188 | parentFragment.getFragmentManager() 189 | .registerFragmentLifecycleCallbacks(mParentDestroyedCallback, false); 190 | holder = createHolderFragment(fm); 191 | mNotCommittedFragmentHolders.put(parentFragment, holder); 192 | return holder; 193 | } 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /lifecyclemodel/src/main/java/me/jessyan/lifecyclemodel/LifecycleModel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 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 me.jessyan.lifecyclemodel; 18 | 19 | import android.app.Activity; 20 | import android.support.v4.app.Fragment; 21 | 22 | /** 23 | * {@link LifecycleModelProviders} 配合 {@link LifecycleModel} 的实现类可以帮助 {@link Activity} 和 {@link Fragment} 24 | * 储存存和管理一些与 UI 相关以及他们必需的数据, 并且这些数据在屏幕旋转或配置更改引起的 {@link Activity} 重建的情况下也会被保留, 直到最后被 finish 25 | * 但是 {@link LifecycleModel} 的实现类切勿直接引用 {@link Activity} 和 {@link Fragment} 以及他们里面 UI 元素 26 | *

27 | * 他还可以让开发者能够在绑定在同一个 {@link Activity} 之下的多个不同的 {@link Fragment} 之间通讯以及共享数据 (Activity 与 Fragmnet 之间的通讯以及共享数据也可以) 28 | * 使用这种方式进行通讯, {@link Fragment} 之间不存在任何耦合关系 29 | *

30 | * {@link LifecycleModel} 可以用来存储以及管理数据, 也可以作为 MVP 模式中的 Presenter (只要实现 {@link LifecycleModel} 即可) 31 | * 或者 MVVM 模式中的 ViewModel (只要实现 {@link LifecycleModel} 即可) 用来管理业务逻辑, 更多使用方式等着你去发现 32 | *

33 |  * public class UserLifecycleModel implements LifecycleModel {
34 |  *     private int id;
35 |  *
36 |  *     public UserLifecycleModel(int id) {
37 |  *          this.id = id;
38 |  *     }
39 |  *
40 |  *     void doAction() {
41 |  *
42 |  *     }
43 |  * }
44 |  *
45 |  *
46 |  * public class MyActivity extends AppCompatActivity {
47 |  *
48 |  *     protected void onCreate(@Nullable Bundle savedInstanceState) {
49 |  *          LifecycleModelProviders.of(this).put(UserLifecycleModel.class.getName(), new UserLifecycleModel(123));
50 |  *          fragmentManager.beginTransaction().add(R.layout.afragment_container_Id, new AFragment).commit();
51 |  *          fragmentManager.beginTransaction().add(R.layout.bfragment_container_Id, new BFragment).commit();
52 |  *     }
53 |  * }
54 |  * 
55 | *

56 | * 只要 AFragment 和 BFragment 绑定在同一个 Activity 下, 并使用同一个 key, 那获取到的 UserLifecycleModel 就是同一个对象 57 | * 这时就可以使用这个 UserLifecycleModel 进行通讯 (Fragment 之间如何通讯? 比如说接口回调? 观察者模式?) 和共享数据 58 | * 这时 Fragment 之间并不知道彼此, 也不互相持有, 所以也不存在耦合关系 59 | *

60 | *

61 |  * public class AFragment extends Fragment {
62 |  *     public void onStart() {
63 |  *         UserLifecycleModel userLifecycleModel = LifecycleModelProviders.of(getActivity()).get(UserLifecycleModel.class.getName());
64 |  *     }
65 |  * }
66 |  *
67 |  * public class BFragment extends Fragment {
68 |  *     public void onStart() {
69 |  *         UserLifecycleModel userLifecycleModel = LifecycleModelProviders.of(getActivity()).get(UserLifecycleModel.class.getName());
70 |  *     }
71 |  * }
72 |  *
73 |  * 
74 | * 75 | * @see 76 | * 功能和 Android Architecture 中的 ViewModel 一致, 但放开了权限不仅可以存储 ViewModel, 还可以存储任意自定义对象 (也可以试试存储 Presenter 哦!) 77 | *

78 | * Created by JessYan on 21/11/2017 16:57 79 | * Contact me 80 | * Follow me 81 | */ 82 | public interface LifecycleModel { 83 | /** 84 | * 这个方法会在宿主 {@link Activity} 或 {@link Fragment} 被彻底销毁时被调用, 在这个方法中释放一些资源可以避免内存泄漏 85 | */ 86 | @SuppressWarnings("WeakerAccess") 87 | void onCleared(); 88 | } 89 | -------------------------------------------------------------------------------- /lifecyclemodel/src/main/java/me/jessyan/lifecyclemodel/LifecycleModelProviders.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 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 me.jessyan.lifecyclemodel; 18 | 19 | import android.app.Activity; 20 | import android.app.Application; 21 | import android.support.annotation.MainThread; 22 | import android.support.annotation.NonNull; 23 | import android.support.v4.app.Fragment; 24 | import android.support.v4.app.FragmentActivity; 25 | 26 | /** 27 | * {@link LifecycleModelProviders} 配合 {@link LifecycleModel} 的实现类可以帮助 {@link Activity} 和 {@link Fragment} 28 | * 储存和管理一些与 UI 相关以及他们必需的数据, 并且这些数据在屏幕旋转或配置更改引起的 {@link Activity} 重建的情况下也会被保留, 直到最后被 finish 29 | * 但是 {@link LifecycleModel} 的实现类切勿直接引用 {@link Activity} 和 {@link Fragment} 以及他们里面 UI 元素 30 | *

31 | * 他还可以让开发者能够在绑定在同一个 {@link Activity} 之下的多个不同的 {@link Fragment} 之间通讯以及共享数据 (Activity 与 Fragmnet 之间的通讯以及共享数据也可以) 32 | * 使用这种方式进行通讯, {@link Fragment} 之间不存在任何耦合关系 33 | *

34 | * {@link LifecycleModel} 可以用来存储以及管理数据, 也可以作为 MVP 模式中的 Presenter (只要实现 {@link LifecycleModel} 即可) 35 | * 或者 MVVM 模式中的 ViewModel (只要实现 {@link LifecycleModel} 即可) 用来管理业务逻辑, 更多使用方式等着你去发现 36 | *

 37 |  * public class UserLifecycleModel implements LifecycleModel {
 38 |  *     private int id;
 39 |  *
 40 |  *     public UserLifecycleModel(int id) {
 41 |  *          this.id = id;
 42 |  *     }
 43 |  *
 44 |  *     void doAction() {
 45 |  *
 46 |  *     }
 47 |  * }
 48 |  *
 49 |  *
 50 |  * public class MyActivity extends AppCompatActivity {
 51 |  *
 52 |  *     protected void onCreate(@Nullable Bundle savedInstanceState) {
 53 |  *          LifecycleModelProviders.of(this).put(UserLifecycleModel.class.getName(), new UserLifecycleModel(123));
 54 |  *          fragmentManager.beginTransaction().add(R.layout.afragment_container_Id, new AFragment).commit();
 55 |  *          fragmentManager.beginTransaction().add(R.layout.bfragment_container_Id, new BFragment).commit();
 56 |  *     }
 57 |  * }
 58 |  * 
59 | *

60 | * 只要 AFragment 和 BFragment 绑定在同一个 Activity 下, 并使用同一个 key, 那获取到的 UserLifecycleModel 就是同一个对象 61 | * 这时就可以使用这个 UserLifecycleModel 进行通讯 (Fragment 之间如何通讯? 比如说接口回调? 观察者模式?) 和共享数据 62 | * 这时 Fragment 之间并不知道彼此, 也不互相持有, 所以也不存在耦合关系 63 | *

64 | *

 65 |  * public class AFragment extends Fragment {
 66 |  *     public void onStart() {
 67 |  *         UserLifecycleModel userLifecycleModel = LifecycleModelProviders.of(getActivity()).get(UserLifecycleModel.class.getName());
 68 |  *     }
 69 |  * }
 70 |  *
 71 |  * public class BFragment extends Fragment {
 72 |  *     public void onStart() {
 73 |  *         UserLifecycleModel userLifecycleModel = LifecycleModelProviders.of(getActivity()).get(UserLifecycleModel.class.getName());
 74 |  *     }
 75 |  * }
 76 |  *
 77 |  * 
78 | * 79 | * @see 80 | * 功能和 Android Architecture 中的 ViewModel 一致, 但放开了权限不仅可以存储 ViewModel, 还可以存储任意自定义对象 (也可以试试存储 Presenter 哦!) 81 | *

82 | * Created by JessYan on 21/11/2017 16:57 83 | * Contact me 84 | * Follow me 85 | */ 86 | public class LifecycleModelProviders { 87 | 88 | 89 | private static Application checkApplication(Activity activity) { 90 | Application application = activity.getApplication(); 91 | if (application == null) { 92 | throw new IllegalStateException("Your activity/fragment is not yet attached to " 93 | + "Application. You can't request LifecycleModel before onCreate call."); 94 | } 95 | return application; 96 | } 97 | 98 | private static Activity checkActivity(Fragment fragment) { 99 | Activity activity = fragment.getActivity(); 100 | if (activity == null) { 101 | throw new IllegalStateException("Can't create LifecycleModelStore for detached fragment"); 102 | } 103 | return activity; 104 | } 105 | 106 | /** 107 | * 返回的 {@link LifecycleModelStore} 可以在传入的这个 {code fragment} 的生命范围内一直存活者 108 | * {@link LifecycleModelStore} 可以存储不同的 {@link LifecycleModel} 实现类 109 | * 更多信息请查看 {@link LifecycleModelProviders} 顶部的注释 110 | * 111 | * @param fragment {@link LifecycleModel} 在这个 {code fragment} 的生命范围内被保留 112 | * @return a LifecycleModelStore instance 113 | */ 114 | @MainThread 115 | public static LifecycleModelStore of(@NonNull Fragment fragment) { 116 | checkApplication(checkActivity(fragment)); 117 | return LifecycleModelStores.of(fragment); 118 | } 119 | 120 | /** 121 | * 返回的 {@link LifecycleModelStore} 可以在传入的这个 {code activity} 的生命范围内一直存活着 122 | * {@link LifecycleModelStore} 可以存储不同的 {@link LifecycleModel} 实现类 123 | * 更多信息请查看 {@link LifecycleModelProviders} 顶部的注释 124 | * 125 | * @param activity {@link LifecycleModel} 在这个 {code activity} 的生命范围内被保留 126 | * @return a LifecycleModelStore instance 127 | */ 128 | @MainThread 129 | public static LifecycleModelStore of(@NonNull FragmentActivity activity) { 130 | checkApplication(activity); 131 | return LifecycleModelStores.of(activity); 132 | } 133 | 134 | } 135 | -------------------------------------------------------------------------------- /lifecyclemodel/src/main/java/me/jessyan/lifecyclemodel/LifecycleModelStore.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 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 me.jessyan.lifecyclemodel; 18 | 19 | import android.app.Activity; 20 | import android.support.v4.app.Fragment; 21 | 22 | import me.jessyan.lifecyclemodel.cache.Cache; 23 | import me.jessyan.lifecyclemodel.cache.LruCache; 24 | 25 | /** 26 | * 这个类的作用为存储 {@link LifecycleModel} 27 | *

28 | * 此类的实例可以在配置更改或者屏幕旋转导致的 {@link Activity} 重建的情况下被完好无损的保留下来, 所以重建后的新 {@link Activity} 29 | * 持有的实例和重建前持有实例为同一对象 30 | *

31 | * 如果当 {@link Activity} 被真正的 {@link Activity#finish()} 不再重建, {@link #clear()} 会被调用 32 | * 并且之前存储的所有 {@link LifecycleModel} 的 {@link LifecycleModel#onCleared()} 方法也会被调用 33 | *

34 | * 通过 {@link LifecycleModelStores} 可向 {@link Activity} 和 {@link Fragment} 提供 {@code LifecycleModelStore} 35 | *

36 | * Created by JessYan on 21/11/2017 16:57 37 | * Contact me 38 | * Follow me 39 | */ 40 | public class LifecycleModelStore { 41 | 42 | private final Cache mCache = new LruCache<>(80); 43 | 44 | /** 45 | * 将 {@code lifecycleModel} 以 {@code key} 作为键进行存储 46 | * 47 | * @param key 48 | * @param lifecycleModel 如果这个 {code key} 之前还存储有其他 {@link LifecycleModel} 对象则返回, 否则返回 {@code null} 49 | */ 50 | public final void put(String key, LifecycleModel lifecycleModel) { 51 | LifecycleModel oldLifecycleModel = mCache.get(key); 52 | if (oldLifecycleModel != null) { 53 | oldLifecycleModel.onCleared(); 54 | } 55 | mCache.put(key, lifecycleModel); 56 | } 57 | 58 | /** 59 | * 根据给定的 {@code key} 获取存储的 {@link LifecycleModel} 实现类 60 | * 61 | * @param key 62 | * @param 63 | * @return 64 | */ 65 | public final T get(String key) { 66 | return (T) mCache.get(key); 67 | } 68 | 69 | /** 70 | * 根据给定的 {@code key} 移除存储的 {@link LifecycleModel} 实现类 71 | * 72 | * @param key 73 | * @param 74 | * @return 75 | */ 76 | public final T remove(String key) { 77 | return (T) mCache.remove(key); 78 | } 79 | 80 | /** 81 | * 清理存储的 {@link LifecycleModel}, 并且通知 {@link LifecycleModel#onCleared()} 82 | */ 83 | public final void clear() { 84 | for (String key : mCache.keySet()) { 85 | mCache.get(key).onCleared(); 86 | } 87 | mCache.clear(); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /lifecyclemodel/src/main/java/me/jessyan/lifecyclemodel/LifecycleModelStores.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 JessYan 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 me.jessyan.lifecyclemodel; 18 | 19 | import android.support.annotation.MainThread; 20 | import android.support.annotation.NonNull; 21 | import android.support.v4.app.Fragment; 22 | import android.support.v4.app.FragmentActivity; 23 | 24 | /** 25 | * Factory methods for {@link LifecycleModelStore} class. 26 | *

27 | * Created by JessYan on 21/11/2017 16:57 28 | * Contact me 29 | * Follow me 30 | */ 31 | @SuppressWarnings("WeakerAccess") 32 | public class LifecycleModelStores { 33 | 34 | private LifecycleModelStores() { 35 | } 36 | 37 | /** 38 | * Returns the {@link LifecycleModelStore} of the given activity. 39 | * 40 | * @param activity an activity whose {@code LifecycleModelStore} is requested 41 | * @return a {@code LifecycleModelStore} 42 | */ 43 | @MainThread 44 | public static LifecycleModelStore of(@NonNull FragmentActivity activity) { 45 | return HolderFragment.holderFragmentFor(activity).getLifecycleModelStore(); 46 | } 47 | 48 | /** 49 | * Returns the {@link LifecycleModelStore} of the given fragment. 50 | * 51 | * @param fragment a fragment whose {@code LifecycleModelStore} is requested 52 | * @return a {@code LifecycleModelStore} 53 | */ 54 | @MainThread 55 | public static LifecycleModelStore of(@NonNull Fragment fragment) { 56 | return HolderFragment.holderFragmentFor(fragment).getLifecycleModelStore(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /lifecyclemodel/src/main/java/me/jessyan/lifecyclemodel/cache/Cache.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 JessYan 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 | package me.jessyan.lifecyclemodel.cache; 17 | 18 | import android.support.annotation.Nullable; 19 | 20 | import java.util.Set; 21 | 22 | 23 | /** 24 | * ================================================ 25 | * 用于缓存框架中所必需的组件 26 | * 27 | * @see LruCache 28 | * Created by JessYan on 25/09/2017 16:36 29 | * Contact me 30 | * Follow me 31 | * ================================================ 32 | */ 33 | public interface Cache { 34 | 35 | /** 36 | * 返回当前缓存已占用的总 size 37 | * 38 | * @return 39 | */ 40 | int size(); 41 | 42 | /** 43 | * 返回当前缓存所能允许的最大 size 44 | * 45 | * @return 46 | */ 47 | int getMaxSize(); 48 | 49 | /** 50 | * 返回这个 {@code key} 在缓存中对应的 {@code value}, 如果返回 {@code null} 说明这个 {@code key} 没有对应的 {@code value} 51 | * 52 | * @param key 53 | * @return 54 | */ 55 | @Nullable 56 | V get(K key); 57 | 58 | /** 59 | * 将 {@code key} 和 {@code value} 以条目的形式加入缓存,如果这个 {@code key} 在缓存中已经有对应的 {@code value} 60 | * 则此 {@code value} 被新的 {@code value} 替换并返回,如果为 {@code null} 说明是一个新条目 61 | * 62 | * @param key 63 | * @param value 64 | * @return 65 | */ 66 | @Nullable 67 | V put(K key, V value); 68 | 69 | /** 70 | * 移除缓存中这个 {@code key} 所对应的条目,并返回所移除条目的 value 71 | * 如果返回为 {@code null} 则有可能时因为这个 {@code key} 对应的 value 为 {@code null} 或条目不存在 72 | * 73 | * @param key 74 | * @return 75 | */ 76 | @Nullable 77 | V remove(K key); 78 | 79 | /** 80 | * 如果这个 {@code key} 在缓存中有对应的 value 并且不为 {@code null}, 则返回 {@code true} 81 | * 82 | * @param key 83 | * @return 84 | */ 85 | boolean containsKey(K key); 86 | 87 | /** 88 | * 返回当前缓存中含有的所有 {@code key} 89 | * 90 | * @return 91 | */ 92 | Set keySet(); 93 | 94 | /** 95 | * 清除缓存中所有的内容 96 | */ 97 | void clear(); 98 | } 99 | -------------------------------------------------------------------------------- /lifecyclemodel/src/main/java/me/jessyan/lifecyclemodel/cache/LruCache.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 JessYan 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 | package me.jessyan.lifecyclemodel.cache; 17 | 18 | import android.support.annotation.Nullable; 19 | 20 | import java.util.LinkedHashMap; 21 | import java.util.Map; 22 | import java.util.Set; 23 | 24 | 25 | /** 26 | * ================================================ 27 | * LRU 即 Least Recently Used,最近最少使用,也就是说,当缓存满了,会优先淘汰那些最近最不常访问的数据 28 | * 此种缓存策略为框架默认提供,可自行实现其他缓存策略,如磁盘缓存,为框架或开发者提供缓存的功能 29 | * 30 | * @see Cache 31 | * Created by JessYan on 25/09/2017 16:57 32 | * Contact me 33 | * Follow me 34 | * ================================================ 35 | */ 36 | public class LruCache implements Cache { 37 | private final LinkedHashMap cache = new LinkedHashMap<>(100, 0.75f, true); 38 | private final int initialMaxSize; 39 | private int maxSize; 40 | private int currentSize = 0; 41 | 42 | /** 43 | * Constructor for LruCache. 44 | * 45 | * @param size 这个缓存的最大 size,这个 size 所使用的单位必须和 {@link #getItemSize(Object)} 所使用的单位一致. 46 | */ 47 | public LruCache(int size) { 48 | this.initialMaxSize = size; 49 | this.maxSize = size; 50 | } 51 | 52 | /** 53 | * 设置一个系数应用于当时构造函数中所传入的 size, 从而得到一个新的 {@link #maxSize} 54 | * 并会立即调用 {@link #evict} 开始清除满足条件的条目 55 | * 56 | * @param multiplier 系数 57 | */ 58 | public synchronized void setSizeMultiplier(float multiplier) { 59 | if (multiplier < 0) { 60 | throw new IllegalArgumentException("Multiplier must be >= 0"); 61 | } 62 | maxSize = Math.round(initialMaxSize * multiplier); 63 | evict(); 64 | } 65 | 66 | /** 67 | * 返回每个 {@code item} 所占用的 size,默认为1,这个 size 的单位必须和构造函数所传入的 size 一致 68 | * 子类可以重写这个方法以适应不同的单位,比如说 bytes 69 | * 70 | * @param item 每个 {@code item} 所占用的 size 71 | */ 72 | protected int getItemSize(V item) { 73 | return 1; 74 | } 75 | 76 | /** 77 | * 当缓存中有被驱逐的条目时,会回调此方法,默认空实现,子类可以重写这个方法 78 | * 79 | * @param key 被驱逐条目的 {@code key} 80 | * @param value 被驱逐条目的 {@code value} 81 | */ 82 | protected void onItemEvicted(K key, V value) { 83 | // optional override 84 | } 85 | 86 | /** 87 | * 返回当前缓存所能允许的最大 size 88 | */ 89 | @Override 90 | public synchronized int getMaxSize() { 91 | return maxSize; 92 | } 93 | 94 | /** 95 | * 返回当前缓存已占用的总 size 96 | */ 97 | @Override 98 | public synchronized int size() { 99 | return currentSize; 100 | } 101 | 102 | /** 103 | * 如果这个 {@code key} 在缓存中有对应的 {@code value} 并且不为 {@code null},则返回 true 104 | * 105 | * @param key 用来映射的 {@code key} 106 | */ 107 | @Override 108 | public synchronized boolean containsKey(K key) { 109 | return cache.containsKey(key); 110 | } 111 | 112 | /** 113 | * 返回当前缓存中含有的所有 {@code key} 114 | * 115 | * @return 116 | */ 117 | @Override 118 | public Set keySet() { 119 | return cache.keySet(); 120 | } 121 | 122 | /** 123 | * 返回这个 {@code key} 在缓存中对应的 {@code value}, 如果返回 {@code null} 说明这个 {@code key} 没有对应的 {@code value} 124 | * 125 | * @param key 用来映射的 {@code key} 126 | */ 127 | @Override 128 | @Nullable 129 | public synchronized V get(K key) { 130 | return cache.get(key); 131 | } 132 | 133 | /** 134 | * 将 {@code key} 和 {@code value} 以条目的形式加入缓存,如果这个 {@code key} 在缓存中已经有对应的 {@code value} 135 | * 则此 {@code value} 被新的 {@code value} 替换并返回,如果为 {@code null} 说明是一个新条目 136 | *

137 | * 如果 {@link #getItemSize} 返回的 size 大于或等于缓存所能允许的最大 size, 则不能向缓存中添加此条目 138 | * 此时会回调 {@link #onItemEvicted(Object, Object)} 通知此方法当前被驱逐的条目 139 | * 140 | * @param key 通过这个 {@code key} 添加条目 141 | * @param value 需要添加的 {@code value} 142 | */ 143 | @Override 144 | @Nullable 145 | public synchronized V put(K key, V value) { 146 | final int itemSize = getItemSize(value); 147 | if (itemSize >= maxSize) { 148 | onItemEvicted(key, value); 149 | return null; 150 | } 151 | 152 | final V result = cache.put(key, value); 153 | if (value != null) { 154 | currentSize += getItemSize(value); 155 | } 156 | if (result != null) { 157 | currentSize -= getItemSize(result); 158 | } 159 | evict(); 160 | 161 | return result; 162 | } 163 | 164 | /** 165 | * 移除缓存中这个 {@code key} 所对应的条目,并返回所移除条目的 {@code value} 166 | * 如果返回为 {@code null} 则有可能时因为这个 {@code key} 对应的 {@code value} 为 {@code null} 或条目不存在 167 | * 168 | * @param key 使用这个 {@code key} 移除对应的条目 169 | */ 170 | @Override 171 | @Nullable 172 | public synchronized V remove(K key) { 173 | final V value = cache.remove(key); 174 | if (value != null) { 175 | currentSize -= getItemSize(value); 176 | } 177 | return value; 178 | } 179 | 180 | /** 181 | * 清除缓存中所有的内容 182 | */ 183 | @Override 184 | public void clear() { 185 | trimToSize(0); 186 | } 187 | 188 | /** 189 | * 当指定的 size 小于当前缓存已占用的总 size 时,会开始清除缓存中最近最少使用的条目 190 | * 191 | * @param size 192 | */ 193 | protected synchronized void trimToSize(int size) { 194 | Map.Entry last; 195 | while (currentSize > size) { 196 | last = cache.entrySet().iterator().next(); 197 | final V toRemove = last.getValue(); 198 | currentSize -= getItemSize(toRemove); 199 | final K key = last.getKey(); 200 | cache.remove(key); 201 | onItemEvicted(key, toRemove); 202 | } 203 | } 204 | 205 | /** 206 | * 当缓存中已占用的总 size 大于所能允许的最大 size ,会使用 {@link #trimToSize(int)} 开始清除满足条件的条目 207 | */ 208 | private void evict() { 209 | trimToSize(maxSize); 210 | } 211 | } 212 | 213 | -------------------------------------------------------------------------------- /lifecyclemodel/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | LifecycleModel 3 | 4 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':lifecyclemodel' 2 | --------------------------------------------------------------------------------