├── .gitattributes
├── .gitignore
├── .idea
├── codeStyles
│ ├── Project.xml
│ └── codeStyleConfig.xml
├── dictionaries
│ └── lizhiyun.xml
├── encodings.xml
├── gradle.xml
├── kannotator.xml
├── misc.xml
├── runConfigurations.xml
└── vcs.xml
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── gucci
│ │ └── lifecycle
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── gucci
│ │ │ └── lifecycle
│ │ │ └── demo
│ │ │ ├── A.kt
│ │ │ ├── B.kt
│ │ │ ├── C.kt
│ │ │ ├── CProcessDialog.kt
│ │ │ ├── CustomDialogFragment.kt
│ │ │ ├── CustomVideoView.kt
│ │ │ ├── DialogExtentions.kt
│ │ │ ├── MainActivity.kt
│ │ │ ├── MyApp.kt
│ │ │ └── TestView.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ └── dialog_custom.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
│ └── com
│ └── gucci
│ └── lifecycle
│ └── ExampleUnitTest.kt
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── gucci
│ │ └── lifecycle
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ └── java
│ │ └── com
│ │ └── gucci
│ │ └── lifecycle
│ │ ├── LifecycleExtend.kt
│ │ ├── LifecycleListener.kt
│ │ ├── LifecycleProvider.kt
│ │ ├── ManagerRetriever.kt
│ │ ├── Tick.kt
│ │ ├── annotations
│ │ ├── OnAttachedToWindow.kt
│ │ ├── OnCreate.kt
│ │ ├── OnDestory.kt
│ │ ├── OnDetachedToWindow.kt
│ │ ├── OnPause.kt
│ │ ├── OnResume.kt
│ │ ├── OnStart.kt
│ │ ├── OnStop.kt
│ │ └── OnTick.kt
│ │ ├── lifecycle
│ │ ├── ActivityFragmentLifecycle.kt
│ │ ├── ApplicationLifecycle.kt
│ │ └── Lifecycle.kt
│ │ ├── lifecycleContainer
│ │ ├── HookListenersHandlerCallback.kt
│ │ ├── RequestManagerFragment.kt
│ │ └── SupportRequestManagerFragment.kt
│ │ └── util
│ │ ├── InvokeUtil.kt
│ │ └── LifecycleUtil.kt
│ └── test
│ └── java
│ └── com
│ └── gucci
│ └── lifecycle
│ └── ExampleUnitTest.java
└── settings.gradle
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/misc.xml
5 | /.idea/caches
6 | /.idea/libraries
7 | /.idea/modules.xml
8 | /.idea/workspace.xml
9 | /.idea/navEditor.xml
10 | /.idea/assetWizardSettings.xml
11 | .DS_Store
12 | /build
13 | /captures
14 | .externalNativeBuild
15 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/dictionaries/lizhiyun.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/kannotator.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 监听生命周期的lifecycle,使用方法比官方lifecycle简单并且支持的场景更多,支持android.app.Activity,android.app.Dialog等,支持多级组件的生命周期自动传递,子模块先执行,支持自动解绑
2 |
3 | #用法
4 | maven { url 'https://jitpack.io' }
5 | implementation 'com.github.wangdanlizhiyun:lifecycle:4.0.0'
6 |
7 | ```
8 | 让业务组件 如A继承LifecycleListener接口进行标示,用@OnCreate等注解标注要在监听到的生命周期时执行的方法,注意必须是无参方法
9 |
10 | 业务组件与生命周期之间的关联通过业务组件的扩展函数bind方法A() bind this,参数支持如下:
11 | 1.android.app.Application 只包含onstart
12 | 2.android.support.v4.app.FragmentActivity
13 | 3.android.app.Activity
14 | 4.android.app.Fragment
15 | 5.android.support.v4.app.Fragment(包含android.support.v4.app.DialogFragment)
16 | 6.android.app.Dialog 只有oncreate和onDestroy即分别对应显示和隐藏
17 | 7.其他context如view内的context
18 | 8.View类型,
19 |
20 | 对于java类由于不能调用扩展函数方法bind就得换成ManagerRetriever.INSTANCE.get(this).addListener(new A());,参数同上
21 | 解绑定依然是自动化的,使用者无需考虑。注意对于参数为Application或者在子线程调用时就不会自动解绑,处理逻辑同glide
22 |
23 | 对于业务组件的子组件无需手动绑定即可自动跟随夫业务组件的生命周期。
24 | 如presenter里的子业务组件的生命周期无需使用者手写大量繁琐的生命周期传递方法
25 | 如果是view组件则子view自动跟随夫view的生命周期
26 | 两种情况可以同时存在并且多层嵌套
27 |
28 | ```
29 | ###TODO:1.免除其他场景的 bind 方法调用
30 |
31 |
--------------------------------------------------------------------------------
/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 | android {
8 | compileSdkVersion 28
9 | defaultConfig {
10 | applicationId "com.gucci.lifecycle.demo"
11 | minSdkVersion 16
12 | targetSdkVersion 28
13 | versionCode 1
14 | versionName "1.0"
15 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
16 | }
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | }
24 |
25 | dependencies {
26 | implementation fileTree(dir: 'libs', include: ['*.jar'])
27 | implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
28 | implementation 'com.android.support:appcompat-v7:28.0.0'
29 | implementation 'com.android.support.constraint:constraint-layout:1.1.3'
30 | testImplementation 'junit:junit:4.12'
31 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
32 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
33 | implementation project(path: ':library')
34 | // implementation 'com.github.wangdanlizhiyun:lifecycle:1.1.0'
35 | debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.5.1'
36 | implementation "org.jetbrains.anko:anko:$anko_version"
37 | }
38 |
--------------------------------------------------------------------------------
/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/gucci/lifecycle/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle
2 |
3 | import android.support.test.InstrumentationRegistry
4 | import android.support.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.gucci.lifecycle", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/app/src/main/java/com/gucci/lifecycle/demo/A.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.demo
2 |
3 | import android.util.Log
4 | import com.gucci.lifecycle.LifecycleListener
5 | import com.gucci.lifecycle.annotations.*
6 |
7 | class A : LifecycleListener {
8 | val b = B()
9 |
10 | @OnStart
11 | fun onStart() {
12 | Log.e("test", "A onStart")
13 | }
14 |
15 | @OnStop
16 | fun onStop() {
17 | Log.e("test", "A onStop")
18 |
19 | }
20 |
21 | @OnDestory
22 | fun onDestory() {
23 | Log.e("test", "A onDestory")
24 |
25 | }
26 |
27 | @OnResume
28 | fun onResume() {
29 | Log.e("test", "A onResume")
30 |
31 | }
32 |
33 | @OnCreate
34 | fun c() {
35 | Log.e("test", "A onCreate")
36 |
37 | }
38 |
39 | @OnPause
40 | fun onPause() {
41 | Log.e("test", "A onPause")
42 |
43 | }
44 |
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/app/src/main/java/com/gucci/lifecycle/demo/B.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.demo
2 |
3 | import android.util.Log
4 | import com.gucci.lifecycle.LifecycleListener
5 | import com.gucci.lifecycle.annotations.*
6 |
7 | class B : LifecycleListener {
8 | @OnStart fun onStart() {
9 |
10 | Log.e("test", "B onStart")
11 | }
12 |
13 | @OnStop fun onStop() {
14 | Log.e("test", "B onStop")
15 |
16 | }
17 |
18 | @OnDestory fun onDestory() {
19 | Log.e("test", "B onDestory")
20 |
21 | }
22 |
23 | @OnResume fun onResume() {
24 | Log.e("test", "B onResume")
25 |
26 | }
27 |
28 | @OnCreate
29 | fun c() {
30 | Log.e("test", "B onCreate")
31 |
32 | }
33 |
34 | @OnPause fun onPause() {
35 | Log.e("test", "B onPause")
36 |
37 | }
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/app/src/main/java/com/gucci/lifecycle/demo/C.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.demo
2 |
3 | import android.util.Log
4 | import com.gucci.lifecycle.LifecycleListener
5 | import com.gucci.lifecycle.annotations.*
6 |
7 | class C : LifecycleListener {
8 | @OnStart fun onStart() {
9 |
10 | Log.e("test", "C onStart")
11 | }
12 |
13 | @OnStop fun onStop() {
14 | Log.e("test", "C onStop")
15 |
16 | }
17 |
18 | @OnDestory fun onDestory() {
19 | Log.e("test", "C onDestory")
20 |
21 | }
22 |
23 | @OnResume fun onResume() {
24 | Log.e("test", "C onResume")
25 |
26 | }
27 |
28 | @OnCreate
29 | fun c() {
30 | Log.e("test", "C onCreate")
31 |
32 | }
33 |
34 | @OnPause fun onPause() {
35 | Log.e("test", "C onPause")
36 |
37 | }
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/app/src/main/java/com/gucci/lifecycle/demo/CProcessDialog.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.demo
2 |
3 | import android.app.ProgressDialog
4 | import android.content.Context
5 | import android.os.Bundle
6 | import com.gucci.lifecycle.bind
7 |
8 | class CProcessDialog : ProgressDialog {
9 | constructor(context: Context) : super(context) {}
10 |
11 | constructor(context: Context, theme: Int) : super(context, theme) {}
12 |
13 | override fun onCreate(savedInstanceState: Bundle?) {
14 | super.onCreate(savedInstanceState)
15 |
16 |
17 | B() bind this
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/app/src/main/java/com/gucci/lifecycle/demo/CustomDialogFragment.kt:
--------------------------------------------------------------------------------
1 | package com.lzy.download
2 |
3 | import android.os.Bundle
4 | import android.support.v4.app.DialogFragment
5 | import android.util.Log
6 | import android.view.LayoutInflater
7 | import android.view.View
8 | import android.view.ViewGroup
9 | import android.widget.TextView
10 | import com.gucci.lifecycle.bind
11 | import com.gucci.lifecycle.demo.B
12 | import com.gucci.lifecycle.demo.R
13 |
14 | class CustomDialogFragment: DialogFragment() {
15 | private var titleTv:TextView? = null
16 | private var messageTv:TextView? = null
17 | private var leftButton:TextView? = null
18 | private var rightButton:TextView? = null
19 |
20 | private var leftClicks:(() -> Unit)? = null
21 | private var rightClicks:(() -> Unit)? = null
22 |
23 | var cancelOutside = true
24 |
25 | var title:String? = null
26 | var message:String? = null
27 | var leftKey: String? = null
28 | var leftButtonDismissAfterClick = true
29 | var rightKey: String? = null
30 | var rightButtonDismissAfterClick = true
31 |
32 | companion object {
33 | fun newInstance(): CustomDialogFragment {
34 | return CustomDialogFragment()
35 | }
36 | }
37 |
38 | override fun onCreate(savedInstanceState: Bundle?) {
39 | super.onCreate(savedInstanceState)
40 | setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Material_Light_Dialog)
41 | }
42 |
43 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
44 | val view = inflater?.inflate(R.layout.dialog_custom, container)
45 | titleTv = view?.findViewById(R.id.title_tv)
46 | messageTv = view?.findViewById(R.id.message_tv)
47 | leftButton = view?.findViewById(R.id.left_button)
48 | rightButton = view?.findViewById(R.id.right_button)
49 |
50 | init()
51 | B() bind this
52 | return view
53 | }
54 |
55 | private fun init() {
56 | dialog?.setCanceledOnTouchOutside(cancelOutside)
57 |
58 | title?.let { text ->
59 | titleTv?.visibility = View.VISIBLE
60 | titleTv?.text = text
61 | }
62 |
63 | message?.let { text ->
64 | messageTv?.visibility = View.VISIBLE
65 | messageTv?.text = text
66 | }
67 |
68 | leftClicks?.let { onClick ->
69 | leftButton?.text = leftKey
70 | leftButton?.visibility = View.VISIBLE
71 | leftButton?.setOnClickListener {
72 | onClick()
73 | if (leftButtonDismissAfterClick) {
74 | dismissAllowingStateLoss()
75 | }
76 | }
77 | }
78 |
79 | rightClicks?.let { onClick ->
80 | rightButton?.text = rightKey
81 | rightButton?.setOnClickListener {
82 | onClick()
83 | if (rightButtonDismissAfterClick) {
84 | dismissAllowingStateLoss()
85 | }
86 | }
87 | }
88 | }
89 |
90 | fun leftClicks(key: String = "取消", dismissAfterClick: Boolean = true, callback: () -> Unit) {
91 | leftKey = key
92 | leftButtonDismissAfterClick = dismissAfterClick
93 | leftClicks = callback
94 | }
95 |
96 | fun rightClicks(key: String = "确定", dismissAfterClick: Boolean = true, callback: () -> Unit) {
97 | rightKey = key
98 | rightButtonDismissAfterClick = dismissAfterClick
99 | rightClicks = callback
100 | }
101 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/gucci/lifecycle/demo/CustomVideoView.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.demo
2 |
3 | import android.content.Context
4 | import android.net.Uri
5 | import android.os.Build
6 | import android.util.AttributeSet
7 | import android.util.Log
8 | import android.view.View
9 | import android.view.ViewManager
10 | import android.widget.VideoView
11 | import com.gucci.lifecycle.LifecycleListener
12 | import com.gucci.lifecycle.annotations.*
13 | import org.jetbrains.anko.custom.ankoView
14 |
15 | class CustomVideoView: VideoView,LifecycleListener {
16 | constructor(context: Context?) : super(context)
17 | constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
18 | constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
19 | override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
20 | val width = View.getDefaultSize(0, widthMeasureSpec)
21 | val height = View.getDefaultSize(0, heightMeasureSpec)
22 | setMeasuredDimension(width, height)
23 | }
24 |
25 | init {
26 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
27 | setOnInfoListener { mp, what, extra ->
28 | mp.isLooping = true
29 | false
30 | }
31 | }
32 | }
33 |
34 | @OnResume fun onResume() {
35 | Log.e("test", "CustomVideoView onResume mCurrentPosition=$mCurrentPosition")
36 | resume()
37 | }
38 |
39 | @OnStart fun onStart() {
40 | Log.e("test", "CustomVideoView onStart mCurrentPosition=$mCurrentPosition")
41 | seekTo(mCurrentPosition)
42 | start()
43 | }
44 |
45 | @OnPause fun onPause() {
46 | Log.e("test", "CustomVideoView onPause")
47 | mCurrentPosition = currentPosition
48 | pause()
49 | }
50 |
51 | @OnStop fun onStop() {
52 | Log.e("test", "CustomVideoView OnStop")
53 | stopPlayback()
54 | }
55 |
56 | @OnDestory fun onDestroy() {
57 | Log.e("test", "CustomVideoView onDestroy")
58 | suspend()
59 | }
60 | protected var mCurrentPosition = 0
61 | }
62 | inline fun ViewManager.customVideoView() = customVideoView {}
63 | inline fun ViewManager.customVideoView(init: CustomVideoView.() -> Unit) = ankoView(::CustomVideoView, 0, init)
64 | inline fun ViewManager.customVideoView(uri: Uri, init: CustomVideoView.() -> Unit) = customVideoView {
65 | setVideoURI(uri)
66 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/gucci/lifecycle/demo/DialogExtentions.kt:
--------------------------------------------------------------------------------
1 | package com.lzy.download
2 |
3 | import android.support.v7.app.AppCompatActivity
4 |
5 | inline fun AppCompatActivity.showCustomDialog(settings:CustomDialogFragment.() -> Unit):CustomDialogFragment{
6 | val dialog = CustomDialogFragment.newInstance()
7 | dialog.apply(settings)
8 | val ft = this.supportFragmentManager.beginTransaction()
9 | val pre = this.supportFragmentManager.findFragmentByTag("dialoag")
10 | pre?.let { ft.remove(it) }
11 | ft.addToBackStack(null)
12 | dialog.show(ft,"dialog")
13 | return dialog
14 | }
15 |
--------------------------------------------------------------------------------
/app/src/main/java/com/gucci/lifecycle/demo/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.demo
2 |
3 | import android.app.Activity
4 | import android.app.Dialog
5 | import android.net.Uri
6 | import android.os.Bundle
7 | import android.support.v7.app.AppCompatActivity
8 | import android.util.Log
9 | import android.view.View
10 | import android.widget.LinearLayout
11 | import com.gucci.lifecycle.bind
12 | import com.lzy.download.CustomDialogFragment
13 | import com.lzy.download.showCustomDialog
14 | import org.jetbrains.anko.*
15 | import org.jetbrains.anko.sdk27.coroutines.onClick
16 |
17 | class MainActivity : AppCompatActivity() {
18 | lateinit var that:Activity
19 | lateinit var mCustomVideoView:CustomVideoView
20 | var dialogFragment : CustomDialogFragment? = null
21 | lateinit var mC:C
22 | lateinit var mLl:LinearLayout
23 | override fun onCreate(savedInstanceState: Bundle?) {
24 | super.onCreate(savedInstanceState)
25 | that = this
26 | val testView = TestView(this)
27 | mLl = verticalLayout {
28 |
29 | button("showDialogFragment"){
30 | onClick {
31 | if (dialogFragment == null){
32 | dialogFragment = showCustomDialog{
33 | message = "fdafa"
34 | cancelOutside = false
35 | }
36 | }else{
37 | dialogFragment?.show(supportFragmentManager,"dialog")
38 | }
39 | }
40 | }
41 | button("showDialog"){
42 | onClick {
43 | CProcessDialog(that).show()
44 | }
45 | }
46 | // mCustomVideoView = customVideoView(Uri.parse("http://tb-video.bdstatic.com/tieba-smallvideo-transcode/10923707_80db72f5f649f4c0dc62c8520184d3d7_0.mp4"))
47 | // {}.lparams(width = matchParent,height = 500)
48 |
49 | button("addView"){
50 | onClick {
51 | mLl.addView(testView)
52 | }
53 | }
54 | button("deleteView"){
55 | onClick {
56 | mLl.removeView(testView)
57 | }
58 | }
59 | }
60 | mLl.visibility = View.VISIBLE
61 | mC = C()
62 | A() bind this
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/app/src/main/java/com/gucci/lifecycle/demo/MyApp.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.demo
2 |
3 | import android.app.Application
4 | import com.squareup.leakcanary.LeakCanary
5 |
6 | class MyApp :Application(){
7 |
8 | override fun onCreate() {
9 | super.onCreate()
10 | if (LeakCanary.isInAnalyzerProcess(this)) {
11 | // This process is dedicated to LeakCanary for heap analysis.
12 | // You should not init your app in this process.
13 | return;
14 | }
15 | LeakCanary.install(this)
16 |
17 |
18 | }
19 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/gucci/lifecycle/demo/TestView.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.demo
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import android.util.Log
6 | import android.widget.TextView
7 | import com.gucci.lifecycle.annotations.OnTick
8 | import com.gucci.lifecycle.tick
9 |
10 |
11 | class TestView: TextView {
12 | constructor(context: Context?) : super(context)
13 | constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
14 | constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
15 | init { tick() }
16 | @OnTick fun doOntick(){
17 | Log.e("test","doOntick")
18 | }
19 | }
--------------------------------------------------------------------------------
/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 |
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/dialog_custom.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
13 |
26 |
27 |
41 |
42 |
56 |
57 |
71 |
72 |
--------------------------------------------------------------------------------
/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/wangdanlizhiyun/lifecycle/6488a4d94af44396d771afa369c56a58262fdda4/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangdanlizhiyun/lifecycle/6488a4d94af44396d771afa369c56a58262fdda4/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangdanlizhiyun/lifecycle/6488a4d94af44396d771afa369c56a58262fdda4/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangdanlizhiyun/lifecycle/6488a4d94af44396d771afa369c56a58262fdda4/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangdanlizhiyun/lifecycle/6488a4d94af44396d771afa369c56a58262fdda4/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangdanlizhiyun/lifecycle/6488a4d94af44396d771afa369c56a58262fdda4/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangdanlizhiyun/lifecycle/6488a4d94af44396d771afa369c56a58262fdda4/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangdanlizhiyun/lifecycle/6488a4d94af44396d771afa369c56a58262fdda4/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangdanlizhiyun/lifecycle/6488a4d94af44396d771afa369c56a58262fdda4/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangdanlizhiyun/lifecycle/6488a4d94af44396d771afa369c56a58262fdda4/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.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 | lifecycle
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/gucci/lifecycle/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle
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.31'
5 | ext.anko_version = '0.10.8'
6 | repositories {
7 | google()
8 | jcenter()
9 |
10 | }
11 | dependencies {
12 | classpath 'com.android.tools.build:gradle:3.4.1'
13 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
14 | // NOTE: Do not place your application dependencies here; they belong
15 | // in the individual module build.gradle files
16 | }
17 | }
18 |
19 | allprojects {
20 | repositories {
21 | google()
22 | jcenter()
23 | maven { url 'https://jitpack.io' }
24 |
25 | }
26 | }
27 |
28 | task clean(type: Delete) {
29 | delete rootProject.buildDir
30 | }
31 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wangdanlizhiyun/lifecycle/6488a4d94af44396d771afa369c56a58262fdda4/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sat Jun 08 11:23:58 PHT 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 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android-extensions'
3 | apply plugin: 'kotlin-android'
4 |
5 | android {
6 | compileSdkVersion 28
7 |
8 |
9 |
10 | defaultConfig {
11 | minSdkVersion 16
12 | targetSdkVersion 28
13 | versionCode 1
14 | versionName "1.0"
15 |
16 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
17 |
18 | }
19 |
20 | buildTypes {
21 | release {
22 | minifyEnabled false
23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
24 | }
25 | }
26 |
27 | }
28 |
29 | dependencies {
30 | implementation fileTree(dir: 'libs', include: ['*.jar'])
31 |
32 | implementation 'com.android.support:appcompat-v7:28.0.0'
33 | testImplementation 'junit:junit:4.12'
34 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
35 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
36 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
37 | }
38 | repositories {
39 | mavenCentral()
40 | }
41 |
--------------------------------------------------------------------------------
/library/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 |
--------------------------------------------------------------------------------
/library/src/androidTest/java/com/gucci/lifecycle/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle;
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() {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.gucci.lifecycle.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/LifecycleExtend.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle
2 |
3 | import android.app.Activity
4 | import android.app.Dialog
5 | import android.support.v4.app.Fragment
6 | import android.support.v4.app.FragmentActivity
7 | import android.view.View
8 | import com.gucci.lifecycle.annotations.OnAttachedToWindow
9 | import com.gucci.lifecycle.annotations.OnDetachedToWindow
10 | import com.gucci.lifecycle.lifecycle.Lifecycle
11 | import com.gucci.lifecycle.util.LifecycleUtil
12 | import java.util.*
13 |
14 | /**
15 | * @see #watch(android.app.Activity)
16 | * @see #watch(android.app.Fragment)
17 | * @see #watch(android.support.v4.app.Fragment)
18 | * @see #watch(android.support.v4.app.FragmentActivity)
19 | * @see #watch(android.support.v4.app.DialogFragment)
20 | * @see #watch(android.app.Dialog) 注意:监听Dialog时watch调用必须在setOnDismissListener和setOnShowListener之前,
21 | * 并且对于dialog而言只有oncreate和onDestroy
22 | */
23 | infix fun LifecycleListener.bind(lifecycle: Lifecycle):LifecycleListener {
24 | lifecycle.addListener(this)
25 | return this
26 | }
27 |
28 | infix fun LifecycleListener.bind(activity: FragmentActivity):LifecycleListener {
29 | this bind ManagerRetriever.get(activity)
30 | return this
31 | }
32 |
33 | infix fun LifecycleListener.bind(activity: Activity):LifecycleListener {
34 | this bind ManagerRetriever.get(activity)
35 | return this
36 | }
37 |
38 | infix fun LifecycleListener.bind(fragment: Fragment?):LifecycleListener {
39 | fragment?.let { this bind ManagerRetriever.get(it) }
40 | return this
41 | }
42 |
43 | infix fun LifecycleListener.bind(fragment: android.app.Fragment):LifecycleListener {
44 | this bind ManagerRetriever.get(fragment)
45 | return this
46 | }
47 |
48 | infix fun LifecycleListener.bind(dialog: Dialog):LifecycleListener {
49 | this bind ManagerRetriever.get(dialog)
50 | return this
51 | }
52 |
53 | infix fun LifecycleListener.bind(view: View):LifecycleListener {
54 | val onAttachStateChangeListener = object : View.OnAttachStateChangeListener {
55 | override fun onViewDetachedFromWindow(v: View?) {
56 | LifecycleUtil.doAction(this@bind, OnDetachedToWindow::class.java)
57 | }
58 |
59 | override fun onViewAttachedToWindow(v: View?) {
60 | LifecycleUtil.doAction(this@bind, OnAttachedToWindow::class.java)
61 | }
62 | }
63 | view.addOnAttachStateChangeListener(onAttachStateChangeListener)
64 | this bind ManagerRetriever.get(view)
65 | return this
66 | }
67 |
68 | fun View.tick() {
69 | Tick(this)
70 | }
71 |
72 |
73 | //var lifecycle: Lifecycle? = null
74 |
75 |
76 | fun Collection.getSnapshot(): List {
77 | val result = ArrayList(this.size)
78 | for (item in this) {
79 | if (item != null) {
80 | result.add(item)
81 | }
82 | }
83 | return result
84 | }
85 |
86 |
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/LifecycleListener.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle
2 |
3 |
4 | interface LifecycleListener {}
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/LifecycleProvider.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle
2 |
3 | import android.app.Application
4 | import android.content.ContentProvider
5 | import android.content.ContentValues
6 | import android.database.Cursor
7 | import android.net.Uri
8 | import com.gucci.lifecycle.util.LifecycleUtil
9 |
10 |
11 | class LifecycleProvider:ContentProvider() {
12 | override fun insert(uri: Uri?, values: ContentValues?): Uri? {
13 | return null
14 | }
15 |
16 | override fun query(
17 | uri: Uri?,
18 | projection: Array?,
19 | selection: String?,
20 | selectionArgs: Array?,
21 | sortOrder: String?
22 | ): Cursor? {
23 | return null
24 | }
25 |
26 | override fun onCreate(): Boolean {
27 | LifecycleUtil.init(context as Application)
28 | return true
29 | }
30 |
31 | override fun update(uri: Uri?, values: ContentValues?, selection: String?, selectionArgs: Array?): Int {
32 | return 0
33 | }
34 |
35 | override fun delete(uri: Uri?, selection: String?, selectionArgs: Array?): Int {
36 | return 0
37 | }
38 |
39 | override fun getType(uri: Uri?): String {
40 | return ""
41 | }
42 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/ManagerRetriever.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle
2 |
3 | import android.annotation.TargetApi
4 | import android.app.Activity
5 | import android.app.Application
6 | import android.app.Dialog
7 | import android.content.Context
8 | import android.content.ContextWrapper
9 | import android.os.*
10 | import android.support.v4.app.Fragment
11 | import android.support.v4.app.FragmentActivity
12 | import android.support.v4.util.ArrayMap
13 | import android.view.View
14 | import com.gucci.lifecycle.lifecycle.ApplicationLifecycle
15 | import com.gucci.lifecycle.lifecycle.Lifecycle
16 | import com.gucci.lifecycle.lifecycleContainer.HookListenersHandlerCallback
17 | import com.gucci.lifecycle.lifecycleContainer.RequestManagerFragment
18 | import com.gucci.lifecycle.lifecycleContainer.SupportRequestManagerFragment
19 | import com.gucci.lifecycle.util.InvokeUtil
20 | import java.lang.Exception
21 | import java.util.*
22 |
23 | object ManagerRetriever {
24 | var Dialog_SHOW = -1
25 | val applicationLifecycle: Lifecycle = ApplicationLifecycle()
26 | private val tempViewToSupportFragment = ArrayMap()
27 | private val tempViewToFragment = ArrayMap()
28 | private val tempBundle = Bundle()
29 | private val FRAGMENT_INDEX_KEY = "key"
30 | val FRAG_TAG = "gucci_fragment"
31 | val ID_REMOVE_SUPPORT_FRAGMENT_MANAGER = 1
32 | val ID_REMOVE_FRAGMENT_MANAGER = 2
33 | val pendingSupportsRequestManagerFragments: HashMap = HashMap()
34 | val pendingRequestManagerFragments: HashMap = HashMap()
35 | val handler = object : Handler(Looper.getMainLooper()) {
36 | override fun handleMessage(msg: Message) {
37 | super.handleMessage(msg)
38 | when (msg.what) {
39 | ID_REMOVE_SUPPORT_FRAGMENT_MANAGER -> {
40 | pendingSupportsRequestManagerFragments.remove(msg.obj)
41 | }
42 | ID_REMOVE_FRAGMENT_MANAGER -> {
43 | pendingRequestManagerFragments.remove(msg.obj)
44 | }
45 | }
46 | }
47 | }
48 |
49 | fun get(activity: Activity): Lifecycle {
50 | if (Looper.getMainLooper() != Looper.myLooper()) {
51 | return applicationLifecycle
52 | }
53 | return fragmentGet(activity.fragmentManager)
54 | }
55 |
56 | fun get(activity: FragmentActivity): Lifecycle {
57 | if (Looper.getMainLooper() != Looper.myLooper()) {
58 | return applicationLifecycle
59 | }
60 | return supportFragmentGet(activity.supportFragmentManager)
61 | }
62 |
63 | fun get(dialog: Dialog): Lifecycle {
64 | if (Looper.getMainLooper() != Looper.myLooper()) {
65 | return applicationLifecycle
66 | }
67 |
68 | val dialogClass = Class.forName("android.app.Dialog")
69 | val handlerClass = Class.forName("android.os.Handler")
70 |
71 | val mListenersHandler: Handler = InvokeUtil.getDeclaredFieldObject(dialogClass,"mListenersHandler", dialog) as Handler
72 | var mCallback = InvokeUtil.getDeclaredFieldObject(handlerClass,"mCallback", mListenersHandler)
73 | if (Dialog_SHOW == -1) {
74 | try {
75 | Dialog_SHOW =
76 | InvokeUtil.getDeclaredFieldObject(dialogClass, "SHOW", null) as Int
77 | } catch (e: Exception) {
78 | }
79 | }
80 | var hookListenersHandlerCallback: HookListenersHandlerCallback? = null
81 | mCallback?.let { hookListenersHandlerCallback = mCallback as HookListenersHandlerCallback? }
82 |
83 | hookListenersHandlerCallback?.let {
84 | return it.lifecycle
85 | }
86 |
87 | hookListenersHandlerCallback =
88 | HookListenersHandlerCallback(mListenersHandler)
89 | InvokeUtil.setDeclaredFieldObject(
90 | handlerClass,
91 | "mCallback",
92 | mListenersHandler,
93 | hookListenersHandlerCallback!!
94 | )
95 | mCallback = InvokeUtil.getDeclaredFieldObject(handlerClass,"mCallback", mListenersHandler)
96 |
97 | if (InvokeUtil.getDeclaredFieldObject("mDismissMessage",dialog) == null){
98 | dialog.setOnDismissListener { }
99 | }
100 | if (InvokeUtil.getDeclaredFieldObject("mShowMessage",dialog) == null){
101 | dialog.setOnShowListener { }
102 | }
103 | return hookListenersHandlerCallback!!.lifecycle
104 | }
105 |
106 | fun get(context: Context): Lifecycle {
107 | if (Looper.myLooper() == Looper.getMainLooper() && !(context is Application)) {
108 | when (context) {
109 | is FragmentActivity -> {
110 | return get(context)
111 | }
112 | is Activity -> {
113 | return get(context)
114 | }
115 | is ContextWrapper -> {
116 | return get(context.baseContext)
117 | }
118 | }
119 | }
120 | return applicationLifecycle
121 | }
122 |
123 |
124 | fun get(fragment: Fragment): Lifecycle {
125 | if (Looper.getMainLooper() != Looper.myLooper()) {
126 | return applicationLifecycle
127 | }
128 | return getSupportRequestManagerFragment(fragment.childFragmentManager).lifecycle
129 | }
130 |
131 | fun get(fragment: android.app.Fragment): Lifecycle {
132 | if (Looper.getMainLooper() != Looper.myLooper() || Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
133 | return applicationLifecycle
134 | } else {
135 | return getFragment(fragment.childFragmentManager).lifecycle
136 | }
137 | }
138 |
139 | fun supportFragmentGet(fm: android.support.v4.app.FragmentManager): Lifecycle {
140 | return getSupportRequestManagerFragment(fm).lifecycle
141 | }
142 |
143 | fun fragmentGet(fm: android.app.FragmentManager): Lifecycle {
144 | return getFragment(fm).lifecycle
145 | }
146 |
147 | private fun getSupportRequestManagerFragment(fm: android.support.v4.app.FragmentManager): SupportRequestManagerFragment {
148 | var fragment: SupportRequestManagerFragment? = fm.findFragmentByTag(FRAG_TAG) as SupportRequestManagerFragment?
149 | if (fragment == null) {
150 | fragment = pendingSupportsRequestManagerFragments.get(fm)
151 | if (fragment == null) {
152 | fragment = SupportRequestManagerFragment()
153 | pendingSupportsRequestManagerFragments[fm] = fragment
154 | fm.beginTransaction().add(fragment, FRAG_TAG).commitAllowingStateLoss()
155 | handler.obtainMessage(ID_REMOVE_SUPPORT_FRAGMENT_MANAGER, fm).sendToTarget()
156 | }
157 | return fragment
158 | } else {
159 | return fragment
160 | }
161 | }
162 |
163 | private fun getFragment(fm: android.app.FragmentManager): RequestManagerFragment {
164 | var fragment: RequestManagerFragment? = fm.findFragmentByTag(FRAG_TAG) as RequestManagerFragment?
165 | if (fragment == null) {
166 | fragment = pendingRequestManagerFragments.get(fm)
167 | if (fragment == null) {
168 | fragment = RequestManagerFragment()
169 | pendingRequestManagerFragments[fm] = fragment
170 | fm.beginTransaction().add(fragment, FRAG_TAG).commitAllowingStateLoss()
171 | handler.obtainMessage(ID_REMOVE_FRAGMENT_MANAGER, fm).sendToTarget()
172 | }
173 | return fragment
174 | } else {
175 | return fragment
176 | }
177 | }
178 | private fun findActivity(context: Context): Activity? {
179 | return context as? Activity ?: if (context is ContextWrapper) {
180 | findActivity(context.baseContext)
181 | } else {
182 | null
183 | }
184 | }
185 | fun get(view: View): Lifecycle {
186 | if (Looper.getMainLooper() != Looper.myLooper()) {
187 | return applicationLifecycle
188 | }
189 | val activity = findActivity(view.context) ?: return get(view.context.applicationContext)
190 | if (activity is FragmentActivity) {
191 | val fragment = findSupportFragment(view, activity)
192 | return fragment?.let { get(it) } ?: get(activity)
193 | }
194 | // Standard Fragments.
195 | val fragment = findFragment(view, activity) ?: return get(activity)
196 | return get(fragment)
197 | }
198 | private fun findFragment(target: View, activity: Activity): android.app.Fragment? {
199 | tempViewToFragment.clear()
200 | findAllFragmentsWithViews(activity.fragmentManager, tempViewToFragment)
201 | var result: android.app.Fragment? = null
202 | val activityRoot = activity.findViewById(android.R.id.content)
203 | var current = target
204 | while (current != activityRoot) {
205 | result = tempViewToFragment.get(current)
206 | if (result != null) {
207 | break
208 | }
209 | if (current.parent is View) {
210 | current = current.parent as View
211 | } else {
212 | break
213 | }
214 | }
215 | tempViewToFragment.clear()
216 | return result
217 | }
218 | @TargetApi(Build.VERSION_CODES.O)
219 | private fun findAllFragmentsWithViews(
220 | fragmentManager: android.app.FragmentManager, result: ArrayMap
221 | ) {
222 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
223 | for (fragment in fragmentManager.fragments) {
224 | if (fragment.view != null) {
225 | result[fragment.view] = fragment
226 | findAllFragmentsWithViews(fragment.childFragmentManager, result)
227 | }
228 | }
229 | } else {
230 | findAllFragmentsWithViewsPreO(fragmentManager, result)
231 | }
232 | }
233 | private fun findAllFragmentsWithViewsPreO(
234 | fragmentManager: android.app.FragmentManager, result: ArrayMap
235 | ) {
236 | var index = 0
237 | while (true) {
238 | tempBundle.putInt(FRAGMENT_INDEX_KEY, index++)
239 | var fragment: android.app.Fragment? = null
240 | try {
241 | fragment = fragmentManager.getFragment(tempBundle, FRAGMENT_INDEX_KEY)
242 | } catch (e: Exception) {
243 | // This generates log spam from FragmentManager anyway.
244 | }
245 |
246 | if (fragment == null) {
247 | break
248 | }
249 | if (fragment.view != null) {
250 | result[fragment.view] = fragment
251 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
252 | findAllFragmentsWithViews(fragment.childFragmentManager, result)
253 | }
254 | }
255 | }
256 | }
257 |
258 | private fun findSupportFragment(target: View, activity: FragmentActivity): Fragment? {
259 | tempViewToSupportFragment.clear()
260 | findAllSupportFragmentsWithViews(
261 | activity.supportFragmentManager.fragments, tempViewToSupportFragment
262 | )
263 | var result: Fragment? = null
264 | val activityRoot = activity.findViewById(android.R.id.content)
265 | var current = target
266 | while (current != activityRoot) {
267 | result = tempViewToSupportFragment[current]
268 | if (result != null) {
269 | break
270 | }
271 | if (current.parent is View) {
272 | current = current.parent as View
273 | } else {
274 | break
275 | }
276 | }
277 |
278 | tempViewToSupportFragment.clear()
279 | return result
280 | }
281 | private fun findAllSupportFragmentsWithViews(
282 | topLevelFragments: Collection?,
283 | result: MutableMap
284 | ) {
285 | if (topLevelFragments == null) {
286 | return
287 | }
288 | for (fragment in topLevelFragments) {
289 | fragment?.also {
290 | it.view?.let{view->
291 | result[view] = fragment
292 | findAllSupportFragmentsWithViews(fragment.childFragmentManager.fragments, result)
293 | }
294 | }
295 |
296 | }
297 | }
298 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/Tick.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle
2 |
3 | import android.view.View
4 | import com.gucci.lifecycle.annotations.*
5 | import com.gucci.lifecycle.util.LifecycleUtil
6 |
7 |
8 | class Tick(private val view: View):LifecycleListener {
9 | private lateinit var mTickRunnable:Runnable
10 | init {
11 | mTickRunnable = Runnable {
12 | if (view.parent == null)return@Runnable
13 | LifecycleUtil.doActionOnOnlyItself(view,OnTick::class.java)
14 | view.postDelayed(mTickRunnable,1000)
15 | }
16 | this bind view
17 | }
18 |
19 | @OnStart
20 | fun doOnStart(){
21 | if (view.parent == null)return
22 | view.removeCallbacks(mTickRunnable)
23 | LifecycleUtil.doActionOnOnlyItself(view,OnTick::class.java)
24 | view.postDelayed(mTickRunnable,1000)
25 | }
26 |
27 | @OnStop
28 | fun doOnStop(){
29 | view.removeCallbacks(mTickRunnable)
30 | }
31 |
32 | @OnAttachedToWindow
33 | fun doOnAttachedToWindow(){
34 | view.removeCallbacks(mTickRunnable)
35 | LifecycleUtil.doActionOnOnlyItself(view,OnTick::class.java)
36 | view.postDelayed(mTickRunnable,1000)
37 | }
38 | @OnDetachedToWindow
39 | fun doOnDetachedToWindow(){
40 | view.removeCallbacks(mTickRunnable)
41 | }
42 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/annotations/OnAttachedToWindow.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.annotations
2 |
3 | /**
4 | * Created by 李志云 2019/4/28 02:10
5 | */
6 | @Target(AnnotationTarget.FUNCTION)
7 | @Retention(AnnotationRetention.RUNTIME)
8 | annotation class OnAttachedToWindow {
9 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/annotations/OnCreate.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.annotations
2 |
3 | /**
4 | * Created by 李志云 2019/4/28 02:10
5 | */
6 | @Target(AnnotationTarget.FUNCTION)
7 | @Retention(AnnotationRetention.RUNTIME)
8 | annotation class OnCreate {
9 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/annotations/OnDestory.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.annotations
2 |
3 | /**
4 | * Created by 李志云 2019/4/28 02:10
5 | */
6 | @Target(AnnotationTarget.FUNCTION)
7 | @Retention(AnnotationRetention.RUNTIME)
8 | annotation class OnDestory {
9 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/annotations/OnDetachedToWindow.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.annotations
2 |
3 | /**
4 | * Created by 李志云 2019/4/28 02:10
5 | */
6 | @Target(AnnotationTarget.FUNCTION)
7 | @Retention(AnnotationRetention.RUNTIME)
8 | annotation class OnDetachedToWindow {
9 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/annotations/OnPause.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.annotations
2 |
3 | /**
4 | * Created by 李志云 2019/4/28 02:10
5 | */
6 | @Target(AnnotationTarget.FUNCTION)
7 | @Retention(AnnotationRetention.RUNTIME)
8 | annotation class OnPause {
9 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/annotations/OnResume.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.annotations
2 |
3 | /**
4 | * Created by 李志云 2019/4/28 02:10
5 | */
6 | @Target(AnnotationTarget.FUNCTION)
7 | @Retention(AnnotationRetention.RUNTIME)
8 | annotation class OnResume {
9 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/annotations/OnStart.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.annotations
2 |
3 | @Target(AnnotationTarget.FUNCTION)
4 | @Retention(AnnotationRetention.RUNTIME)
5 | annotation class OnStart {
6 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/annotations/OnStop.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.annotations
2 |
3 | /**
4 | * Created by 李志云 2019/4/28 02:10
5 | */
6 | @Target(AnnotationTarget.FUNCTION)
7 | @Retention(AnnotationRetention.RUNTIME)
8 | annotation class OnStop {
9 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/annotations/OnTick.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.annotations
2 |
3 | /**
4 | * Created by 李志云 2019/4/28 02:10
5 | */
6 | @Target(AnnotationTarget.FUNCTION)
7 | @Retention(AnnotationRetention.RUNTIME)
8 | annotation class OnTick {
9 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/lifecycle/ActivityFragmentLifecycle.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.lifecycle
2 |
3 | import android.view.ViewGroup
4 | import com.gucci.lifecycle.LifecycleListener
5 | import com.gucci.lifecycle.util.LifecycleUtil.Companion.doAction
6 | import com.gucci.lifecycle.util.LifecycleUtil.Companion.getAllNeedListeneredFields
7 | import com.gucci.lifecycle.annotations.*
8 | import com.gucci.lifecycle.getSnapshot
9 | import com.gucci.lifecycle.util.InvokeUtil
10 | import java.util.*
11 |
12 | open class ActivityFragmentLifecycle : Lifecycle {
13 | override fun getListeners(): Set {
14 | return lifecycleListeners
15 | }
16 |
17 | val lifecycleListeners = Collections.newSetFromMap(WeakHashMap())
18 | var isStarted = false
19 | var isResumed = false
20 | var isDestroyed = false
21 | var isFirst = true
22 |
23 | override fun removeListener(litener: LifecycleListener) {
24 | lifecycleListeners.remove(litener)
25 | }
26 |
27 | override fun addListener(litener: LifecycleListener) {
28 | lifecycleListeners.add(litener)
29 | if (isDestroyed) {
30 | doAction(litener,OnDestory::class.java)
31 | } else if (isStarted) {
32 | doAction(litener,OnStart::class.java)
33 | } else if (isResumed) {
34 | doAction(litener,OnResume::class.java)
35 | } else {
36 | if (isFirst) {
37 | isFirst = false
38 | } else {
39 | doAction(litener,OnStop::class.java)
40 | }
41 | }
42 | }
43 |
44 | fun onCreate() {
45 | lifecycleListeners.getSnapshot().forEach { performChildrenAndYouSelf(it, OnCreate::class.java) }
46 | }
47 |
48 | fun onResume() {
49 | isResumed = true
50 | lifecycleListeners.getSnapshot().forEach { performChildrenAndYouSelf(it, OnResume::class.java) }
51 | }
52 |
53 | fun onPause() {
54 | isResumed = false
55 | lifecycleListeners.getSnapshot().forEach { performChildrenAndYouSelf(it, OnPause::class.java) }
56 | }
57 |
58 | fun onStart() {
59 | isStarted = true
60 | lifecycleListeners.getSnapshot().forEach { performChildrenAndYouSelf(it, OnStart::class.java) }
61 | }
62 |
63 | fun onStop() {
64 | isStarted = false
65 | lifecycleListeners.getSnapshot().forEach { performChildrenAndYouSelf(it, OnStop::class.java) }
66 | }
67 |
68 | fun onDestory() {
69 | isDestroyed = true
70 | lifecycleListeners.getSnapshot().forEach { performChildrenAndYouSelf(it, OnDestory::class.java) }
71 | lifecycleListeners.clear()
72 | }
73 |
74 | fun performChildrenAndYouSelf(lifecycleListener: LifecycleListener, clazz: Class) {
75 | if (lifecycleListener is ViewGroup) {
76 | val count = lifecycleListener.childCount
77 | for (i in 0 until count) {
78 | val child = lifecycleListener.getChildAt(i)
79 | if (child is LifecycleListener) {
80 | performChildrenAndYouSelf(child, clazz)
81 | }
82 | }
83 | } else {
84 | //非ViewGroup,它的内部也可能包含ViewGroup,所以这里的代码还得递归到外面
85 | getAllNeedListeneredFields(lifecycleListener).forEach {
86 | val bean = InvokeUtil.getDeclaredFieldObject(it, lifecycleListener)
87 | if (bean != null && bean is LifecycleListener) {
88 | performChildrenAndYouSelf(bean, clazz)
89 | }
90 | }
91 | }
92 | doAction(lifecycleListener,clazz)
93 | }
94 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/lifecycle/ApplicationLifecycle.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.lifecycle
2 |
3 | import com.gucci.lifecycle.LifecycleListener
4 | import com.gucci.lifecycle.annotations.OnStart
5 | import com.gucci.lifecycle.util.LifecycleUtil
6 | import java.util.*
7 |
8 | /**
9 | * 留待拆解glide使用
10 | */
11 | class ApplicationLifecycle : Lifecycle {
12 | override fun getListeners(): Set {
13 | return lifecycleListeners
14 | }
15 |
16 | //建议使用它时需要监听application的低电量状态onLowMemory时清空之
17 | private val lifecycleListeners = Collections.newSetFromMap(WeakHashMap())
18 |
19 | override fun addListener(litener: LifecycleListener) {
20 | LifecycleUtil.doAction(litener,OnStart::class.java)
21 | lifecycleListeners.add(litener)
22 | }
23 |
24 | override fun removeListener(litener: LifecycleListener) {
25 | }
26 |
27 | fun clear() {
28 | lifecycleListeners.clear()
29 | }
30 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/lifecycle/Lifecycle.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.lifecycle
2 |
3 | import com.gucci.lifecycle.LifecycleListener
4 |
5 | interface Lifecycle {
6 | fun addListener(litener: LifecycleListener)
7 | fun removeListener(litener: LifecycleListener)
8 | fun getListeners():Set
9 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/lifecycleContainer/HookListenersHandlerCallback.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.lifecycleContainer
2 |
3 | import android.os.Handler
4 | import android.os.Message
5 | import com.gucci.lifecycle.ManagerRetriever
6 | import com.gucci.lifecycle.lifecycle.ActivityFragmentLifecycle
7 |
8 | class HookListenersHandlerCallback(val handler: Handler):Handler.Callback {
9 | val lifecycle = ActivityFragmentLifecycle()
10 | override fun handleMessage(msg: Message): Boolean {
11 | when(msg.what){
12 | ManagerRetriever.Dialog_SHOW ->{
13 | lifecycle.onCreate()
14 | }
15 | else ->{
16 | lifecycle.onDestory()
17 | }
18 | }
19 | handler.handleMessage(msg)
20 | return true
21 | }
22 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/lifecycleContainer/RequestManagerFragment.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.lifecycleContainer
2 |
3 | import android.app.Fragment
4 | import android.content.Context
5 | import android.os.Bundle
6 | import com.gucci.lifecycle.lifecycle.ActivityFragmentLifecycle
7 |
8 |
9 | class RequestManagerFragment : Fragment() {
10 |
11 | val lifecycle = ActivityFragmentLifecycle()
12 |
13 |
14 | override fun onStart() {
15 | super.onStart()
16 | lifecycle.onStart()
17 | }
18 |
19 | override fun onStop() {
20 | super.onStop()
21 | lifecycle.onStop()
22 | }
23 |
24 | override fun onDestroy() {
25 | super.onDestroy()
26 | lifecycle.onDestory()
27 | }
28 |
29 | override fun onCreate(savedInstanceState: Bundle?) {
30 | super.onCreate(savedInstanceState)
31 | lifecycle.onCreate()
32 | }
33 |
34 | override fun onPause() {
35 | super.onPause()
36 | lifecycle.onPause()
37 | }
38 |
39 | override fun onResume() {
40 | super.onResume()
41 | lifecycle.onResume()
42 | }
43 |
44 | override fun onAttach(context: Context?) {
45 | super.onAttach(context)
46 | }
47 |
48 | override fun onDetach() {
49 | super.onDetach()
50 | }
51 |
52 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/lifecycleContainer/SupportRequestManagerFragment.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.lifecycleContainer
2 |
3 | import android.content.Context
4 | import android.os.Bundle
5 | import android.support.v4.app.Fragment
6 | import android.view.LayoutInflater
7 | import android.view.View
8 | import android.view.ViewGroup
9 | import com.gucci.lifecycle.lifecycle.ActivityFragmentLifecycle
10 |
11 | class SupportRequestManagerFragment : Fragment() {
12 | val lifecycle = ActivityFragmentLifecycle()
13 | private var rootRequestManagerFragment:SupportRequestManagerFragment? = null
14 | private val childRequestManagerFragments = HashSet()
15 | override fun onDestroy() {
16 | super.onDestroy()
17 | lifecycle.onDestory()
18 | }
19 |
20 | override fun onStart() {
21 | super.onStart()
22 | lifecycle.onStart()
23 | }
24 |
25 | override fun onStop() {
26 | super.onStop()
27 | lifecycle.onStop()
28 | }
29 |
30 |
31 | override fun onCreate(savedInstanceState: Bundle?) {
32 | super.onCreate(savedInstanceState)
33 | lifecycle.onCreate()
34 | }
35 |
36 | override fun onPause() {
37 | super.onPause()
38 | lifecycle.onPause()
39 | }
40 |
41 | override fun onResume() {
42 | super.onResume()
43 | lifecycle.onResume()
44 | }
45 |
46 |
47 | override fun onAttach(context: Context?) {
48 | super.onAttach(context)
49 | }
50 |
51 | override fun onDetach() {
52 | super.onDetach()
53 | }
54 |
55 |
56 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/util/InvokeUtil.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.util
2 |
3 | import java.lang.reflect.Field
4 | import java.lang.reflect.Method
5 | import java.util.*
6 |
7 |
8 | class InvokeUtil {
9 | companion object {
10 |
11 | @Throws(NoSuchFieldException::class)
12 | fun findField(instance: Any, name: String): Field {
13 | return findField(instance::class.java, name)
14 | }
15 |
16 | @Throws(NoSuchFieldException::class)
17 | fun findField(forName: String, name: String): Field {
18 | return findField(Class.forName(forName), name)
19 | }
20 |
21 | @Throws(NoSuchFieldException::class)
22 | fun findField(c: Class<*>, name: String): Field {
23 | var clazz = c
24 | //反射获得
25 | while (clazz != null) {
26 | try {
27 | val field = clazz.getDeclaredField(name)
28 | //如果无法访问 设置为可访问
29 | if (!field.isAccessible) {
30 | field.isAccessible = true
31 | }
32 | return field
33 | } catch (e: NoSuchFieldException) {
34 | //如果找不到往父类找
35 | clazz = clazz.superclass
36 | }
37 |
38 | }
39 | throw NoSuchFieldException("Field " + name + " not found in " + clazz)
40 | }
41 |
42 |
43 | /**
44 | * 反射获得 指定对象(当前-》父类-》父类...)中的 函数
45 | * @param instance
46 | * @param name
47 | * @param parameterTypes
48 | * @return
49 | * @throws NoSuchMethodException
50 | */
51 | @Throws(NoSuchMethodException::class)
52 | fun findMethod(instance: Any, name: String, vararg parameterTypes: Class<*>): Method {
53 | var clazz: Class<*>? = null
54 | if (instance is Class<*>){
55 | clazz = instance
56 | }else{
57 | instance::class.java
58 | }
59 | while (clazz != null) {
60 | try {
61 | val method = clazz.getDeclaredMethod(name, *parameterTypes)
62 | if (!method.isAccessible) {
63 | method.isAccessible = true
64 | }
65 | return method
66 | } catch (e: NoSuchMethodException) {
67 | //如果找不到往父类找
68 | clazz = clazz.superclass
69 | }
70 |
71 | }
72 | throw NoSuchMethodException("Method " + name + " with parameters " + Arrays.asList(*parameterTypes) + " not found in " + instance.javaClass)
73 | }
74 |
75 | fun getDeclaredFieldObject(clazz: Class<*>, fieldName: String, `object`: Any?): Any? {
76 | try {
77 | val field = clazz.getDeclaredField(fieldName)
78 | return getDeclaredFieldObject(field, `object`)
79 | }catch (e:java.lang.Exception){}
80 | return null
81 | }
82 | fun getDeclaredFieldObject(field:Field, `object`: Any?): Any? {
83 | try {
84 | field.isAccessible = true
85 | return field.get(`object`)
86 | }catch (e:java.lang.Exception){}
87 | return null
88 | }
89 |
90 |
91 |
92 | fun getDeclaredFieldObject(fieldName: String, `object`: Any): Any? {
93 | return getDeclaredFieldObject(
94 | `object`::class.java,
95 | fieldName,
96 | `object`
97 | )
98 | }
99 |
100 | @Throws(Exception::class)
101 | fun setDeclaredFieldObject(clazz: Class<*>, fieldName: String, `object`: Any, value: Any) {
102 | val field = clazz.getDeclaredField(fieldName)
103 | field.isAccessible = true
104 | field.set(`object`, value)
105 | }
106 |
107 | @Throws(Exception::class)
108 | fun setDeclaredFieldObject(fieldName: String, `object`: Any, value: Any) {
109 | val field = `object`::class.java.getDeclaredField(fieldName)
110 | field.isAccessible = true
111 | field.set(`object`, value)
112 | }
113 | @Throws(Exception::class)
114 | fun invoke(instance: Any?,method:Method,vararg value: Any){
115 | method.isAccessible = true
116 | method.invoke(instance,value)
117 | }
118 | @Throws(Exception::class)
119 | fun invokeForResult(instance: Any?,method:Method,vararg value: Any):Any{
120 | method.isAccessible = true
121 | return method.invoke(instance,value)
122 | }
123 | @Throws(Exception::class)
124 | fun invokeForResult(instance: Any?,method:Method):Any{
125 | method.isAccessible = true
126 | return method.invoke(instance)
127 | }
128 | @Throws(Exception::class)
129 | fun invoke(instance: Any?,method:Method){
130 | method.isAccessible = true
131 | method.invoke(instance)
132 | }
133 |
134 | @Throws(NoSuchFieldException::class, IllegalAccessException::class)
135 | fun expandFieldArray(instance: Any, fieldName: String, extraElements: Array) {
136 | val field = findField(instance, fieldName)
137 | var original = field.get(instance) as Array
138 | val combined = java.lang.reflect.Array.newInstance(original.javaClass.componentType, original.size + extraElements.size);
139 | System.arraycopy(extraElements, 0, combined, 0, extraElements.size)
140 | System.arraycopy(original, 0, combined, extraElements.size, original.size)
141 | field.set(instance, combined)
142 | }
143 |
144 | }
145 |
146 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/gucci/lifecycle/util/LifecycleUtil.kt:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle.util
2 |
3 | import android.app.Activity
4 | import android.app.Application
5 | import android.os.Bundle
6 | import android.util.Log
7 | import com.gucci.lifecycle.LifecycleListener
8 | import com.gucci.lifecycle.annotations.*
9 | import java.lang.Exception
10 | import java.lang.reflect.Field
11 |
12 |
13 | class LifecycleUtil {
14 |
15 | companion object {
16 | val sListenerMap = HashMap,ArrayList>()
17 | fun doAction(lifecycleListener: LifecycleListener, clazz: Class) {
18 | lifecycleListener.javaClass.declaredMethods.forEach { method ->
19 | method.getAnnotation(clazz)?.let {
20 | if (method.getParameterTypes().size == 0) {
21 | try {
22 | InvokeUtil.invoke(lifecycleListener, method)
23 | }catch (e:Exception){
24 | e.printStackTrace()
25 | }
26 | }
27 | }
28 | }
29 | }
30 |
31 | fun getAllNeedListeneredFields(any: Any): ArrayList {
32 | sListenerMap[any.javaClass]?.let {
33 | return it
34 | }
35 | val list = ArrayList()
36 | any.javaClass.declaredFields?.let {
37 | it.forEach {
38 | if (isListener(it)) {
39 | list.add(it)
40 | }
41 | }
42 | }
43 | sListenerMap.put(any.javaClass,list)
44 | return list
45 | }
46 |
47 | fun isListener(f: Field): Boolean {
48 | val cls = f.getType().getInterfaces()
49 | for (c in cls) {
50 | if (LifecycleListener::class.java == c) {
51 | return true
52 | }
53 | }
54 | return false
55 | }
56 |
57 | fun init(application: Application){
58 | application.registerActivityLifecycleCallbacks(object :Application.ActivityLifecycleCallbacks{
59 | override fun onActivityPaused(activity: Activity) {
60 | dispatchAction(activity, OnPause::class.java)
61 | }
62 |
63 | override fun onActivityResumed(activity: Activity) {
64 | dispatchAction(activity, OnResume::class.java)
65 | }
66 |
67 | override fun onActivityStarted(activity: Activity) {
68 | dispatchAction(activity, OnStart::class.java)
69 | }
70 |
71 | override fun onActivityDestroyed(activity: Activity) {
72 | dispatchAction(activity, OnDestory::class.java)
73 | }
74 |
75 | override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) {
76 | }
77 |
78 | override fun onActivityStopped(activity: Activity) {
79 | dispatchAction(activity, OnStop::class.java)
80 | }
81 |
82 | override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
83 | dispatchAction(activity, OnCreate::class.java)
84 | }
85 |
86 | })
87 |
88 | }
89 | fun dispatchAction(any: Any,clazz: Class){
90 | getAllNeedListeneredFields(any).forEach {
91 | val bean = InvokeUtil.getDeclaredFieldObject(it, any)
92 | if (bean is LifecycleListener) {
93 | doAction(bean, clazz)
94 | }
95 | }
96 | }
97 |
98 | fun doActionOnOnlyItself(any: Any, clazz: Class) {
99 |
100 | any.javaClass.declaredMethods.forEach { method ->
101 | method.getAnnotation(clazz)?.let {
102 | if (method.getParameterTypes().size == 0) {
103 | try {
104 | InvokeUtil.invoke(any, method)
105 | }catch (e:Exception){
106 | e.printStackTrace()
107 | }
108 | }
109 | }
110 | }
111 | }
112 | }
113 | }
--------------------------------------------------------------------------------
/library/src/test/java/com/gucci/lifecycle/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.gucci.lifecycle;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':library'
2 |
--------------------------------------------------------------------------------