├── .gitignore
├── LICENSE
├── README.md
├── build.gradle
├── cactus-sample
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── gyf
│ │ └── cactus
│ │ └── sample
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── ic_launcher-web.png
│ ├── java
│ │ └── com
│ │ │ └── gyf
│ │ │ └── cactus
│ │ │ └── sample
│ │ │ ├── App.kt
│ │ │ ├── AppManager.kt
│ │ │ ├── BaseActivity.kt
│ │ │ ├── MainActivity.kt
│ │ │ ├── MainReceiver.kt
│ │ │ ├── PrefExt.kt
│ │ │ ├── Preference.kt
│ │ │ ├── Save.kt
│ │ │ └── TwoActivity.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ ├── activity_two.xml
│ │ └── notification_view.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ ├── ic_launcher_foreground.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ ├── ic_launcher_foreground.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ ├── ic_launcher_foreground.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ ├── ic_launcher_foreground.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ ├── ic_launcher_foreground.png
│ │ └── ic_launcher_round.png
│ │ ├── raw
│ │ └── main.mp3
│ │ └── values
│ │ ├── colors.xml
│ │ ├── ic_launcher_background.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── gyf
│ └── cactus
│ └── sample
│ └── ExampleUnitTest.kt
├── cactus.png
├── cactus
├── .gitignore
├── build.gradle
├── consumer-rules.pro
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── aidl
│ └── com
│ │ └── gyf
│ │ └── cactus
│ │ └── entity
│ │ ├── CactusConfig.aidl
│ │ └── ICactusInterface.aidl
│ ├── java
│ └── com
│ │ └── gyf
│ │ └── cactus
│ │ ├── Cactus.kt
│ │ ├── callback
│ │ ├── AppBackgroundCallback.kt
│ │ ├── CactusBackgroundCallback.kt
│ │ └── CactusCallback.kt
│ │ ├── entity
│ │ ├── CactusConfig.kt
│ │ ├── Constant.kt
│ │ ├── DefaultConfig.kt
│ │ └── NotificationConfig.kt
│ │ ├── exception
│ │ ├── CactusException.kt
│ │ └── CactusUncaughtExceptionHandler.kt
│ │ ├── ext
│ │ ├── CactusExt.kt
│ │ ├── ConfigExt.kt
│ │ ├── ManagerExt.kt
│ │ └── NotificationExt.kt
│ │ ├── pix
│ │ └── OnePixActivity.kt
│ │ ├── receiver
│ │ └── StopReceiver.kt
│ │ ├── service
│ │ ├── CactusJobService.kt
│ │ ├── HideForegroundService.kt
│ │ ├── LocalService.kt
│ │ └── RemoteService.kt
│ │ └── workmanager
│ │ └── CactusWorker.kt
│ └── res
│ ├── drawable
│ ├── icon_cactus_small.png
│ └── icon_cactus_trans.png
│ ├── raw
│ └── cactus.mp3
│ └── values
│ ├── strings.xml
│ └── styles.xml
├── gradle.properties
├── gradle
└── wrapper
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.gitignore.io/api/androidstudio
3 |
4 | ### AndroidStudio ###
5 | # Covers files to be ignored for android development using Android Studio.
6 |
7 | # Built application files
8 | *.ap_
9 |
10 | # Files for the ART/Dalvik VM
11 | *.dex
12 |
13 | # Java class files
14 | *.class
15 |
16 | # Generated files
17 | bin/
18 | gen/
19 | out/
20 |
21 | # Gradle files
22 | .gradle
23 | .gradle/
24 | build/
25 |
26 | # Signing files
27 | .signing/
28 |
29 | # Local configuration file (sdk path, etc)
30 | local.properties
31 |
32 | # Proguard folder generated by Eclipse
33 | proguard/
34 |
35 | # Log Files
36 | *.log
37 |
38 | # Android Studio
39 | /*/build/
40 | /*/local.properties
41 | /*/out
42 | /*/*/build
43 | /*/*/production
44 | captures/
45 | .navigation/
46 | *.ipr
47 | *~
48 | *.swp
49 |
50 | # Android Patch
51 | gen-external-apklibs
52 |
53 | # External native build folder generated in Android Studio 2.2 and later
54 | .externalNativeBuild
55 |
56 | # NDK
57 | obj/
58 |
59 | # IntelliJ IDEA
60 | *.iml
61 | *.iws
62 | /out/
63 |
64 | # User-specific configurations
65 | .idea
66 |
67 | # Keystore files
68 | *.jks
69 |
70 | # OS-specific files
71 | .DS_Store
72 | .DS_Store?
73 | ._*
74 | .Spotlight-V100
75 | .Trashes
76 | ehthumbs.db
77 | Thumbs.db
78 |
79 | # Legacy Eclipse project files
80 | .classpath
81 | .project
82 |
83 | # Mobile Tools for Java (J2ME)
84 | .mtj.tmp/
85 |
86 | # Package Files #
87 | #*.jar
88 | *.war
89 | *.ear
90 |
91 | # virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml)
92 | hs_err_pid*
93 |
94 | ## Plugin-specific files:
95 |
96 | # mpeltonen/sbt-idea plugin
97 | .idea_modules/
98 |
99 | # JIRA plugin
100 | atlassian-ide-plugin.xml
101 |
102 | # Mongo Explorer plugin
103 | .idea/mongoSettings.xml
104 |
105 | # Crashlytics plugin (for Android Studio and IntelliJ)
106 | com_crashlytics_export_strings.xml
107 | crashlytics.properties
108 | crashlytics-build.properties
109 | fabric.properties
110 |
111 | # End of https://www.gitignore.io/api/androidstudio
112 | .idea/copyright/
113 | gradle/wrapper/gradle-wrapper.jar
114 | /cactus-sample/release/cactus-sample-release.apk
115 | /cactus-sample/release/output.json
116 |
--------------------------------------------------------------------------------
/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 | ## [点我下载demo](https://www.pgyer.com/Cactus)(密码:cactus)
2 |
3 | ## 注意!注意!注意!写在前面
4 | 如果你项目里使用了Thread.UncaughtExceptionHandler或者第三方异常捕获库,比如友盟,bugly等,Cactus请在Thread.UncaughtExceptionHandler或者第三方异常捕获库,比如友盟,bugly等之后注册使用,并且建议在Application里注册使用。
5 | 为什么要这样操作?因为如果android 8.0以上设备隐藏了通知栏信息,当您的app崩溃重启后会出现invalid channel for service notification异常,而该异常属于系统级别的,没法捕获,所以Cactus对该异常进行了杀死app的操作,但是并不能保证第三方异常监控还是能捕获它。
6 | 如果第三方后台还是有该异常信息,你又觉得该异常影响你的app崩溃率,请调用hideNotificationAfterO(false)方法,打开通知栏信息。
7 |
8 | ## 使用
9 | > android studio
10 | - androidx
11 | ```groovy
12 | implementation 'com.gyf.cactus:cactus:1.1.3-beta13'
13 | ```
14 | - android support
15 | ```groovy
16 | implementation 'com.gyf.cactus:cactus-support:1.1.3-beta13'
17 | ```
18 |
19 | ## 用法(具体api请参考api说明)
20 | #### java用法
21 |
22 | - 注册
23 | ```java
24 | Cactus.getInstance()
25 | .isDebug(true)
26 | .setPendingIntent(pendingIntent)
27 | .addCallback(new CactusCallback())
28 | ... //其他api等
29 | ...
30 | .register(this)
31 | ```
32 | - 注销
33 | ```java
34 | Cactus.getInstance().unregister(this)
35 | ```
36 | - 重启
37 | ```java
38 | Cactus.getInstance().restart(this)
39 | ```
40 | #### kotlin用法
41 |
42 | - 注册
43 | ```kotlin
44 | cactus {
45 | setPendingIntent(pendingIntent)
46 | setMusicId(R.raw.main)
47 | isDebug(true)
48 | ... //其他api等
49 | ...
50 | addCallback({
51 | //onStop回调,可以省略
52 | }) {
53 | //doWork回调
54 | }
55 | }
56 | ```
57 | - 注销
58 | ```kotlin
59 | cactusUnregister()
60 | ```
61 | - 重启
62 | ```kotlin
63 | cactusRestart()
64 | ```
65 | ## 混淆规则(proguard-rules.pro)
66 | ```
67 | -keep class com.gyf.cactus.entity.* {*;}
68 | ```
69 |
70 | ## api说明,★ 标识的建议用户修改,而不是使用默认值
71 | | api | 说明 | api | 说明 |
72 | | :------------- |:-------------:| :------------- | :-------------:|
73 | | ★ setChannelId | 渠道Id,默认是Cactus,建议用户修改,非必传 | ★ setChannelName | 渠道名,用于设置里通知渠道展示,默认是Cactus,建议用户修改,非必传 |
74 | | ★ setTitle | 通知栏标题,默认是Cactus,建议用户修改,非必传 | ★ setContent |通知栏内容,默认是Cactus is running,建议用户修改,非必传 |
75 | | ★ setSmallIcon | 通知栏小图标,默认是库里的图标,建议用户修改,非必传 | setLargeIcon | 通知栏大图标,默认没有大图标,非必传 |
76 | | ★ setServiceId | 服务Id,默认是1到Int.MAX_VALUE随机数,非必传 | setPendingIntent | 设置PendingIntent,用来处理通知栏点击事件,非必传 |
77 | | addCallback | 增加回调,用于处理一些额外的工作,非必传 | addBackgroundCallback | 前后台切换回调,用于处理app前后台切换,非必传 |
78 | | setWorkerEnabled | 是否可以使用WorkManager,默认可以使用,非必传 | setCrashRestartUIEnabled | 奔溃是否可以重启用户界面,默认为false,google原生rom android 10 以下可以正常重启,非必传 |
79 | | setRemoteViews | 设置RemoteViews(自定义布局),非必传 | setBigRemoteViews |设置BigRemoteViews(自定义布局),非必传 |
80 | | hideNotification | 是否隐藏通知栏,经测试,除了android 7.1手机之外都可以隐藏,默认隐藏,非必传 | hideNotificationAfterO |是否隐藏Android 8.0以上通知栏,默认隐藏 |
81 | | setMusicEnabled | 是否可以播放音乐,默认可以播放音乐,非必传 | setBackgroundMusicEnabled | 后台是否可以播放音乐,默认不可以后台播放音乐,非必传 |
82 | | setMusicId | 设置自定义音乐,默认是无声音乐,该api只要在isDebug为true才会有生效,非必传 | ★ setMusicInterval | 设置音乐间隔时间,时间间隔越长,越省电,默认间隔时间是0,非必传 |
83 | | setOnePixEnabled | 是否可以使用一像素,默认可以使用,只有在android p以下可以使用,非必传 | isDebug | 是否Debug模式,默认没有调试信息,非必传 |
84 | | setNotification | 设置notification,非必传,如果不传,将使用用户根据其他api设置的信息构建Notification | setNotificationChannel |设置NotificationChannel,非必传,如果不传,将使用默认的NotificationChannel |
85 | | register | 必须调用,建议在Application里初始化,使用Kotlin扩展函数不需要调用此方法 | unregister | 注销,并不会立马停止,而是在1s之后停止,非必须调用,比如可以在app完全退出的时候可以调用,根据你的需求调用 |
86 | | restart | 重启,与register区别在于不会重新配置CactusConfig信息,而是使用上一次配置的信息 | isRunning | 是否在运行 |
87 |
88 | ## 流程图
89 | 
90 |
91 | ## 保活效果,仅供参考(数字代码oom_adj优先级,优先级数字越小越不容易被杀)
92 | | 维度 | android 6.0以下虚拟机 | android 7.1虚拟机 | android 7/8/8.1/9/10虚拟机 | vovo x23 (android 9) | 华为 mate20 /OnePlus (android 9) | 华为 mate30 pro (android 10) |
93 | | :-------------: |:-------------:| :-------------:| :-------------:| :-------------:|:-------------:|:-------------:|
94 | | 前台 | 0 | 0 |0 |0 |0 |0 |
95 | | 后台(优化前) | 6 | 立马死了 |11 |8 |11 |11 |
96 | | 后台(优化后) | 1 | 3 |3 |4 |3 |0 |
97 | | 息屏(优化前) | 6 | 立马死了 |11 |9 |11 |11 |
98 | | 息屏(优化后) | 0 | 3 |3 |4 |3 |0 |
99 | - 说明:oom_adj优先级数字越小越不容易被杀
100 |
101 | | oom_adj | 说明 | oom_adj | 说明 |
102 | | :-------------: |:-------------:| :-------------:| :-------------:|
103 | | 0 | 前台进程 | 1 |可见进程 |
104 | | 2 | 可感知的进程,比如那种播放音乐 | 3 |正在备份的进程 |
105 | | 4 | 高权重进程 | 5 |有Service的进程 |
106 | | 6 | 与Home交互的进程 | 7 |切换进程 |
107 | | 8 | 不活跃的进程 | 9 |缓存进程,也就是空进程 |
108 | | 11 | 缓存进程,也就是空进程 | 15 |缓存进程,空进程,在内存不足的情况下就会优先被kill |
109 | | 16 | 预留的最低级别,一般对于缓存的进程才有可能设置成这个级别 | | |
110 |
111 | ## 更新说明
112 | #### 1.1.2
113 | - 增加注销和重启功能
114 | - 增加判断服务是否是在运行中
115 | - 增加hideNotificationAfterO方法(是否隐藏Android 8.0以上通知栏)
116 | - 优化代码
117 |
118 | #### 1.1.1
119 | - 重点:修复1.1.0版本由于新增设置渠道api(setNotificationChannel)忘记做渠道判断,导致在8.0以下手机奔溃,1.0.8版本不受影响
120 |
121 | #### 1.1.0
122 | - 除了android7.1手机都可以隐藏通知栏了
123 | - 增加一些通知栏相关api,比如可以自定义view了
124 | - 优化代码
125 |
126 | #### 1.0.8
127 | - 解决设置后台可以播放音乐,奔溃重启后无法继续播放音乐的问题
128 |
129 | #### 1.0.7
130 | - 增加前后台切换监听
131 | - 增加设置后台是否可以播放音乐的api
132 |
133 | ## 联系我 ##
134 | - QQ群 314360549(问题交流)
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext.cactus_version = '1.1.3-beta13'
5 | ext.kotlin_version = '1.4.0'
6 | repositories {
7 | google()
8 | jcenter()
9 |
10 | }
11 | dependencies {
12 | classpath 'com.android.tools.build:gradle:3.6.2'
13 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
14 | classpath 'com.novoda:bintray-release:0.9.2'
15 | // NOTE: Do not place your application dependencies here; they belong
16 | // in the individual module build.gradle files
17 | }
18 | }
19 |
20 | allprojects {
21 | repositories {
22 | google()
23 | jcenter()
24 |
25 | }
26 | tasks.withType(Javadoc) {
27 | options {
28 | encoding "UTF-8"
29 | charSet 'UTF-8'
30 | links "http://docs.oracle.com/javase/7/docs/api"
31 | }
32 | options.addStringOption('Xdoclint:none', '-quiet')
33 | options.addStringOption('encoding', 'UTF-8')
34 | }
35 | }
36 |
37 | task clean(type: Delete) {
38 | delete rootProject.buildDir
39 | }
40 |
--------------------------------------------------------------------------------
/cactus-sample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/cactus-sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 | android {
5 | compileSdkVersion 29
6 | buildToolsVersion "29.0.3"
7 |
8 |
9 | defaultConfig {
10 | applicationId "com.gyf.cactus.sample"
11 | minSdkVersion 14
12 | targetSdkVersion 29
13 | versionCode 1
14 | versionName "$cactus_version"
15 |
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | }
18 |
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 |
26 | }
27 |
28 | dependencies {
29 | implementation fileTree(dir: 'libs', include: ['*.jar'])
30 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
31 | implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
32 | implementation 'androidx.appcompat:appcompat:1.2.0'
33 | implementation 'androidx.core:core-ktx:1.3.1'
34 | implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
35 | testImplementation 'junit:junit:4.12'
36 | androidTestImplementation 'androidx.test:runner:1.3.0'
37 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
38 | implementation "io.reactivex.rxjava2:rxkotlin:2.4.0"
39 | implementation "io.reactivex.rxjava2:rxandroid:2.1.1"
40 | implementation project(path: ':cactus')
41 | }
42 |
--------------------------------------------------------------------------------
/cactus-sample/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 |
--------------------------------------------------------------------------------
/cactus-sample/src/androidTest/java/com/gyf/cactus/sample/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.sample
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.gyf.cactus.simple", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/cactus-sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
15 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/cactus-sample/src/main/ic_launcher-web.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/ic_launcher-web.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/java/com/gyf/cactus/sample/App.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.sample
2 |
3 | import android.annotation.SuppressLint
4 | import android.app.Application
5 | import android.app.PendingIntent
6 | import android.content.Context
7 | import android.content.Intent
8 | import android.content.IntentFilter
9 | import android.util.Log
10 | import android.widget.Toast
11 | import androidx.lifecycle.MutableLiveData
12 | import com.gyf.cactus.Cactus
13 | import com.gyf.cactus.callback.CactusCallback
14 | import com.gyf.cactus.ext.cactus
15 | import io.reactivex.Observable
16 | import io.reactivex.android.schedulers.AndroidSchedulers
17 | import io.reactivex.disposables.Disposable
18 | import io.reactivex.schedulers.Schedulers
19 | import java.text.SimpleDateFormat
20 | import java.util.*
21 | import java.util.concurrent.TimeUnit
22 |
23 | /**
24 | * @author geyifeng
25 | * @date 2019-08-30 09:49
26 | */
27 | class App : Application(), CactusCallback {
28 |
29 | companion object {
30 | const val TAG = "cactus-sample"
31 |
32 | @SuppressLint("StaticFieldLeak")
33 | lateinit var context: Context
34 |
35 | /**
36 | * 结束时间
37 | */
38 | val mEndDate = MutableLiveData()
39 |
40 | /**
41 | * 上次存活时间
42 | */
43 | val mLastTimer = MutableLiveData()
44 |
45 | /**
46 | * 存活时间
47 | */
48 | val mTimer = MutableLiveData()
49 |
50 | /**
51 | * 运行状态
52 | */
53 | val mStatus = MutableLiveData().apply { value = true }
54 | }
55 |
56 | private var mDisposable: Disposable? = null
57 |
58 | override fun onCreate() {
59 | super.onCreate()
60 | context = applicationContext
61 | //可选,设置通知栏点击事件
62 | val pendingIntent =
63 | PendingIntent.getActivity(this, 0, Intent().apply {
64 | setClass(this@App, MainActivity::class.java)
65 | addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
66 | }, PendingIntent.FLAG_UPDATE_CURRENT)
67 | //可选,注册广播监听器
68 | registerReceiver(MainReceiver(), IntentFilter().apply {
69 | addAction(Cactus.CACTUS_WORK)
70 | addAction(Cactus.CACTUS_STOP)
71 | addAction(Cactus.CACTUS_BACKGROUND)
72 | addAction(Cactus.CACTUS_FOREGROUND)
73 | })
74 |
75 | cactus {
76 | //可选,设置通知栏点击事件
77 | setPendingIntent(pendingIntent)
78 | //可选,设置音乐
79 | setMusicId(R.raw.main)
80 | //可选,是否是debug模式
81 | isDebug(true)
82 | //可选,退到后台是否可以播放音乐
83 | setBackgroundMusicEnabled(true)
84 | //可选,设置奔溃可以重启,google原生rom android 10以下可以正常重启
85 | setCrashRestartUIEnabled(true)
86 | //可选,运行时回调
87 | addCallback(this@App)
88 | //可选,切后台切换回调
89 | addBackgroundCallback {
90 | Toast.makeText(this@App, if (it) "退到后台啦" else "跑到前台啦", Toast.LENGTH_SHORT).show()
91 | }
92 | }
93 | //或者这样设置前后台监听
94 | // registerActivityLifecycleCallbacks(AppBackgroundCallback {
95 | //
96 | // })
97 | }
98 |
99 | @SuppressLint("CheckResult")
100 | override fun doWork(times: Int) {
101 | Log.d(TAG, "doWork:$times")
102 | mStatus.postValue(true)
103 | val dateFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
104 | dateFormat.timeZone = TimeZone.getTimeZone("GMT+00:00")
105 | var oldTimer = Save.timer
106 | if (times == 1) {
107 | Save.lastTimer = oldTimer
108 | Save.endDate = Save.date
109 | oldTimer = 0L
110 | }
111 | mLastTimer.postValue(dateFormat.format(Date(Save.lastTimer * 1000)))
112 | mEndDate.postValue(Save.endDate)
113 | mDisposable = Observable.interval(1, TimeUnit.SECONDS)
114 | .map {
115 | oldTimer + it
116 | }
117 | .subscribeOn(Schedulers.io())
118 | .observeOn(AndroidSchedulers.mainThread())
119 | .subscribe { aLong ->
120 | Save.timer = aLong
121 | Save.date = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).run {
122 | format(Date())
123 | }
124 | mTimer.value = dateFormat.format(Date(aLong * 1000))
125 | }
126 | }
127 |
128 | override fun onStop() {
129 | Log.d(TAG, "onStop")
130 | mStatus.postValue(false)
131 | mDisposable?.apply {
132 | if (!isDisposed) {
133 | dispose()
134 | }
135 | }
136 | }
137 | }
--------------------------------------------------------------------------------
/cactus-sample/src/main/java/com/gyf/cactus/sample/AppManager.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.sample
2 |
3 | import android.app.Activity
4 | import android.os.Build
5 | import java.util.*
6 | import kotlin.system.exitProcess
7 |
8 | /**
9 | * Activity管理类
10 | *
11 | * @author geyifeng
12 | * @date 2018/7/17
13 | */
14 | class AppManager {
15 |
16 | companion object {
17 | val INSTANCE: AppManager = Holder.INSTANCE
18 | }
19 |
20 | private object Holder {
21 | val INSTANCE = AppManager()
22 | }
23 |
24 | private val stackActivity = Stack()
25 |
26 | /**
27 | * 增加Activity
28 | *
29 | * @param activity Activity
30 | */
31 | fun addActivity(activity: Activity) {
32 | stackActivity.add(activity)
33 | }
34 |
35 | /**
36 | * 移除Activity
37 | *
38 | * @param activity Activity
39 | */
40 | fun removeActivity(activity: Activity) {
41 | activity.finish()
42 | stackActivity.remove(activity)
43 | }
44 |
45 | /**
46 | * 删除所有Activity
47 | */
48 | fun removeAllActivity() {
49 | for (activity in stackActivity) {
50 | activity.finish()
51 | }
52 | stackActivity.clear()
53 | }
54 |
55 | /**
56 | * 获得最顶部的Activity
57 | *
58 | * @return Activity
59 | */
60 | fun getTopActivity(): Activity? = if (stackActivity.isNotEmpty()) {
61 | stackActivity[stackActivity.size - 1]
62 | } else {
63 | null
64 | }
65 |
66 | /**
67 | * 是否有某个Activity
68 | *
69 | * @param clazz Class
70 | * @return Boolean
71 | */
72 | fun hasActivity(clazz: Class): Boolean {
73 | stackActivity.forEach {
74 | if (it::class.java.name == clazz.name) {
75 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
76 | !(it.isDestroyed || it.isFinishing)
77 | } else {
78 | !it.isFinishing
79 | }
80 | }
81 | }
82 | return false
83 | }
84 |
85 | /**
86 | * 退出
87 | */
88 | fun exitApp() {
89 | removeAllActivity()
90 | android.os.Process.killProcess(android.os.Process.myPid())
91 | exitProcess(1)
92 | }
93 | }
--------------------------------------------------------------------------------
/cactus-sample/src/main/java/com/gyf/cactus/sample/BaseActivity.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.sample
2 |
3 | import android.os.Bundle
4 | import androidx.appcompat.app.AppCompatActivity
5 |
6 | /**
7 | * @author geyifeng
8 | * @date 2019-11-01 17:34
9 | */
10 | open class BaseActivity : AppCompatActivity() {
11 | override fun onCreate(savedInstanceState: Bundle?) {
12 | super.onCreate(savedInstanceState)
13 | AppManager.INSTANCE.addActivity(this)
14 | }
15 |
16 | override fun onDestroy() {
17 | super.onDestroy()
18 | AppManager.INSTANCE.removeActivity(this)
19 | }
20 | }
--------------------------------------------------------------------------------
/cactus-sample/src/main/java/com/gyf/cactus/sample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.sample
2 |
3 | import android.annotation.SuppressLint
4 | import android.os.Bundle
5 | import android.os.Handler
6 | import android.view.View
7 | import android.widget.Toast
8 | import androidx.lifecycle.Observer
9 | import com.gyf.cactus.ext.cactusRestart
10 | import com.gyf.cactus.ext.cactusUnregister
11 | import com.gyf.cactus.ext.cactusUpdateNotification
12 | import kotlinx.android.synthetic.main.activity_main.*
13 |
14 | /**
15 | * @author geyifeng
16 | * @date 2019-08-28 17:22
17 | */
18 | @Suppress("DIVISION_BY_ZERO")
19 | @SuppressLint("SetTextI18n")
20 | class MainActivity : BaseActivity() {
21 |
22 | private var times = 0L
23 |
24 | private val list = listOf(
25 | Pair("今日头条", "抖音全世界通用"),
26 | Pair("微博", "赵丽颖吐槽中餐厅"),
27 | Pair("绿洲", "今天又是美好的一天"),
28 | Pair("QQ", "好友申请"),
29 | Pair("微信", "在吗?"),
30 | Pair("百度地图", "新的路径规划"),
31 | Pair("墨迹天气", "明日大风,注意出行"),
32 | Pair("信息", "1条文本信息"),
33 | Pair("手机天猫", "你关注的宝贝降价啦")
34 | )
35 |
36 | companion object {
37 | private const val TIME = 4000L
38 | }
39 |
40 | override fun onCreate(savedInstanceState: Bundle?) {
41 | super.onCreate(savedInstanceState)
42 | setContentView(R.layout.activity_main)
43 | initData()
44 | setListener()
45 | }
46 |
47 | private fun initData() {
48 | tvVersion.text = "Version(版本):${BuildConfig.VERSION_NAME}"
49 | App.mEndDate.observe(this, Observer {
50 | tvLastDate.text = it
51 | })
52 | App.mLastTimer.observe(this, Observer {
53 | tvLastTimer.text = it
54 | })
55 | App.mTimer.observe(this, Observer {
56 | tvTimer.text = it
57 | })
58 | App.mStatus.observe(this, Observer {
59 | tvStatus.text = if (it) {
60 | "Operating status(运行状态):Running(运行中)"
61 | } else {
62 | "Operating status(运行状态):Stopped(已停止)"
63 | }
64 | })
65 | }
66 |
67 | private fun setListener() {
68 | //更新通知栏信息
69 | btnUpdate.onClick {
70 | val num = (0..8).random()
71 | cactusUpdateNotification {
72 | setTitle(list[num].first)
73 | setContent(list[num].second)
74 | }
75 | }
76 | //停止
77 | btnStop.onClick {
78 | cactusUnregister()
79 | }
80 | //重启
81 | btnRestart.onClick {
82 | cactusRestart()
83 | }
84 | //奔溃
85 | btnCrash.setOnClickListener {
86 | Toast.makeText(
87 | this,
88 | "The app will crash after three seconds(3s后奔溃)",
89 | Toast.LENGTH_SHORT
90 | ).show()
91 | Handler().postDelayed({
92 | 2 / 0
93 | }, 3000)
94 | }
95 | }
96 |
97 | private inline fun View.onClick(crossinline block: () -> Unit) {
98 | setOnClickListener {
99 | val nowTime = System.currentTimeMillis()
100 | val intervals = nowTime - times
101 | if (intervals > TIME) {
102 | times = nowTime
103 | block()
104 | } else {
105 | Toast.makeText(
106 | context,
107 | ((TIME.toFloat() - intervals) / 1000).toString() + "秒之后再点击",
108 | Toast.LENGTH_SHORT
109 | ).show()
110 | }
111 | }
112 | }
113 | }
--------------------------------------------------------------------------------
/cactus-sample/src/main/java/com/gyf/cactus/sample/MainReceiver.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.sample
2 |
3 | import android.content.BroadcastReceiver
4 | import android.content.Context
5 | import android.content.Intent
6 | import android.util.Log
7 | import com.gyf.cactus.Cactus
8 |
9 | /**
10 | * 测试Cactus广播接受
11 | * @author geyifeng
12 | * @date 2019-08-30 10:30
13 | */
14 | class MainReceiver : BroadcastReceiver() {
15 | override fun onReceive(context: Context, intent: Intent) {
16 | intent.action?.apply {
17 | when (this) {
18 | Cactus.CACTUS_WORK -> {
19 | Log.d(
20 | App.TAG,
21 | this + "--" + intent.getIntExtra(Cactus.CACTUS_TIMES, 0)
22 | )
23 | }
24 | Cactus.CACTUS_STOP -> {
25 | Log.d(App.TAG, this)
26 | }
27 | Cactus.CACTUS_BACKGROUND -> {
28 | Log.d(App.TAG, this)
29 | }
30 | Cactus.CACTUS_FOREGROUND -> {
31 | Log.d(App.TAG, this)
32 | }
33 | }
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/cactus-sample/src/main/java/com/gyf/cactus/sample/PrefExt.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.sample
2 |
3 | import kotlin.reflect.jvm.jvmName
4 |
5 |
6 | /**
7 | * SharedPreferences扩展函数
8 | * @author gyf
9 | * @date 2018/7/17
10 | */
11 | inline fun R.preference(defaultValue: T) =
12 | Preference(App.context, "", defaultValue, R::class.jvmName)
--------------------------------------------------------------------------------
/cactus-sample/src/main/java/com/gyf/cactus/sample/Preference.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.sample
2 |
3 | import android.content.Context
4 | import kotlin.properties.ReadWriteProperty
5 | import kotlin.reflect.KProperty
6 |
7 | class Preference(val context: Context, private val attrName: String, private val defaultValue: T, private val fileName: String = "fileName")
8 | : ReadWriteProperty {
9 |
10 | private val mPreferences by lazy {
11 | context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
12 | }
13 |
14 | override fun getValue(thisRef: Any?, property: KProperty<*>): T {
15 | return findPreference(findProperName(property))
16 | }
17 |
18 | override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
19 | putPreference(findProperName(property), value)
20 | }
21 |
22 | private fun findProperName(property: KProperty<*>) = if (attrName.isEmpty()) property.name else attrName
23 |
24 | @Suppress("IMPLICIT_CAST_TO_ANY", "UNCHECKED_CAST")
25 | private fun findPreference(key: String): T {
26 | return mPreferences.run {
27 | when (defaultValue) {
28 | is String -> getString(key, defaultValue)
29 | is Int -> getInt(key, defaultValue)
30 | is Long -> getLong(key, defaultValue)
31 | is Float -> getFloat(key, defaultValue)
32 | is Boolean -> getBoolean(key, defaultValue)
33 | else -> throw IllegalArgumentException("Unsupported type.")
34 | } as T
35 | }
36 | }
37 |
38 | private fun putPreference(key: String, value: T) {
39 | mPreferences.edit().apply {
40 | when (value) {
41 | is String -> putString(key, value)
42 | is Int -> putInt(key, value)
43 | is Long -> putLong(key, value)
44 | is Float -> putFloat(key, value)
45 | is Boolean -> putBoolean(key, value)
46 | else -> throw IllegalArgumentException("Unsupported type.")
47 | }
48 | }.apply()
49 | }
50 |
51 | }
--------------------------------------------------------------------------------
/cactus-sample/src/main/java/com/gyf/cactus/sample/Save.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.sample
2 |
3 | import android.annotation.SuppressLint
4 |
5 | /**
6 | * @author geyifeng
7 | * @date 2019-09-03 13:55
8 | */
9 | @SuppressLint("StaticFieldLeak")
10 | object Save {
11 | var timer by preference(0L)
12 | var lastTimer by preference(0L)
13 | var date by preference("0000-01-01 00:00:00")
14 | var endDate by preference("0000-01-01 00:00:00")
15 | }
--------------------------------------------------------------------------------
/cactus-sample/src/main/java/com/gyf/cactus/sample/TwoActivity.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.sample
2 |
3 | import android.os.Bundle
4 |
5 | class TwoActivity : BaseActivity() {
6 |
7 | override fun onCreate(savedInstanceState: Bundle?) {
8 | super.onCreate(savedInstanceState)
9 | setContentView(R.layout.activity_two)
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
23 |
24 |
31 |
32 |
42 |
43 |
50 |
51 |
61 |
62 |
69 |
70 |
80 |
81 |
86 |
87 |
96 |
97 |
106 |
107 |
114 |
115 |
122 |
123 |
130 |
131 |
138 |
139 |
140 |
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/layout/activity_two.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/layout/notification_view.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-hdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-hdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-mdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-mdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/raw/main.mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus-sample/src/main/res/raw/main.mp3
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #008577
5 | #008577
6 |
7 |
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/values/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFFFFF
4 |
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Cactus
3 | Crash(奔溃)
4 | Update Notification(更新通知栏)
5 | Stop(停止)
6 | Restart(重启)
7 |
8 |
--------------------------------------------------------------------------------
/cactus-sample/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/cactus-sample/src/test/java/com/gyf/cactus/sample/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.sample
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 |
--------------------------------------------------------------------------------
/cactus.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus.png
--------------------------------------------------------------------------------
/cactus/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/cactus/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'com.novoda.bintray-release'
4 |
5 | android {
6 | compileSdkVersion 29
7 | buildToolsVersion "29.0.3"
8 |
9 | defaultConfig {
10 | minSdkVersion 14
11 | targetSdkVersion 29
12 | }
13 |
14 |
15 | lintOptions {
16 | checkReleaseBuilds false
17 | // Or, if you prefer, you can continue to check for errors in release builds,
18 | // but continue the build even when errors are found:
19 | abortOnError false
20 | }
21 |
22 | }
23 |
24 | dependencies {
25 | implementation fileTree(dir: 'libs', include: ['*.jar'])
26 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
27 | implementation 'androidx.appcompat:appcompat:1.2.0'
28 | implementation 'androidx.work:work-runtime:2.4.0'
29 | implementation 'com.google.code.gson:gson:2.8.6'
30 | }
31 |
32 | publish {
33 | userOrg = 'geyifeng'
34 | groupId = 'com.gyf.cactus'
35 | artifactId = 'cactus'
36 | publishVersion = "$cactus_version"
37 | desc = 'Android Keep Alive'
38 | website = 'https://github.com/gyf-dev/Cactus'
39 | }
40 |
--------------------------------------------------------------------------------
/cactus/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus/consumer-rules.pro
--------------------------------------------------------------------------------
/cactus/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 |
--------------------------------------------------------------------------------
/cactus/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
16 |
17 |
20 |
21 |
25 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/cactus/src/main/aidl/com/gyf/cactus/entity/CactusConfig.aidl:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.entity;
2 |
3 | parcelable CactusConfig;
--------------------------------------------------------------------------------
/cactus/src/main/aidl/com/gyf/cactus/entity/ICactusInterface.aidl:
--------------------------------------------------------------------------------
1 | // ICactusInterface.aidl
2 | package com.gyf.cactus.entity;
3 |
4 | import com.gyf.cactus.entity.CactusConfig;
5 |
6 | interface ICactusInterface {
7 | void wakeup(in CactusConfig config);
8 | void connectionTimes(in int time);
9 | }
10 |
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/Cactus.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus
2 |
3 | import android.app.Notification
4 | import android.app.NotificationChannel
5 | import android.app.PendingIntent
6 | import android.content.Context
7 | import android.graphics.Bitmap
8 | import android.os.Build
9 | import android.widget.RemoteViews
10 | import com.gyf.cactus.callback.CactusBackgroundCallback
11 | import com.gyf.cactus.callback.CactusCallback
12 | import com.gyf.cactus.entity.CactusConfig
13 | import com.gyf.cactus.entity.Constant
14 | import com.gyf.cactus.entity.DefaultConfig
15 | import com.gyf.cactus.entity.NotificationConfig
16 | import com.gyf.cactus.ext.*
17 |
18 | /**
19 | * Cactus保活方案,Cactus有两种形式处理回调事件,
20 | * 第一种使用CactusCallback,
21 | * 第二种注册CACTUS_WORK和CACTUS_STOP广播监听器。
22 | *
23 | * @author geyifeng
24 | * @date 2019-08-28 17:22
25 | */
26 | class Cactus private constructor() {
27 |
28 | /**
29 | * 配置信息
30 | */
31 | private var mCactusConfig = CactusConfig()
32 |
33 | /**
34 | * 通知栏信息
35 | */
36 | private var mNotificationConfig = NotificationConfig()
37 |
38 | /**
39 | * 默认配置信息
40 | */
41 | private val mDefaultConfig = DefaultConfig()
42 |
43 | /**
44 | * 是否使用上一次保存的配置信息
45 | */
46 | private var mUsePreviousConfig = false
47 |
48 | companion object {
49 | /**
50 | * 运行时回调广播ACTION
51 | */
52 | @JvmField
53 | val CACTUS_WORK = "work".fieldById
54 |
55 | /**
56 | * 停止时回调广播ACTION
57 | */
58 | @JvmField
59 | val CACTUS_STOP = "stop".fieldById
60 |
61 | /**
62 | * 后台回调广播ACTION
63 | */
64 | @JvmField
65 | val CACTUS_BACKGROUND = "background".fieldById
66 |
67 | /**
68 | * 前台后调广播ACTION
69 | */
70 | @JvmField
71 | val CACTUS_FOREGROUND = "foreground".fieldById
72 |
73 | /**
74 | * key,通过广播形式获取启动次数
75 | */
76 | const val CACTUS_TIMES = "times"
77 |
78 | @JvmStatic
79 | val instance by lazy { Cactus() }
80 | }
81 |
82 | /**
83 | * 设置notification,非必传,如果不传,将使用用户根据其他api设置的信息构建Notification
84 | *
85 | * @param notification Notification
86 | * @return Cactus
87 | */
88 | fun setNotification(notification: Notification) = apply {
89 | mNotificationConfig.notification = notification
90 | }
91 |
92 | /**
93 | * 设置NotificationChannel,非必传,如果不传,将使用默认的NotificationChannel
94 | *
95 | * @param notificationChannel NotificationChannel?
96 | * @return Cactus
97 | */
98 | fun setNotificationChannel(notificationChannel: NotificationChannel?) = apply {
99 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
100 | mNotificationConfig.notificationChannel = notificationChannel
101 | }
102 | }
103 |
104 | /**
105 | * 是否隐藏通知栏,经测试,除了android 7.1手机之外都可以隐藏,默认隐藏,非必传
106 | *
107 | * @param hide Boolean
108 | * @return Cactus
109 | */
110 | fun hideNotification(hide: Boolean) = apply {
111 | mNotificationConfig.hideNotification = hide
112 | }
113 |
114 | /**
115 | * 是否隐藏Android 8.0以上通知栏
116 | *
117 | * @param hide Boolean
118 | * @return Cactus
119 | */
120 | fun hideNotificationAfterO(hide: Boolean) = apply {
121 | mNotificationConfig.hideNotificationAfterO = hide
122 | }
123 |
124 | /**
125 | * 设置PendingIntent,用来处理通知栏点击事件,非必传
126 | *
127 | * @param pendingIntent PendingIntent
128 | * @return Cactus
129 | */
130 | fun setPendingIntent(pendingIntent: PendingIntent) = apply {
131 | mNotificationConfig.pendingIntent = pendingIntent
132 | }
133 |
134 | /**
135 | * 服务Id,默认是1到Int.MAX_VALUE随机数,非必传
136 | *
137 | * @param serviceId Int
138 | * @return Cactus
139 | */
140 | fun setServiceId(serviceId: Int) = apply {
141 | mNotificationConfig.serviceId = serviceId
142 | }
143 |
144 | /**
145 | * 渠道Id,默认是Cactus,建议用户修改,非必传
146 | *
147 | * @param channelId String
148 | * @return Cactus
149 | */
150 | fun setChannelId(channelId: String) = apply {
151 | mNotificationConfig.channelId = channelId
152 | }
153 |
154 | /**
155 | * 渠道名,用于设置里通知渠道展示,默认是Cactus,建议用户修改,非必传
156 | *
157 | * @param channelName String
158 | * @return Cactus
159 | */
160 | fun setChannelName(channelName: String) = apply {
161 | mNotificationConfig.channelName = channelName
162 | }
163 |
164 | /**
165 | * 通知栏标题,默认是Cactus,建议用户修改,非必传
166 | *
167 | * @param title String
168 | * @return Cactus
169 | */
170 | fun setTitle(title: String) = apply {
171 | mNotificationConfig.title = title
172 | }
173 |
174 | /**
175 | * 通知栏内容,默认是Cactus is running,建议用户修改,非必传
176 | *
177 | * @param content String
178 | * @return Cactus
179 | */
180 | fun setContent(content: String) = apply {
181 | mNotificationConfig.content = content
182 | }
183 |
184 | /**
185 | * 设置RemoteViews(自定义布局),非必传
186 | *
187 | * @param remoteViews RemoteViews
188 | * @return Cactus
189 | */
190 | fun setRemoteViews(remoteViews: RemoteViews) = apply {
191 | mNotificationConfig.hideNotification = false
192 | mNotificationConfig.remoteViews = remoteViews
193 | }
194 |
195 | /**
196 | * 设置BigRemoteViews(自定义布局),非必传
197 | *
198 | * @param bigRemoteViews RemoteViews
199 | * @return Cactus
200 | */
201 | fun setBigRemoteViews(bigRemoteViews: RemoteViews) = apply {
202 | mNotificationConfig.hideNotification = false
203 | mNotificationConfig.bigRemoteViews = bigRemoteViews
204 | }
205 |
206 | /**
207 | * 通知栏小图标,默认是库里的图标,建议用户修改,非必传
208 | *
209 | * @param smallIcon Int
210 | * @return Cactus
211 | */
212 | fun setSmallIcon(smallIcon: Int) = apply {
213 | mNotificationConfig.smallIcon = smallIcon
214 | }
215 |
216 | /**
217 | * 通知栏大图标,默认是库里的图标,建议用户修改,非必传
218 | *
219 | * @param largeIcon Int
220 | * @return Cactus
221 | */
222 | fun setLargeIcon(largeIcon: Int) = apply {
223 | mNotificationConfig.largeIcon = largeIcon
224 | }
225 |
226 | /**
227 | * 通知栏大图标,非必传
228 | *
229 | * @param largeIcon Bitmap
230 | * @return Cactus
231 | */
232 | fun setLargeIcon(largeIcon: Bitmap) = apply {
233 | mNotificationConfig.largeIconBitmap = largeIcon
234 | }
235 |
236 |
237 | /**
238 | * 是否可以播放音乐,默认可以播放音乐,非必传
239 | *
240 | * @param enabled Boolean
241 | * @return Cactus
242 | */
243 | fun setMusicEnabled(enabled: Boolean) = apply {
244 | mDefaultConfig.musicEnabled = enabled
245 | }
246 |
247 | /**
248 | * 后台是否可以播放音乐,默认不可以后台播放音乐,非必传
249 | *
250 | * @param enabled Boolean
251 | * @return Cactus
252 | */
253 | fun setBackgroundMusicEnabled(enabled: Boolean) = apply {
254 | mDefaultConfig.backgroundMusicEnabled = enabled
255 | }
256 |
257 | /**
258 | * 设置自定义音乐,默认是无声音乐,非必传
259 | *
260 | * @param musicId Int
261 | * @return Cactus
262 | */
263 | fun setMusicId(musicId: Int) = apply {
264 | mDefaultConfig.musicId = musicId
265 | }
266 |
267 | /**
268 | * 设置音乐间隔时间,时间间隔越长,越省电,默认间隔时间是0,非必传
269 | *
270 | * @param repeatInterval Long
271 | * @return Cactus
272 | */
273 | fun setMusicInterval(repeatInterval: Long) = apply {
274 | if (repeatInterval >= 0L) {
275 | mDefaultConfig.repeatInterval = repeatInterval
276 | }
277 | }
278 |
279 | /**
280 | * 是否可以使用一像素,默认可以使用,只有在android p以下可以使用,非必传
281 | *
282 | * @param enabled Boolean
283 | * @return Cactus
284 | */
285 | fun setOnePixEnabled(enabled: Boolean) = apply {
286 | mDefaultConfig.onePixEnabled = enabled
287 | }
288 |
289 | /**
290 | * 是否可以使用WorkManager,默认可以使用,非必传
291 | *
292 | * @param enabled Boolean
293 | * @return WaterBear
294 | */
295 | fun setWorkerEnabled(enabled: Boolean) = apply {
296 | mDefaultConfig.workerEnabled = enabled
297 | }
298 |
299 | /**
300 | * 奔溃是否可以重启用户界面,默认为false,google原生rom android 10 以下可以正常重启,非必传
301 | *
302 | * @param enabled Boolean
303 | * @return WaterBear
304 | */
305 | fun setCrashRestartUIEnabled(enabled: Boolean) = apply {
306 | mDefaultConfig.crashRestartEnabled = enabled
307 | }
308 |
309 | /**
310 | * 设置回调工作在主线程,默认在Binder线程
311 | *
312 | * @param enabled Boolean
313 | * @return Cactus
314 | */
315 | fun setWorkOnMainThread(enabled: Boolean) = apply {
316 | mDefaultConfig.workOnMainThread = enabled
317 | }
318 |
319 | /**
320 | * 是否使用上一次保存的配置信息
321 | *
322 | * @param usePreviousConfig Boolean
323 | * @return Cactus
324 | */
325 | fun usePreviousConfig(usePreviousConfig: Boolean) = apply {
326 | mUsePreviousConfig = usePreviousConfig
327 | }
328 |
329 | /**
330 | * 是否Debug模式,默认没有调试信息,非必传
331 | *
332 | * @param isDebug Boolean
333 | * @return Cactus
334 | */
335 | fun isDebug(isDebug: Boolean) = apply {
336 | mDefaultConfig.debug = isDebug
337 | }
338 |
339 | /**
340 | * 增加回调,用于处理一些额外的工作,非必传
341 | *
342 | * @param cactusCallback CactusCallback
343 | * @return Cactus
344 | */
345 | fun addCallback(cactusCallback: CactusCallback) = apply {
346 | Constant.CALLBACKS.add(cactusCallback)
347 | }
348 |
349 | /**
350 | * 增加回调,lambda形式,用于处理一些额外的工作,非必传
351 | *
352 | * @param stop Function0
353 | * @param work Function1
354 | * @return Cactus
355 | */
356 | fun addCallback(stop: (() -> Unit)? = null, work: (Int) -> Unit) = apply {
357 | Constant.CALLBACKS.add(object : CactusCallback {
358 | override fun doWork(times: Int) {
359 | work(times)
360 | }
361 |
362 | override fun onStop() {
363 | stop?.let {
364 | it()
365 | }
366 | }
367 | })
368 | }
369 |
370 | /**
371 | * 前后台切换回调,用于处理app前后台切换,非必传
372 | *
373 | * @param cactusBackgroundCallback CactusBackgroundCallback
374 | * @return Cactus
375 | */
376 | fun addBackgroundCallback(cactusBackgroundCallback: CactusBackgroundCallback) = apply {
377 | Constant.BACKGROUND_CALLBACKS.add(cactusBackgroundCallback)
378 | }
379 |
380 | /**
381 | * 前后台切换回调,用于处理app前后台切换,非必传
382 | *
383 | * @param block Function1
384 | * @return Cactus
385 | */
386 | fun addBackgroundCallback(block: (Boolean) -> Unit) = apply {
387 | Constant.BACKGROUND_CALLBACKS.add(object : CactusBackgroundCallback {
388 | override fun onBackground(background: Boolean) {
389 | block(background)
390 | }
391 | })
392 | }
393 |
394 | /**
395 | * 必须调用,建议在Application里初始化,使用Kotlin扩展函数不需要调用此方法
396 | *
397 | * @param context Context
398 | */
399 | fun register(context: Context) {
400 | val cactusConfig = CactusConfig(
401 | mNotificationConfig,
402 | mDefaultConfig
403 | )
404 | mCactusConfig = if (mUsePreviousConfig) {
405 | context.getPreviousConfig() ?: cactusConfig
406 | } else cactusConfig
407 | context.register(mCactusConfig)
408 | }
409 |
410 | /**
411 | * 注销,并不会立马停止,而是在1s之后停止,非必须调用,比如可以在app完全退出的时候可以调用,根据你的需求调用
412 | *
413 | * @param context Context
414 | */
415 | fun unregister(context: Context) = context.unregister()
416 |
417 | /**
418 | * 重启,与register区别在于不会重新配置CactusConfig信息,而是使用上一次配置的信息
419 | *
420 | * @param context Context
421 | */
422 | fun restart(context: Context) = context.restart()
423 |
424 | /**
425 | * 更新通知栏
426 | *
427 | * @param context Context
428 | */
429 | fun updateNotification(context: Context) {
430 | mCactusConfig.notificationConfig = mNotificationConfig
431 | context.updateNotification(mCactusConfig)
432 | }
433 |
434 | /**
435 | * 是否在运行
436 | */
437 | fun isRunning(context: Context) = context.isCactusRunning
438 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/callback/AppBackgroundCallback.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.callback
2 |
3 | import android.app.Activity
4 | import android.app.Application
5 | import android.content.Context
6 | import android.content.Intent
7 | import android.os.Bundle
8 | import android.os.Handler
9 | import com.gyf.cactus.Cactus
10 | import com.gyf.cactus.ext.sMainHandler
11 | import com.gyf.cactus.pix.OnePixActivity
12 | import java.lang.ref.WeakReference
13 |
14 | /**
15 | *
16 | * 处理前后台切换
17 | *
18 | * @author geyifeng
19 | * @date 2019-11-01 10:36
20 | */
21 | class AppBackgroundCallback @JvmOverloads constructor(
22 | private var context: Context? = null,
23 | private var block: ((Boolean) -> Unit)? = null
24 | ) :
25 | Application.ActivityLifecycleCallbacks {
26 |
27 | private var mContext: WeakReference? = null
28 |
29 | /**
30 | * 前台Activity数量
31 | */
32 | private var mFrontActivityCount = 0
33 | /**
34 | * 当Activity数量大于0的时候,标识是否已经发出前后台广播
35 | */
36 | private var mIsSend = false
37 | /**
38 | * 是否是第一次发送前后台广播
39 | */
40 | private var mIsFirst = true
41 | /**
42 | * 是否使用监听回调
43 | */
44 | private var mUseCallback = true
45 |
46 | companion object {
47 | private const val FIRST_TIME = 1000L
48 | }
49 |
50 | init {
51 | sMainHandler.postDelayed({
52 | if (mFrontActivityCount == 0) {
53 | post()
54 | }
55 | }, FIRST_TIME)
56 | }
57 |
58 | override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
59 | if (activity !is OnePixActivity) {
60 | mContext = WeakReference(activity)
61 | }
62 | }
63 |
64 | override fun onActivityStarted(activity: Activity) {
65 | if (activity !is OnePixActivity) {
66 | mFrontActivityCount++
67 | post()
68 | }
69 | }
70 |
71 | override fun onActivityResumed(activity: Activity) {
72 | }
73 |
74 | override fun onActivityPaused(activity: Activity) {
75 | }
76 |
77 | override fun onActivityStopped(activity: Activity) {
78 | if (activity !is OnePixActivity) {
79 | mFrontActivityCount--
80 | post()
81 | }
82 | }
83 |
84 | override fun onActivityDestroyed(activity: Activity) {
85 | }
86 |
87 | override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
88 | }
89 |
90 | internal fun useCallback(useCallback: Boolean) {
91 | mUseCallback = useCallback
92 | }
93 |
94 | /**
95 | * 处理广播
96 | */
97 | private fun post() {
98 | (mContext?.get() ?: context)?.apply {
99 | if (mUseCallback) {
100 | if (mFrontActivityCount == 0) {
101 | mIsSend = false
102 | sMainHandler.postDelayed {
103 | sendBroadcast(Intent().setAction(Cactus.CACTUS_BACKGROUND))
104 | block?.let { it(true) }
105 | }
106 | } else {
107 | if (!mIsSend) {
108 | mIsSend = true
109 | sMainHandler.postDelayed {
110 | sendBroadcast(Intent().setAction(Cactus.CACTUS_FOREGROUND))
111 | block?.let { it(false) }
112 | }
113 | }
114 | }
115 | }
116 | }
117 | }
118 |
119 | private inline fun Handler.postDelayed(crossinline block: () -> Unit) {
120 | if (mIsFirst) {
121 | postDelayed(
122 | {
123 | block()
124 | mIsFirst = false
125 | },
126 | FIRST_TIME
127 | )
128 | } else {
129 | block()
130 | }
131 | }
132 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/callback/CactusBackgroundCallback.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.callback
2 |
3 | /**
4 | * 前后台切换回调
5 | *
6 | * @author geyifeng
7 | * @date 2019-11-01 12:01
8 | */
9 | interface CactusBackgroundCallback {
10 | /**
11 | * 前后台切换回调
12 | * @param background Boolean
13 | */
14 | fun onBackground(background: Boolean)
15 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/callback/CactusCallback.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.callback
2 |
3 | /**
4 | * 监听回调
5 | *
6 | * @author geyifeng
7 | * @date 2019-08-28 17:58
8 | */
9 | interface CactusCallback {
10 |
11 | /**
12 | * do something
13 | * @param times Int 连接次数
14 | */
15 | fun doWork(times: Int)
16 |
17 | /**
18 | * 停止时调用
19 | */
20 | fun onStop()
21 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/entity/CactusConfig.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.entity
2 |
3 | import android.os.Parcel
4 | import android.os.Parcelable
5 |
6 | /**
7 | * 用户配置的信息
8 | *
9 | * @author geyifeng
10 | * @date 2019-08-29 17:46
11 | */
12 | data class CactusConfig(
13 | /**
14 | * 通知栏信息
15 | */
16 | var notificationConfig: NotificationConfig = NotificationConfig(),
17 | /**
18 | * 默认配置信息
19 | */
20 | val defaultConfig: DefaultConfig = DefaultConfig()
21 | ) : Parcelable {
22 | constructor(source: Parcel) : this(
23 | source.readParcelable(NotificationConfig::class.java.classLoader)!!,
24 | source.readParcelable(DefaultConfig::class.java.classLoader)!!
25 | )
26 |
27 | override fun describeContents() = 0
28 |
29 | override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
30 | writeParcelable(notificationConfig, 0)
31 | writeParcelable(defaultConfig, 0)
32 | }
33 |
34 | companion object {
35 | @JvmField
36 | val CREATOR: Parcelable.Creator = object : Parcelable.Creator {
37 | override fun createFromParcel(source: Parcel): CactusConfig =
38 | CactusConfig(source)
39 |
40 | override fun newArray(size: Int): Array = arrayOfNulls(size)
41 | }
42 | }
43 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/entity/Constant.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.entity
2 |
3 | import com.gyf.cactus.callback.CactusBackgroundCallback
4 | import com.gyf.cactus.callback.CactusCallback
5 |
6 | /**
7 | * @author geyifeng
8 | * @date 2019-12-17 00:12
9 | */
10 | internal object Constant {
11 | /**
12 | * 包名
13 | */
14 | internal const val CACTUS_PACKAGE = "com.gyf.cactus"
15 | /**
16 | * 停止标识符
17 | */
18 | internal const val CACTUS_FLAG_STOP = "$CACTUS_PACKAGE.flag.stop"
19 | /**
20 | * tag
21 | */
22 | internal const val CACTUS_TAG = "cactus"
23 | /**
24 | * 配置信息
25 | */
26 | internal const val CACTUS_CONFIG = "cactusConfig"
27 | /**
28 | * 通知栏配置信息
29 | */
30 | internal const val CACTUS_NOTIFICATION_CONFIG = "notificationConfig"
31 | /**
32 | * 服务ID key
33 | */
34 | internal const val CACTUS_SERVICE_ID = "serviceId"
35 | /**
36 | * JobID key
37 | */
38 | internal const val CACTUS_JOB_ID = "jobId"
39 | /**
40 | * 进程名字
41 | */
42 | internal const val CACTUS_EMOTE_SERVICE = "cactusRemoteService"
43 | /**
44 | * 回调集合
45 | */
46 | internal val CALLBACKS = arrayListOf()
47 | /**
48 | * 前后台回调集合
49 | */
50 | internal val BACKGROUND_CALLBACKS = arrayListOf()
51 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/entity/DefaultConfig.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.entity
2 |
3 | import android.content.Intent
4 | import android.os.Parcel
5 | import android.os.Parcelable
6 | import com.gyf.cactus.R
7 |
8 | /**
9 | * 默认配置信息
10 | *
11 | * @author geyifeng
12 | * @date 2019-09-02 09:44
13 | */
14 | data class DefaultConfig(
15 | /**
16 | * 是否debug
17 | */
18 | var debug: Boolean = false,
19 | /**
20 | * 是否可以使用后台音乐
21 | */
22 | var musicEnabled: Boolean = true,
23 | /**
24 | * app退出到后台是否可以播放音乐
25 | */
26 | var backgroundMusicEnabled: Boolean = false,
27 | /**
28 | * 音乐播放循环间隔
29 | */
30 | var repeatInterval: Long = 0L,
31 | /**
32 | * 音乐播放声源
33 | */
34 | var musicId: Int = R.raw.cactus,
35 | /**
36 | * 是否可以使用一像素
37 | */
38 | var onePixEnabled: Boolean = true,
39 | /**
40 | * 是否可以使用WorkManager
41 | */
42 | var workerEnabled: Boolean = true,
43 | /**
44 | * 奔溃是否可以重启
45 | */
46 | var crashRestartEnabled: Boolean = false,
47 | /**
48 | * 工作在主线程
49 | */
50 | var workOnMainThread: Boolean = false,
51 | /**
52 | * 重启Intent
53 | */
54 | var restartIntent: Intent? = null
55 | ) : Parcelable {
56 | constructor(source: Parcel) : this(
57 | 1 == source.readInt(),
58 | 1 == source.readInt(),
59 | 1 == source.readInt(),
60 | source.readLong(),
61 | source.readInt(),
62 | 1 == source.readInt(),
63 | 1 == source.readInt(),
64 | 1 == source.readInt(),
65 | 1 == source.readInt(),
66 | source.readParcelable(Intent::class.java.classLoader)
67 | )
68 |
69 | override fun describeContents() = 0
70 |
71 | override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
72 | writeInt((if (debug) 1 else 0))
73 | writeInt((if (musicEnabled) 1 else 0))
74 | writeInt((if (backgroundMusicEnabled) 1 else 0))
75 | writeLong(repeatInterval)
76 | writeInt(musicId)
77 | writeInt((if (onePixEnabled) 1 else 0))
78 | writeInt((if (workerEnabled) 1 else 0))
79 | writeInt((if (crashRestartEnabled) 1 else 0))
80 | writeInt((if (workOnMainThread) 1 else 0))
81 | writeParcelable(restartIntent, 0)
82 | }
83 |
84 | companion object {
85 | @JvmField
86 | val CREATOR: Parcelable.Creator =
87 | object : Parcelable.Creator {
88 | override fun createFromParcel(source: Parcel): DefaultConfig = DefaultConfig(source)
89 | override fun newArray(size: Int): Array = arrayOfNulls(size)
90 | }
91 | }
92 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/entity/NotificationConfig.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.entity
2 |
3 | import android.app.Notification
4 | import android.app.PendingIntent
5 | import android.graphics.Bitmap
6 | import android.os.Parcel
7 | import android.os.Parcelable
8 | import android.widget.RemoteViews
9 | import com.gyf.cactus.R
10 |
11 | /**
12 | * 通知栏信息
13 | *
14 | * @author geyifeng
15 | * @date 2019-08-28 17:10
16 | */
17 | data class NotificationConfig(
18 | /**
19 | * 服务id
20 | */
21 | var serviceId: Int = (1..Int.MAX_VALUE).random(),
22 | /**
23 | * 渠道id
24 | */
25 | var channelId: String = "Cactus",
26 | /**
27 | * 渠道名
28 | */
29 | var channelName: String = "Cactus",
30 | /**
31 | * 标题名
32 | */
33 | var title: String = "Cactus",
34 | /**
35 | * 通知栏内容
36 | */
37 | var content: String = "Cactus is running",
38 | /**
39 | * 小图标
40 | */
41 | var smallIcon: Int = R.drawable.icon_cactus_small,
42 | /**
43 | * 大图标
44 | */
45 | var largeIcon: Int = 0,
46 | /**
47 | * 大图标
48 | */
49 | var largeIconBitmap: Bitmap? = null,
50 | /**
51 | * 是否隐藏 Android O以上通知栏
52 | */
53 | var hideNotificationAfterO: Boolean = false,
54 | /**
55 | * 是否隐藏通知栏,对于 Android O以下有效
56 | */
57 | var hideNotification: Boolean = false,
58 | /**
59 | * 自定义布局
60 | */
61 | var remoteViews: RemoteViews? = null,
62 | /**
63 | * 自定义大布局
64 | */
65 | var bigRemoteViews: RemoteViews? = null,
66 | /**
67 | * 点击标题栏跳转事件
68 | */
69 | @Transient
70 | var pendingIntent: PendingIntent? = null,
71 | /**
72 | * 用户传入的Notification,使用该属性,以上配置就不会生效
73 | */
74 | @Transient
75 | var notification: Notification? = null,
76 | /**
77 | * 用户传入的NotificationChannel
78 | */
79 | @Transient
80 | var notificationChannel: Parcelable? = null
81 | ) : Parcelable {
82 |
83 | /**
84 | * 是否可以更新
85 | *
86 | * @param notificationConfig NotificationConfig
87 | */
88 | fun canUpdate(notificationConfig: NotificationConfig): Boolean {
89 | val can = serviceId == notificationConfig.serviceId &&
90 | channelId == notificationConfig.channelId &&
91 | channelName == notificationConfig.channelName &&
92 | hideNotification == notificationConfig.hideNotification &&
93 | hideNotificationAfterO == notificationConfig.hideNotificationAfterO &&
94 | !hideNotification && !hideNotificationAfterO
95 | return if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
96 | can && notificationChannel == notificationConfig.notificationChannel &&
97 | notification?.channelId == notificationConfig.notification?.channelId
98 | } else can
99 | }
100 |
101 | constructor(source: Parcel) : this(
102 | source.readInt(),
103 | source.readString() ?: "Cactus",
104 | source.readString() ?: "Cactus",
105 | source.readString() ?: "Cactus",
106 | source.readString() ?: "The app of cactus is running",
107 | source.readInt(),
108 | source.readInt(),
109 | source.readParcelable(Bitmap::class.java.classLoader),
110 | 1 == source.readInt(),
111 | 1 == source.readInt(),
112 | source.readParcelable(RemoteViews::class.java.classLoader),
113 | source.readParcelable(RemoteViews::class.java.classLoader),
114 | source.readParcelable(PendingIntent::class.java.classLoader),
115 | source.readParcelable(Notification::class.java.classLoader),
116 | source.readParcelable(Parcelable::class.java.classLoader)
117 | )
118 |
119 | override fun describeContents() = 0
120 |
121 | override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
122 | writeInt(serviceId)
123 | writeString(channelId)
124 | writeString(channelName)
125 | writeString(title)
126 | writeString(content)
127 | writeInt(smallIcon)
128 | writeInt(largeIcon)
129 | writeParcelable(largeIconBitmap, 0)
130 | writeInt((if (hideNotificationAfterO) 1 else 0))
131 | writeInt((if (hideNotification) 1 else 0))
132 | writeParcelable(remoteViews, 0)
133 | writeParcelable(bigRemoteViews, 0)
134 | writeParcelable(pendingIntent, 0)
135 | writeParcelable(notification, 0)
136 | writeParcelable(notificationChannel, 0)
137 | }
138 |
139 | companion object {
140 | @JvmField
141 | val CREATOR: Parcelable.Creator =
142 | object : Parcelable.Creator {
143 | override fun createFromParcel(source: Parcel): NotificationConfig =
144 | NotificationConfig(source)
145 |
146 | override fun newArray(size: Int): Array = arrayOfNulls(size)
147 | }
148 | }
149 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/exception/CactusException.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.exception
2 |
3 | /**
4 | * 异常处理
5 | *
6 | * @author geyifeng
7 | * @date 2019-11-08 11:51
8 | */
9 | class CactusException internal constructor(msg: String) : Exception(msg)
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/exception/CactusUncaughtExceptionHandler.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.exception
2 |
3 | import android.os.Process
4 | import kotlin.system.exitProcess
5 |
6 | /**
7 | * 默认的全局捕获
8 | *
9 | * @author geyifeng
10 | * @date 2019-12-12 14:57
11 | */
12 | internal class CactusUncaughtExceptionHandler private constructor() :
13 | Thread.UncaughtExceptionHandler {
14 |
15 | companion object {
16 | @JvmStatic
17 | val instance by lazy {
18 | CactusUncaughtExceptionHandler()
19 | }
20 | }
21 |
22 | private val mDefault = Thread.getDefaultUncaughtExceptionHandler()
23 |
24 | init {
25 | Thread.setDefaultUncaughtExceptionHandler(this)
26 | }
27 |
28 | override fun uncaughtException(t: Thread, e: Throwable) {
29 | val message = e.message
30 | if (message != null && (message.contains(
31 | "Bad notification for startForeground: " +
32 | "java.lang.RuntimeException: invalid channel for service notification"
33 | ) || message.contains("Context.startForegroundService() did not then call Service.startForeground()"))
34 | ) {
35 | Process.killProcess(Process.myPid())
36 | exitProcess(10)
37 | } else {
38 | mDefault?.uncaughtException(t, e)
39 | }
40 | }
41 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/ext/CactusExt.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.ext
2 |
3 | import android.app.Activity
4 | import android.app.Application
5 | import android.app.PendingIntent
6 | import android.app.Service
7 | import android.content.Context
8 | import android.content.Intent
9 | import android.content.ServiceConnection
10 | import android.os.*
11 | import android.util.Log
12 | import androidx.core.app.NotificationManagerCompat
13 | import androidx.work.ExistingPeriodicWorkPolicy
14 | import androidx.work.PeriodicWorkRequest
15 | import androidx.work.WorkManager
16 | import com.gyf.cactus.Cactus
17 | import com.gyf.cactus.callback.AppBackgroundCallback
18 | import com.gyf.cactus.entity.CactusConfig
19 | import com.gyf.cactus.entity.Constant
20 | import com.gyf.cactus.exception.CactusUncaughtExceptionHandler
21 | import com.gyf.cactus.pix.OnePixActivity
22 | import com.gyf.cactus.receiver.StopReceiver
23 | import com.gyf.cactus.service.CactusJobService
24 | import com.gyf.cactus.service.LocalService
25 | import com.gyf.cactus.service.RemoteService
26 | import com.gyf.cactus.workmanager.CactusWorker
27 | import java.lang.ref.WeakReference
28 | import java.util.concurrent.TimeUnit
29 |
30 | /**
31 | * Cactus扩展
32 | *
33 | * @author geyifeng
34 | * @date 2019-08-28 18:23
35 | */
36 |
37 | /**
38 | * 用以保存一像素Activity
39 | */
40 | private var mWeakReference: WeakReference? = null
41 |
42 | /**
43 | * 用来表示是前台还是后台
44 | */
45 | private var mIsForeground = false
46 |
47 | /**
48 | * 是否注册过
49 | */
50 | private var sRegistered = false
51 |
52 | /**
53 | * 主Handler
54 | */
55 | internal val sMainHandler by lazy {
56 | Handler(Looper.getMainLooper())
57 | }
58 |
59 | /**
60 | * 启动次数
61 | */
62 | internal var sTimes = 0
63 |
64 | /**
65 | * 启动次数,用以判断是否使用奔溃重启
66 | */
67 | internal var sStartTimes = 0
68 |
69 | /**
70 | * 配置信息
71 | */
72 | internal var sCactusConfig: CactusConfig? = null
73 |
74 | /**
75 | * 前后台切换监听
76 | */
77 | private var mAppBackgroundCallback: AppBackgroundCallback? = null
78 |
79 | /**
80 | * kotlin里使用Cactus
81 | *
82 | * @receiver Context
83 | * @param block [@kotlin.ExtensionFunctionType] Function1
84 | */
85 | fun Context.cactus(block: Cactus.() -> Unit) =
86 | Cactus.instance.apply { block() }.register(this)
87 |
88 | /**
89 | * 注销
90 | *
91 | * @receiver Context
92 | */
93 | fun Context.cactusUnregister() = Cactus.instance.unregister(this)
94 |
95 | /**
96 | * 重启
97 | *
98 | * @receiver Context
99 | */
100 | fun Context.cactusRestart() = Cactus.instance.restart(this)
101 |
102 | /**
103 | * 更新通知栏
104 | *
105 | * @receiver Context
106 | * @param block [@kotlin.ExtensionFunctionType] Function1
107 | */
108 | fun Context.cactusUpdateNotification(block: Cactus.() -> Unit) =
109 | Cactus.instance.apply { block() }.updateNotification(this)
110 |
111 | /**
112 | * 是否已经停止
113 | *
114 | * @receiver Context
115 | * @return Boolean
116 | */
117 | val Context.cactusIsRunning
118 | get() = Cactus.instance.isRunning(this)
119 |
120 | /**
121 | * kotlin里使用注册Receiver
122 | *
123 | * @receiver Context
124 | * @param block Function0
125 | */
126 | internal fun Context.registerStopReceiver(block: () -> Unit) =
127 | StopReceiver.newInstance(this).register(block)
128 |
129 | /**
130 | * 注册Cactus服务
131 | *
132 | * @receiver Context
133 | * @param cactusConfig CactusConfig
134 | */
135 | internal fun Context.register(cactusConfig: CactusConfig) {
136 | if (isMain) {
137 | try {
138 | if (sRegistered && isCactusRunning) {
139 | log("Cactus is running,Please stop Cactus before registering!!")
140 | } else {
141 | sStartTimes++
142 | sRegistered = true
143 | handleRestartIntent(cactusConfig)
144 | saveConfig(cactusConfig)
145 | CactusUncaughtExceptionHandler.instance
146 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
147 | registerJobCactus(cactusConfig)
148 | } else {
149 | registerCactus(cactusConfig)
150 | }
151 | if (this is Application && mAppBackgroundCallback == null) {
152 | mAppBackgroundCallback = AppBackgroundCallback(this)
153 | registerActivityLifecycleCallbacks(mAppBackgroundCallback)
154 | }
155 | mAppBackgroundCallback?.useCallback(true)
156 | }
157 | } catch (e: Exception) {
158 | log("Unable to open cactus service!!")
159 | }
160 | }
161 | }
162 |
163 | /**
164 | * 注销Cactus
165 | *
166 | * @receiver Context
167 | */
168 | internal fun Context.unregister() {
169 | try {
170 | if (isCactusRunning && sRegistered) {
171 | sRegistered = false
172 | sCactusConfig?.apply {
173 | if (defaultConfig.workerEnabled) {
174 | unregisterWorker()
175 | }
176 | }
177 | sendBroadcast(Intent("${Constant.CACTUS_FLAG_STOP}.$packageName"))
178 | sMainHandler.postDelayed({
179 | mAppBackgroundCallback?.also {
180 | it.useCallback(false)
181 | if (this is Application) {
182 | unregisterActivityLifecycleCallbacks(it)
183 | mAppBackgroundCallback = null
184 | }
185 | }
186 | }, 1000)
187 | } else {
188 | log("Cactus is not running,Please make sure Cactus is running!!")
189 | }
190 | } catch (e: Exception) {
191 | }
192 | }
193 |
194 | /**
195 | * 重新启动
196 | *
197 | * @receiver Context
198 | */
199 | internal fun Context.restart() = register(getConfig())
200 |
201 | /**
202 | * 更新通知栏
203 | *
204 | * @receiver Context
205 | * @param cactusConfig CactusConfig
206 | */
207 | internal fun Context.updateNotification(cactusConfig: CactusConfig) {
208 | if (!getConfig().notificationConfig.canUpdate(cactusConfig.notificationConfig)) {
209 | return
210 | }
211 | saveConfig(cactusConfig)
212 | val managerCompat = NotificationManagerCompat.from(this)
213 | val notification = getNotification(cactusConfig.notificationConfig)
214 | managerCompat.notify(cactusConfig.notificationConfig.serviceId, notification)
215 | }
216 |
217 | /**
218 | * 最终都将调用此方法,注册Cactus服务
219 | *
220 | * @receiver Context
221 | * @param cactusConfig CactusConfig
222 | */
223 | internal fun Context.registerCactus(cactusConfig: CactusConfig) {
224 | val intent = Intent(this, LocalService::class.java)
225 | intent.putExtra(Constant.CACTUS_CONFIG, cactusConfig)
226 | startInternService(intent)
227 | sMainHandler.postDelayed({
228 | if (cactusConfig.defaultConfig.workerEnabled) {
229 | registerWorker()
230 | } else {
231 | unregisterWorker()
232 | }
233 | }, 5000)
234 | }
235 |
236 | /**
237 | * 注册JobService
238 | *
239 | * @receiver Context
240 | * @param cactusConfig CactusConfig
241 | */
242 | internal fun Context.registerJobCactus(cactusConfig: CactusConfig) {
243 | val intent = Intent(this, CactusJobService::class.java)
244 | intent.putExtra(Constant.CACTUS_CONFIG, cactusConfig)
245 | startInternService(intent)
246 | }
247 |
248 | /**
249 | * 开启WorkManager
250 | *
251 | * @receiver Context
252 | */
253 | internal fun Context.registerWorker() {
254 | if (isCactusRunning && sRegistered) {
255 | try {
256 | val workRequest =
257 | PeriodicWorkRequest.Builder(CactusWorker::class.java, 15, TimeUnit.SECONDS)
258 | .build()
259 | WorkManager.getInstance(this).enqueueUniquePeriodicWork(
260 | CactusWorker::class.java.name,
261 | ExistingPeriodicWorkPolicy.REPLACE,
262 | workRequest
263 | )
264 | } catch (e: Exception) {
265 | unregisterWorker()
266 | log("WorkManager registration failed")
267 | }
268 | }
269 | }
270 |
271 | /**
272 | * 取消WorkManager
273 | *
274 | * @receiver Context
275 | * @return Operation
276 | */
277 | internal fun Context.unregisterWorker() =
278 | WorkManager.getInstance(this).cancelUniqueWork(CactusWorker::class.java.name)
279 |
280 | /**
281 | * 开启远程服务
282 | *
283 | * @receiver Service
284 | * @param serviceConnection ServiceConnection
285 | * @param cactusConfig CactusConfig
286 | */
287 | internal fun Service.startRemoteService(
288 | serviceConnection: ServiceConnection,
289 | cactusConfig: CactusConfig
290 | ) = startAndBindService(RemoteService::class.java, serviceConnection, cactusConfig)
291 |
292 | /**
293 | * 开启本地服务
294 | *
295 | * @receiver Service
296 | * @param serviceConnection ServiceConnection
297 | * @param cactusConfig CactusConfig
298 | * @param isStart Boolean
299 | */
300 | internal fun Service.startLocalService(
301 | serviceConnection: ServiceConnection,
302 | cactusConfig: CactusConfig,
303 | isStart: Boolean = true
304 | ) = startAndBindService(LocalService::class.java, serviceConnection, cactusConfig, isStart)
305 |
306 | /**
307 | * 开启并绑定服务
308 | *
309 | * @receiver Service
310 | * @param cls Class<*>
311 | * @param serviceConnection ServiceConnection
312 | * @param cactusConfig CactusConfig
313 | * @param isStart Boolean
314 | * @return Boolean
315 | */
316 | private fun Service.startAndBindService(
317 | cls: Class<*>,
318 | serviceConnection: ServiceConnection,
319 | cactusConfig: CactusConfig,
320 | isStart: Boolean = true
321 | ) = run {
322 | val intent = Intent(this, cls)
323 | intent.putExtra(Constant.CACTUS_CONFIG, cactusConfig)
324 | if (isStart) {
325 | startInternService(intent)
326 | }
327 | val bindService = bindService(intent, serviceConnection, Context.BIND_IMPORTANT)
328 | bindService
329 | }
330 |
331 | /**
332 | * 开启Service
333 | *
334 | * @receiver Context
335 | * @param intent Intent
336 | */
337 | internal fun Context.startInternService(intent: Intent) {
338 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
339 | startForegroundService(intent)
340 | } else {
341 | startService(intent)
342 | }
343 | }
344 |
345 | /**
346 | * 停止服务
347 | *
348 | * @receiver Service
349 | */
350 | internal fun Service.stopService() {
351 | sMainHandler.postDelayed({
352 | try {
353 | this.stopSelf()
354 | } catch (e: Exception) {
355 | }
356 | }, 1000)
357 | }
358 |
359 | /**
360 | * 设置重启Intent
361 | *
362 | * @receiver Context
363 | * @param cactusConfig CactusConfig
364 | */
365 | private fun Context.handleRestartIntent(cactusConfig: CactusConfig) {
366 | cactusConfig.defaultConfig.apply {
367 | if (crashRestartEnabled) {
368 | restartIntent = packageManager.getLaunchIntentForPackage(packageName)
369 | restartIntent?.apply {
370 | addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
371 | addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
372 | }
373 | } else {
374 | restartIntent = null
375 | }
376 | }
377 | }
378 |
379 | /**
380 | * 开启一像素界面
381 | *
382 | * @receiver Context
383 | */
384 | internal fun Context.startOnePixActivity() {
385 | if (!isScreenOn && Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
386 | mIsForeground = isForeground
387 | log("isForeground:$mIsForeground")
388 | val onePixIntent = Intent(this, OnePixActivity::class.java)
389 | onePixIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
390 | onePixIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
391 | val pendingIntent = PendingIntent.getActivity(this, 0, onePixIntent, 0)
392 | try {
393 | pendingIntent.send()
394 | } catch (e: Exception) {
395 | }
396 | }
397 | }
398 |
399 | /**
400 | * 销毁一像素
401 | */
402 | internal fun finishOnePix() {
403 | mWeakReference?.apply {
404 | get()?.apply {
405 | finish()
406 | }
407 | mWeakReference = null
408 | }
409 | }
410 |
411 | /**
412 | * 保存一像素,方便销毁
413 | *
414 | * @receiver OnePixActivity
415 | */
416 | internal fun OnePixActivity.setOnePix() {
417 | if (mWeakReference == null) {
418 | mWeakReference = WeakReference(this)
419 | }
420 | }
421 |
422 | /**
423 | * 退到后台
424 | *
425 | * @receiver Context
426 | */
427 | internal fun backBackground() {
428 | mWeakReference?.apply {
429 | get()?.apply {
430 | if (!mIsForeground && isScreenOn) {
431 | val home = Intent(Intent.ACTION_MAIN)
432 | home.flags = Intent.FLAG_ACTIVITY_NEW_TASK
433 | home.addCategory(Intent.CATEGORY_HOME)
434 | startActivity(home)
435 | }
436 | }
437 | }
438 | }
439 |
440 | /**
441 | * WaterBear是否在运行中
442 | */
443 | internal val Context.isCactusRunning
444 | get() = run {
445 | isServiceRunning(LocalService::class.java.name) and isRunningTaskExist(Constant.CACTUS_EMOTE_SERVICE)
446 | }
447 |
448 | /**
449 | * 获得带id值的字段值
450 | */
451 | internal val String.fieldById get() = "${Constant.CACTUS_PACKAGE}.${this}.$id"
452 |
453 | /**
454 | * 获取id
455 | */
456 | internal val id get() = if (Process.myUid() <= 0) Process.myPid() else Process.myUid()
457 |
458 | /**
459 | * 解除DeathRecipient绑定
460 | *
461 | * @receiver IBinder.DeathRecipient
462 | * @param iInterface IInterface?
463 | * @param block Function0?
464 | */
465 | internal fun IBinder.DeathRecipient.unlinkToDeath(
466 | iInterface: IInterface? = null,
467 | block: (() -> Unit)? = null
468 | ) {
469 | iInterface?.asBinder()?.unlinkToDeath(this, 0)
470 | block?.invoke()
471 | }
472 |
473 | /**
474 | * 全局log
475 | *
476 | * @param msg String
477 | */
478 | internal fun log(msg: String) {
479 | sCactusConfig?.defaultConfig?.apply {
480 | if (debug) {
481 | Log.d(Constant.CACTUS_TAG, msg)
482 | }
483 | } ?: Log.v(Constant.CACTUS_TAG, msg)
484 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/ext/ConfigExt.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.ext
2 |
3 | import android.content.Context
4 | import com.google.gson.Gson
5 | import com.gyf.cactus.entity.CactusConfig
6 | import com.gyf.cactus.entity.Constant
7 |
8 | /**
9 | * 配置信息扩展
10 | *
11 | * @author geyifeng
12 | * @date 2019-11-19 13:34
13 | */
14 |
15 | /**
16 | * 保存配置信息
17 | *
18 | * @receiver Context
19 | * @param cactusConfig CactusConfig
20 | */
21 | internal fun Context.saveConfig(cactusConfig: CactusConfig) {
22 | sCactusConfig = cactusConfig
23 | val serviceId = getServiceId()
24 | if (serviceId > 0) {
25 | cactusConfig.notificationConfig.serviceId = serviceId
26 | }
27 | getSharedPreferences(Constant.CACTUS_TAG, Context.MODE_PRIVATE).edit().apply {
28 | putString(Constant.CACTUS_CONFIG, Gson().toJson(cactusConfig))
29 | if (serviceId <= 0) {
30 | putInt(Constant.CACTUS_SERVICE_ID, cactusConfig.notificationConfig.serviceId)
31 | }
32 | }.apply()
33 | }
34 |
35 | /**
36 | * 获取配置信息
37 | *
38 | * @receiver Context
39 | * @return CactusConfig
40 | */
41 | internal fun Context.getConfig() = sCactusConfig ?: getPreviousConfig() ?: CactusConfig()
42 |
43 | /**
44 | * 获取Sp保存的配置信息
45 | *
46 | * @receiver Context
47 | * @return CactusConfig?
48 | */
49 | internal fun Context.getPreviousConfig() = getSharedPreferences(
50 | Constant.CACTUS_TAG,
51 | Context.MODE_PRIVATE
52 | ).getString(Constant.CACTUS_CONFIG, null)?.run {
53 | Gson().fromJson(this, CactusConfig::class.java)
54 | }
55 |
56 | /**
57 | * 保存JobId
58 | *
59 | * @receiver Context
60 | * @param jobId Int
61 | */
62 | internal fun Context.saveJobId(jobId: Int) =
63 | getSharedPreferences(
64 | Constant.CACTUS_TAG,
65 | Context.MODE_PRIVATE
66 | ).edit().putInt(Constant.CACTUS_JOB_ID, jobId).apply()
67 |
68 | /**
69 | * 获得JobId
70 | *
71 | * @receiver Context
72 | * @return Int
73 | */
74 | internal fun Context.getJobId() =
75 | getSharedPreferences(
76 | Constant.CACTUS_TAG,
77 | Context.MODE_PRIVATE
78 | ).getInt(Constant.CACTUS_JOB_ID, -1)
79 |
80 | /**
81 | * 获得serviceId
82 | *
83 | * @receiver Context
84 | * @return Int
85 | */
86 | private fun Context.getServiceId() = getSharedPreferences(
87 | Constant.CACTUS_TAG,
88 | Context.MODE_PRIVATE
89 | ).getInt(Constant.CACTUS_SERVICE_ID, -1)
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/ext/ManagerExt.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.ext
2 |
3 | import android.annotation.SuppressLint
4 | import android.app.ActivityManager
5 | import android.content.Context
6 | import android.os.PowerManager
7 | import android.os.Process
8 |
9 | /**
10 | * PowerManager和ActivityManager
11 | *
12 | * @author geyifeng
13 | * @date 2019-12-20 12:26
14 | */
15 |
16 | /**
17 | * 屏幕是否亮屏
18 | */
19 | internal val Context.isScreenOn
20 | get() = run {
21 | try {
22 | val pm = applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager
23 | pm.isScreenOn
24 | } catch (e: Exception) {
25 | false
26 | }
27 | }
28 |
29 | /**
30 | * 获得主进程的pid
31 | */
32 | internal val Context.mainPid
33 | get() = run {
34 | val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
35 | var pid = Process.myPid()
36 | activityManager.runningAppProcesses?.forEach {
37 | if (it.processName == packageName) {
38 | pid = it.pid
39 | return@forEach
40 | }
41 | }
42 | pid
43 | }
44 |
45 | /**
46 | * 是否主进程
47 | */
48 | internal val Context.isMain
49 | get() = run {
50 | val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
51 | activityManager.runningAppProcesses.forEach {
52 | if (it.pid == Process.myPid() && it.processName == packageName) {
53 | return@run true
54 | }
55 | }
56 | false
57 | }
58 |
59 | /**
60 | * 是否在前台
61 | */
62 | internal val Context.isForeground
63 | @SuppressLint("NewApi")
64 | get() = run {
65 | var foreground = false
66 | val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
67 | activityManager.getRunningTasks(1)?.apply {
68 | if (isNotEmpty()) {
69 | this[0].topActivity?.let {
70 | foreground = (it.packageName == packageName)
71 | }
72 | }
73 | }
74 | foreground
75 | }
76 |
77 | /**
78 | * 判断服务是否在运行
79 | *
80 | * @receiver Context
81 | * @param className String
82 | * @return Boolean
83 | */
84 | fun Context.isServiceRunning(className: String): Boolean {
85 | val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
86 | activityManager.getRunningServices(Integer.MAX_VALUE)?.also {
87 | val l = it.iterator()
88 | while (l.hasNext()) {
89 | val si = l.next()
90 | if (className == si.service.className) {
91 | return true
92 | }
93 | }
94 | }
95 | return false
96 | }
97 |
98 | /**
99 | * 判断任务是否在运行
100 | *
101 | * @receiver Context
102 | * @param processName String
103 | * @return Boolean
104 | */
105 | fun Context.isRunningTaskExist(processName: String): Boolean {
106 | val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
107 | activityManager.runningAppProcesses?.forEach {
108 | if (it.processName == "$packageName:$processName") {
109 | return true
110 | }
111 | }
112 | return false
113 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/ext/NotificationExt.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.ext
2 |
3 | import android.app.Notification
4 | import android.app.NotificationChannel
5 | import android.app.NotificationManager
6 | import android.app.Service
7 | import android.content.Context
8 | import android.content.Intent
9 | import android.graphics.BitmapFactory
10 | import android.os.Build
11 | import androidx.core.app.NotificationCompat
12 | import androidx.core.app.NotificationManagerCompat
13 | import com.gyf.cactus.R
14 | import com.gyf.cactus.entity.Constant
15 | import com.gyf.cactus.entity.NotificationConfig
16 | import com.gyf.cactus.exception.CactusException
17 | import com.gyf.cactus.service.HideForegroundService
18 |
19 | /**
20 | * @author geyifeng
21 | * @date 2019-11-16 18:01
22 | */
23 |
24 | /**
25 | * 小图标
26 | */
27 | private val NotificationConfig.handleSmallIcon
28 | get() = if (hideNotification && Build.VERSION.SDK_INT != Build.VERSION_CODES.N_MR1) {
29 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !hideNotificationAfterO) {
30 | smallIcon
31 | } else {
32 | R.drawable.icon_cactus_trans
33 | }
34 | } else {
35 | smallIcon
36 | }
37 |
38 | /**
39 | * 设置通知栏信息
40 | *
41 | * @receiver Service
42 | * @param notificationConfig NotificationConfig
43 | */
44 | internal fun Service.setNotification(
45 | notificationConfig: NotificationConfig,
46 | isHideService: Boolean = false
47 | ) {
48 | val managerCompat = NotificationManagerCompat.from(this)
49 | val notification = getNotification(notificationConfig)
50 | notificationConfig.apply {
51 | //更新Notification
52 | managerCompat.notify(serviceId, notification)
53 | //设置前台服务Notification
54 | startForeground(serviceId, notification)
55 | //隐藏Notification
56 | if (hideNotification) {
57 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
58 | if (managerCompat.getNotificationChannel(notification.channelId) != null
59 | && hideNotificationAfterO
60 | ) {
61 | sMainHandler.postDelayed(
62 | {
63 | managerCompat.deleteNotificationChannel(notification.channelId)
64 | }, 1000
65 | )
66 | }
67 | } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) {
68 | if (!isHideService) {
69 | val intent = Intent(this@setNotification, HideForegroundService::class.java)
70 | intent.putExtra(Constant.CACTUS_NOTIFICATION_CONFIG, this)
71 | startInternService(intent)
72 | }
73 | }
74 | }
75 | }
76 | }
77 |
78 | /**
79 | * 获得Notification
80 | *
81 | * @param notificationConfig NotificationConfig
82 | * @return Notification
83 | */
84 | internal fun Context.getNotification(notificationConfig: NotificationConfig): Notification =
85 | notificationConfig.run {
86 | val managerCompat = NotificationManagerCompat.from(this@getNotification)
87 | //构建Notification
88 | val notification =
89 | notification ?: NotificationCompat.Builder(this@getNotification, channelId)
90 | .setContentTitle(title)
91 | .setContentText(content)
92 | .setSmallIcon(handleSmallIcon)
93 | .setLargeIcon(
94 | largeIconBitmap ?: if (largeIcon == 0) {
95 | null
96 | } else {
97 | BitmapFactory.decodeResource(
98 | resources,
99 | largeIcon
100 | )
101 | }
102 | )
103 | .setContentIntent(pendingIntent)
104 | .setAutoCancel(true)
105 | .setVisibility(NotificationCompat.VISIBILITY_SECRET)
106 | .setPriority(NotificationCompat.PRIORITY_MIN)
107 | .apply {
108 | remoteViews?.also {
109 | setContent(it)
110 | }
111 | bigRemoteViews?.also {
112 | setCustomBigContentView(it)
113 | }
114 | }
115 | .build()
116 | //设置渠道
117 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
118 | managerCompat.getNotificationChannel(notification.channelId) == null
119 | ) {
120 | if (notificationChannel != null && notificationChannel is NotificationChannel) {
121 | (notificationChannel as NotificationChannel).apply {
122 | if (id != notification.channelId) {
123 | throw CactusException(
124 | "保证渠道相同(The id of the NotificationChannel " +
125 | "is different from the channel of the Notification.)"
126 | )
127 | }
128 | }
129 | } else {
130 | notificationChannel = NotificationChannel(
131 | notification.channelId,
132 | notificationConfig.channelName,
133 | NotificationManager.IMPORTANCE_NONE
134 | )
135 | }
136 | managerCompat.createNotificationChannel(notificationChannel as NotificationChannel)
137 | }
138 | notification
139 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/pix/OnePixActivity.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.pix
2 |
3 | import android.app.Activity
4 | import android.os.Bundle
5 | import android.view.Gravity
6 | import com.gyf.cactus.ext.finishOnePix
7 | import com.gyf.cactus.ext.isScreenOn
8 | import com.gyf.cactus.ext.log
9 | import com.gyf.cactus.ext.setOnePix
10 |
11 | /**
12 | * 一像素界面
13 | * @author geyifeng
14 | * @date 2019-08-29 13:29
15 | */
16 | class OnePixActivity : Activity() {
17 |
18 | override fun onCreate(savedInstanceState: Bundle?) {
19 | super.onCreate(savedInstanceState)
20 | log("one pix is created")
21 | overridePendingTransition(0, 0)
22 | //设定一像素的activity
23 | window.setGravity(Gravity.START or Gravity.TOP)
24 | window.attributes = window.attributes.apply {
25 | x = 0
26 | y = 0
27 | height = 1
28 | width = 1
29 | }
30 | setOnePix()
31 | }
32 |
33 | override fun onResume() {
34 | super.onResume()
35 | if (isScreenOn) {
36 | finish()
37 | }
38 | }
39 |
40 | override fun onDestroy() {
41 | super.onDestroy()
42 | finishOnePix()
43 | log("one pix is destroyed")
44 | }
45 |
46 | override fun finish() {
47 | super.finish()
48 | overridePendingTransition(0, 0)
49 | }
50 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/receiver/StopReceiver.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.receiver
2 |
3 | import android.content.BroadcastReceiver
4 | import android.content.Context
5 | import android.content.Intent
6 | import android.content.IntentFilter
7 | import com.gyf.cactus.entity.Constant
8 | import com.gyf.cactus.ext.mainPid
9 |
10 | /**
11 | * 注销服务监听
12 | *
13 | * @author geyifeng
14 | * @date 2019-11-19 10:05
15 | */
16 | internal class StopReceiver private constructor(val context: Context) : BroadcastReceiver() {
17 |
18 | companion object {
19 | internal fun newInstance(context: Context) = StopReceiver(context)
20 | }
21 |
22 | /**
23 | * 待操作事件
24 | */
25 | private var mBlock: (() -> Unit)? = null
26 |
27 | private var mActionStop = "${Constant.CACTUS_FLAG_STOP}.${context.packageName}"
28 |
29 | init {
30 | context.registerReceiver(this, IntentFilter(mActionStop))
31 | }
32 |
33 | /**
34 | * 注册
35 | *
36 | * @param block Function0
37 | */
38 | internal fun register(block: () -> Unit) {
39 | mBlock = block
40 | }
41 |
42 | override fun onReceive(context: Context?, intent: Intent?) {
43 | intent?.action?.also {
44 | when (it) {
45 | mActionStop -> {
46 | this.context.unregisterReceiver(this)
47 | mBlock?.let {
48 | it()
49 | }
50 | }
51 | }
52 | }
53 | }
54 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/service/CactusJobService.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.service
2 |
3 | import android.app.Service
4 | import android.app.job.JobInfo
5 | import android.app.job.JobParameters
6 | import android.app.job.JobScheduler
7 | import android.app.job.JobService
8 | import android.content.ComponentName
9 | import android.content.Context
10 | import android.content.Intent
11 | import android.os.Build
12 | import androidx.annotation.RequiresApi
13 | import com.gyf.cactus.entity.CactusConfig
14 | import com.gyf.cactus.entity.Constant
15 | import com.gyf.cactus.ext.*
16 |
17 | /**
18 | * @author geyifeng
19 | * @date 2019-08-30 13:03
20 | */
21 | @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
22 | class CactusJobService : JobService() {
23 |
24 | private lateinit var mJobScheduler: JobScheduler
25 |
26 | private lateinit var mCactusConfig: CactusConfig
27 |
28 | private var mJobId = 100
29 |
30 | /**
31 | * 停止标识符
32 | */
33 | private var mIsStop = false
34 |
35 | override fun onCreate() {
36 | super.onCreate()
37 | mCactusConfig = getConfig()
38 | registerJob()
39 | registerStopReceiver {
40 | mIsStop = true
41 | stopService()
42 | }
43 | }
44 |
45 | override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
46 | intent?.getParcelableExtra(Constant.CACTUS_CONFIG)?.let {
47 | mCactusConfig = it
48 | }
49 | setNotification(mCactusConfig.notificationConfig)
50 | registerCactus(mCactusConfig)
51 | return Service.START_STICKY
52 | }
53 |
54 | override fun onDestroy() {
55 | stopForeground(true)
56 | mJobScheduler.cancel(mJobId)
57 | saveJobId(-1)
58 | super.onDestroy()
59 | }
60 |
61 | override fun onStartJob(jobParameters: JobParameters): Boolean {
62 | log("onStartJob")
63 | if (!isCactusRunning && !mIsStop) {
64 | registerCactus(mCactusConfig)
65 | }
66 | return false
67 | }
68 |
69 | override fun onStopJob(jobParameters: JobParameters): Boolean {
70 | log("onStopJob")
71 | if (!isCactusRunning && !mIsStop) {
72 | registerCactus(mCactusConfig)
73 | }
74 | return false
75 | }
76 |
77 | /**
78 | * 开始Job
79 | */
80 | private fun registerJob() {
81 | mJobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
82 | mJobId = getJobId()
83 | if (mJobId != -1) {
84 | mJobScheduler.cancel(mJobId)
85 | }
86 | mJobId = id
87 | saveJobId(mJobId)
88 | val builder = JobInfo.Builder(
89 | mJobId,
90 | ComponentName(packageName, CactusJobService::class.java.name)
91 | ).apply {
92 | try {
93 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
94 | setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS) //执行的最小延迟时间
95 | setOverrideDeadline(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS) //执行的最长延时时间
96 | setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS)
97 | setBackoffCriteria(
98 | JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS,
99 | JobInfo.BACKOFF_POLICY_LINEAR
100 | )//线性重试方案
101 | } else {
102 | setPeriodic(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS)
103 | setRequiresDeviceIdle(true)
104 | }
105 | setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
106 | setRequiresCharging(true) // 当插入充电器,执行该任务
107 | setPersisted(true)
108 | } catch (e: Exception) {
109 | }
110 | }
111 | mJobScheduler.schedule(builder.build())
112 | }
113 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/service/HideForegroundService.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.service
2 |
3 | import android.app.Service
4 | import android.content.Intent
5 | import android.os.IBinder
6 | import com.gyf.cactus.entity.Constant
7 | import com.gyf.cactus.entity.NotificationConfig
8 | import com.gyf.cactus.ext.sMainHandler
9 | import com.gyf.cactus.ext.setNotification
10 |
11 | /**
12 | * 隐藏前台服务
13 | * @author geyifeng
14 | * @date 2019-08-30 14:27
15 | */
16 | class HideForegroundService : Service() {
17 |
18 | override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
19 | intent?.getParcelableExtra(Constant.CACTUS_NOTIFICATION_CONFIG)
20 | ?.let {
21 | setNotification(it, true)
22 | }
23 | sMainHandler.postDelayed({
24 | stopForeground(true)
25 | stopSelf()
26 | }, 2000)
27 | return START_NOT_STICKY
28 | }
29 |
30 | override fun onBind(intent: Intent): IBinder? {
31 | return null
32 | }
33 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/service/LocalService.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.service
2 |
3 | import android.app.PendingIntent
4 | import android.app.Service
5 | import android.content.*
6 | import android.media.MediaPlayer
7 | import android.os.IBinder
8 | import com.gyf.cactus.Cactus
9 | import com.gyf.cactus.entity.CactusConfig
10 | import com.gyf.cactus.entity.Constant
11 | import com.gyf.cactus.entity.ICactusInterface
12 | import com.gyf.cactus.ext.*
13 |
14 | /**
15 | * 本地服务
16 | *
17 | * @author geyifeng
18 | * @date 2019-08-28 17:05
19 | */
20 | class LocalService : Service(), IBinder.DeathRecipient {
21 |
22 | /**
23 | * 配置信息
24 | */
25 | private lateinit var mCactusConfig: CactusConfig
26 |
27 | /**
28 | * 音乐播放器
29 | */
30 | private var mMediaPlayer: MediaPlayer? = null
31 |
32 | /**
33 | * 广播
34 | */
35 | private var mServiceReceiver: ServiceReceiver? = null
36 |
37 | /**
38 | * Service是否在运行
39 | */
40 | private var mIsServiceRunning = false
41 |
42 | /**
43 | * 音乐是否在播放
44 | */
45 | private var mIsMusicRunning = false
46 |
47 | /**
48 | * 服务连接次数
49 | */
50 | private var mConnectionTimes = sTimes
51 |
52 | /**
53 | * 停止标识符
54 | */
55 | private var mIsStop = false
56 |
57 | /**
58 | * 是否已经绑定
59 | */
60 | private var mIsBind = false
61 |
62 | /**
63 | * 是否已经注册linkToDeath
64 | */
65 | private var mIsDeathBind = false
66 |
67 | private lateinit var mLocalBinder: LocalBinder
68 |
69 | private var mIInterface: ICactusInterface? = null
70 |
71 | private val mServiceConnection = object : ServiceConnection {
72 | override fun onServiceDisconnected(name: ComponentName?) {
73 | log("onServiceDisconnected")
74 | if (!mIsStop) {
75 | mIsBind = startRemoteService(this, mCactusConfig)
76 | }
77 | }
78 |
79 | override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
80 | log("onServiceConnected")
81 | service?.let {
82 | mIInterface = ICactusInterface.Stub.asInterface(it)
83 | ?.apply {
84 | if (asBinder().isBinderAlive && asBinder().pingBinder()) {
85 | try {
86 | ++mConnectionTimes
87 | wakeup(mCactusConfig)
88 | connectionTimes(mConnectionTimes)
89 | if (!mIsDeathBind) {
90 | mIsDeathBind = true
91 | asBinder().linkToDeath(this@LocalService, 0)
92 | }
93 | } catch (e: Exception) {
94 | --mConnectionTimes
95 | }
96 | }
97 | }
98 | }
99 | }
100 | }
101 |
102 | override fun binderDied() {
103 | log("binderDied")
104 | try {
105 | unlinkToDeath(mIInterface) {
106 | mIsDeathBind = false
107 | mIInterface = null
108 | if (!mIsStop) {
109 | mIsBind = startRemoteService(mServiceConnection, mCactusConfig)
110 | }
111 | }
112 | } catch (e: Exception) {
113 | }
114 | }
115 |
116 | override fun onCreate() {
117 | super.onCreate()
118 | mCactusConfig = getConfig()
119 | registerStopReceiver {
120 | mIsStop = true
121 | sTimes = mConnectionTimes
122 | stopService()
123 | }
124 | }
125 |
126 | override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
127 | intent?.getParcelableExtra(Constant.CACTUS_CONFIG)?.let {
128 | mCactusConfig = it
129 | }
130 | setNotification(mCactusConfig.notificationConfig)
131 | mIsBind = startRemoteService(mServiceConnection, mCactusConfig)
132 | return START_STICKY
133 | }
134 |
135 | override fun onDestroy() {
136 | super.onDestroy()
137 | stopForeground(true)
138 | stopBind()
139 | stopService(Intent(this, RemoteService::class.java))
140 | onStop()
141 | }
142 |
143 | override fun onBind(intent: Intent?): IBinder? {
144 | mLocalBinder = LocalBinder()
145 | return mLocalBinder
146 | }
147 |
148 | inner class LocalBinder : ICactusInterface.Stub() {
149 |
150 | override fun wakeup(config: CactusConfig) {
151 | mCactusConfig = config
152 | }
153 |
154 | override fun connectionTimes(time: Int) {
155 | mConnectionTimes = time
156 | if (mConnectionTimes > 3 && mConnectionTimes % 2 == 0) {
157 | ++mConnectionTimes
158 | }
159 | sTimes = mConnectionTimes
160 | doWork((mConnectionTimes + 1) / 2)
161 | }
162 | }
163 |
164 | /**
165 | * 屏幕息屏亮屏与前后台切换广播
166 | */
167 | inner class ServiceReceiver : BroadcastReceiver() {
168 |
169 | override fun onReceive(context: Context?, intent: Intent?) {
170 | intent?.action?.apply {
171 | when (this) {
172 | Intent.ACTION_SCREEN_OFF -> {
173 | // 熄屏,打开1像素Activity
174 | log("screen off")
175 | openOnePix()
176 | playMusic()
177 | }
178 | Intent.ACTION_SCREEN_ON -> {
179 | //亮屏,关闭1像素Activity
180 | log("screen on")
181 | closeOnePix()
182 | if (!mCactusConfig.defaultConfig.backgroundMusicEnabled) {
183 | pauseMusic()
184 | }
185 | }
186 | Cactus.CACTUS_BACKGROUND -> {
187 | log("background")
188 | if (mCactusConfig.defaultConfig.backgroundMusicEnabled) {
189 | playMusic()
190 | }
191 | onBackground(true)
192 | }
193 | Cactus.CACTUS_FOREGROUND -> {
194 | log("foreground")
195 | pauseMusic()
196 | onBackground(false)
197 | }
198 | }
199 | }
200 | }
201 | }
202 |
203 | /**
204 | * 解除相关绑定
205 | */
206 | private fun stopBind() {
207 | try {
208 | if (mIsDeathBind) {
209 | mIsDeathBind = false
210 | unlinkToDeath(mIInterface)
211 | }
212 | if (mIsBind) {
213 | unbindService(mServiceConnection)
214 | mIsBind = false
215 | }
216 | } catch (e: Exception) {
217 | }
218 | }
219 |
220 | /**
221 | * 处理外部事情
222 | *
223 | * @param times Int,启动次数
224 | */
225 | private fun doWork(times: Int) {
226 | if (!mIsServiceRunning) {
227 | mIsServiceRunning = true
228 | log("LocalService is run >>>> do work times = $times")
229 | registerMedia()
230 | registerBroadcastReceiver()
231 | sendBroadcast(
232 | Intent(Cactus.CACTUS_WORK).putExtra(
233 | Cactus.CACTUS_TIMES,
234 | times
235 | )
236 | )
237 | setCrashRestart(times)
238 | if (Constant.CALLBACKS.isNotEmpty()) {
239 | Constant.CALLBACKS.forEach {
240 | if (mCactusConfig.defaultConfig.workOnMainThread) {
241 | sMainHandler.post { it.doWork(times) }
242 | } else {
243 | it.doWork(times)
244 | }
245 | }
246 | }
247 | }
248 | }
249 |
250 | /**
251 | * 停止回调
252 | */
253 | private fun onStop() {
254 | if (mIsServiceRunning) {
255 | mIsServiceRunning = false
256 | log("LocalService is stop!")
257 | unregisterReceiver()
258 | sendBroadcast(Intent(Cactus.CACTUS_STOP))
259 | pauseMusic()
260 | mMediaPlayer = null
261 | if (Constant.CALLBACKS.isNotEmpty()) {
262 | Constant.CALLBACKS.forEach {
263 | it.onStop()
264 | }
265 | }
266 | }
267 | }
268 |
269 | /**
270 | * 打开一像素
271 | */
272 | private fun openOnePix() {
273 | if (mCactusConfig.defaultConfig.onePixEnabled) {
274 | sMainHandler.postDelayed({ startOnePixActivity() }, 1000)
275 | }
276 | }
277 |
278 | /**
279 | * 关闭一像素
280 | */
281 | private fun closeOnePix() {
282 | mCactusConfig.defaultConfig.apply {
283 | if (onePixEnabled) {
284 | backBackground()
285 | finishOnePix()
286 | }
287 | }
288 | }
289 |
290 | /**
291 | * 设置奔溃重启,google原生rom android 10 以下可以正常重启
292 | *
293 | * @param times Int
294 | */
295 | private fun setCrashRestart(times: Int) {
296 | if (times > 1 && sStartTimes == 1) {
297 | mCactusConfig.defaultConfig.restartIntent?.also {
298 | try {
299 | PendingIntent.getActivity(this, 0, it, 0).send()
300 | } catch (e: Exception) {
301 | }
302 | }
303 | }
304 | }
305 |
306 | /**
307 | * 是否是在后台
308 | *
309 | * @param background Boolean
310 | */
311 | private fun onBackground(background: Boolean) {
312 | if (Constant.BACKGROUND_CALLBACKS.isNotEmpty()) {
313 | Constant.BACKGROUND_CALLBACKS.forEach {
314 | it.onBackground(background)
315 | }
316 | }
317 | }
318 |
319 | /**
320 | * 注册息屏亮屏、前后台切换广播监听
321 | */
322 | private fun registerBroadcastReceiver() {
323 | if (mServiceReceiver == null) {
324 | mServiceReceiver = ServiceReceiver()
325 | }
326 | mServiceReceiver?.let {
327 | registerReceiver(it, IntentFilter().apply {
328 | addAction(Intent.ACTION_SCREEN_ON)
329 | addAction(Intent.ACTION_SCREEN_OFF)
330 | addAction(Cactus.CACTUS_BACKGROUND)
331 | addAction(Cactus.CACTUS_FOREGROUND)
332 | })
333 | }
334 | }
335 |
336 | /**
337 | * 注销息屏亮屏、前后台切换广播监听
338 | */
339 | private fun unregisterReceiver() {
340 | mServiceReceiver?.let {
341 | unregisterReceiver(it)
342 | mServiceReceiver = null
343 | }
344 | }
345 |
346 | /**
347 | * 注册音乐播放器
348 | */
349 | private fun registerMedia() {
350 | if (mCactusConfig.defaultConfig.musicEnabled) {
351 | if (mMediaPlayer == null) {
352 | mMediaPlayer = MediaPlayer.create(this, mCactusConfig.defaultConfig.musicId)
353 | }
354 | mMediaPlayer?.apply {
355 | if (!mCactusConfig.defaultConfig.debug) {
356 | setVolume(0f, 0f)
357 | }
358 | setOnCompletionListener {
359 | sMainHandler.postDelayed(
360 | {
361 | mIsMusicRunning = false
362 | playMusic()
363 | },
364 | mCactusConfig.defaultConfig.repeatInterval
365 | )
366 | }
367 | setOnErrorListener { _, _, _ -> false }
368 | if (!isScreenOn) {
369 | playMusic()
370 | }
371 | }
372 | }
373 | }
374 |
375 | /**
376 | * 播放音乐
377 | */
378 | private fun playMusic() {
379 | mMediaPlayer?.apply {
380 | if (mCactusConfig.defaultConfig.musicEnabled) {
381 | if (!mIsMusicRunning) {
382 | start()
383 | mIsMusicRunning = true
384 | log("music is playing")
385 | }
386 | }
387 | }
388 | }
389 |
390 | /**
391 | * 暂停音乐
392 | */
393 | private fun pauseMusic() {
394 | mMediaPlayer?.apply {
395 | if (mIsMusicRunning) {
396 | pause()
397 | mIsMusicRunning = false
398 | log("music is pause")
399 | }
400 | }
401 | }
402 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/service/RemoteService.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.service
2 |
3 | import android.app.Service
4 | import android.content.ComponentName
5 | import android.content.Intent
6 | import android.content.ServiceConnection
7 | import android.os.IBinder
8 | import android.os.Process
9 | import com.gyf.cactus.entity.CactusConfig
10 | import com.gyf.cactus.entity.Constant
11 | import com.gyf.cactus.entity.ICactusInterface
12 | import com.gyf.cactus.exception.CactusUncaughtExceptionHandler
13 | import com.gyf.cactus.ext.*
14 | import kotlin.system.exitProcess
15 |
16 | /**
17 | * 远程服务
18 | *
19 | * @author geyifeng
20 | * @date 2019-08-28 17:05
21 | */
22 | class RemoteService : Service(), IBinder.DeathRecipient {
23 |
24 | /**
25 | * 配置信息
26 | */
27 | private lateinit var mCactusConfig: CactusConfig
28 |
29 | /**
30 | * 服务连接次数
31 | */
32 | private var mConnectionTimes = sTimes
33 |
34 | /**
35 | * 停止标识符
36 | */
37 | private var mIsStop = false
38 |
39 | /**
40 | * 是否已经绑定
41 | */
42 | private var mIsBind = false
43 |
44 | /**
45 | * 是否已经注册linkToDeath
46 | */
47 | private var mIsDeathBind = false
48 |
49 | private lateinit var remoteBinder: RemoteBinder
50 |
51 | private var mIInterface: ICactusInterface? = null
52 |
53 | private val mServiceConnection = object : ServiceConnection {
54 | override fun onServiceDisconnected(name: ComponentName?) {
55 | log("onServiceDisconnected")
56 | if (!mIsStop) {
57 | mIsBind = startLocalService(this, mCactusConfig)
58 | }
59 | }
60 |
61 | override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
62 | log("onServiceConnected")
63 | service?.let {
64 | mIInterface = ICactusInterface.Stub.asInterface(it)
65 | ?.apply {
66 | if (asBinder().isBinderAlive && asBinder().pingBinder()) {
67 | try {
68 | ++mConnectionTimes
69 | wakeup(mCactusConfig)
70 | connectionTimes(mConnectionTimes)
71 | if (!mIsDeathBind) {
72 | mIsDeathBind = true
73 | asBinder().linkToDeath(this@RemoteService, 0)
74 | }
75 | } catch (e: Exception) {
76 | --mConnectionTimes
77 | }
78 | }
79 | }
80 | }
81 | }
82 | }
83 |
84 | override fun binderDied() {
85 | log("binderDied")
86 | try {
87 | unlinkToDeath(mIInterface) {
88 | mIsDeathBind = false
89 | mIInterface = null
90 | if (!mIsStop) {
91 | mIsBind = startLocalService(mServiceConnection, mCactusConfig)
92 | }
93 | }
94 | } catch (e: Exception) {
95 | }
96 | }
97 |
98 | override fun onCreate() {
99 | super.onCreate()
100 | CactusUncaughtExceptionHandler.instance
101 | try {
102 | log("handleNotification")
103 | mCactusConfig = getConfig()
104 | setNotification(mCactusConfig.notificationConfig)
105 | } catch (e: Exception) {
106 | }
107 | registerStopReceiver {
108 | mIsStop = true
109 | sTimes = mConnectionTimes
110 | stopService()
111 | }
112 | }
113 |
114 | override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
115 | intent?.getParcelableExtra(Constant.CACTUS_CONFIG)?.let {
116 | sCactusConfig = it
117 | mCactusConfig = it
118 | }
119 | setNotification(mCactusConfig.notificationConfig)
120 | mIsBind = startLocalService(mServiceConnection, mCactusConfig, false)
121 | log("RemoteService is running")
122 | return START_STICKY
123 | }
124 |
125 | override fun onDestroy() {
126 | super.onDestroy()
127 | stopForeground(true)
128 | stopBind()
129 | log("RemoteService has stopped")
130 | Process.killProcess(Process.myPid())
131 | exitProcess(10)
132 | }
133 |
134 | override fun onBind(intent: Intent?): IBinder? {
135 | remoteBinder = RemoteBinder()
136 | return remoteBinder
137 | }
138 |
139 | inner class RemoteBinder : ICactusInterface.Stub() {
140 |
141 | override fun wakeup(config: CactusConfig) {
142 | mCactusConfig = config
143 | setNotification(mCactusConfig.notificationConfig)
144 | }
145 |
146 | override fun connectionTimes(time: Int) {
147 | mConnectionTimes = time
148 | if (mConnectionTimes > 4 && mConnectionTimes % 2 == 1) {
149 | ++mConnectionTimes
150 | }
151 | sTimes = mConnectionTimes
152 | }
153 | }
154 |
155 | /**
156 | * 解除相关绑定
157 | */
158 | private fun stopBind() {
159 | try {
160 | if (mIsDeathBind) {
161 | mIsDeathBind = false
162 | unlinkToDeath(mIInterface)
163 | }
164 | if (mIsBind) {
165 | unbindService(mServiceConnection)
166 | mIsBind = false
167 | }
168 | } catch (e: Exception) {
169 | }
170 | }
171 | }
--------------------------------------------------------------------------------
/cactus/src/main/java/com/gyf/cactus/workmanager/CactusWorker.kt:
--------------------------------------------------------------------------------
1 | package com.gyf.cactus.workmanager
2 |
3 | import android.content.Context
4 | import androidx.work.Worker
5 | import androidx.work.WorkerParameters
6 | import com.gyf.cactus.ext.*
7 |
8 | /**
9 | * WorkManager定时器
10 | *
11 | * @author geyifeng
12 | * @date 2019-09-02 11:22
13 | */
14 | class CactusWorker(val context: Context, workerParams: WorkerParameters) :
15 | Worker(context, workerParams) {
16 |
17 | /**
18 | * 停止标识符
19 | */
20 | private var mIsStop = false
21 |
22 | init {
23 | context.registerStopReceiver {
24 | mIsStop = true
25 | }
26 | }
27 |
28 | override fun doWork(): Result {
29 | context.apply {
30 | val cactusConfig = getConfig()
31 | log("${this@CactusWorker}-doWork")
32 | if (!isCactusRunning && !mIsStop && !isStopped) {
33 | register(cactusConfig)
34 | }
35 | }
36 | return Result.success()
37 | }
38 | }
--------------------------------------------------------------------------------
/cactus/src/main/res/drawable/icon_cactus_small.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus/src/main/res/drawable/icon_cactus_small.png
--------------------------------------------------------------------------------
/cactus/src/main/res/drawable/icon_cactus_trans.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus/src/main/res/drawable/icon_cactus_trans.png
--------------------------------------------------------------------------------
/cactus/src/main/res/raw/cactus.mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gyf-dev/Cactus/369e3a28f0ee61b8876f58bad157baae6a5598a1/cactus/src/main/res/raw/cactus.mp3
--------------------------------------------------------------------------------
/cactus/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Cactus
3 |
4 |
--------------------------------------------------------------------------------
/cactus/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/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 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
22 | android.injected.testOnly=false
23 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Feb 25 16:10:47 CST 2020
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.6.4-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 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':cactus-sample', ':cactus'
2 | rootProject.name='Cactus'
3 |
--------------------------------------------------------------------------------