├── .github
├── FUNDING.yml
└── ISSUE_TEMPLATE
│ └── bug----.md
├── .gitignore
├── LICENSE
├── README-EN.md
├── README.md
├── app.jks
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── azhon
│ │ └── app
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── azhon
│ │ │ └── app
│ │ │ ├── MainActivity.kt
│ │ │ └── MyDownload.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ ├── ic_dialog.png
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── values-en-rUS
│ │ └── strings.xml
│ │ ├── values-night
│ │ └── themes.xml
│ │ ├── values-zh-rTW
│ │ └── strings.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── themes.xml
│ └── test
│ └── java
│ └── com
│ └── azhon
│ └── app
│ └── ExampleUnitTest.kt
├── appupdate-no-op
├── .gitignore
├── build.gradle
├── consumer-rules.pro
├── gradle.properties
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── azhon
│ │ └── appupdate
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ └── java
│ │ └── com
│ │ └── azhon
│ │ └── appupdate
│ │ ├── base
│ │ ├── BaseHttpDownloadManager.kt
│ │ └── bean
│ │ │ └── DownloadStatus.kt
│ │ ├── listener
│ │ ├── OnButtonClickListener.kt
│ │ ├── OnDownloadListener.kt
│ │ └── OnDownloadListenerAdapter.kt
│ │ ├── manager
│ │ └── DownloadManager.kt
│ │ └── util
│ │ └── ApkUtil.kt
│ └── test
│ └── java
│ └── com
│ └── azhon
│ └── appupdate
│ └── ExampleUnitTest.kt
├── appupdate
├── .gitignore
├── build.gradle
├── consumer-rules.pro
├── gradle.properties
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── azhon
│ │ └── appupdate
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── azhon
│ │ │ └── appupdate
│ │ │ ├── base
│ │ │ ├── BaseHttpDownloadManager.kt
│ │ │ └── bean
│ │ │ │ └── DownloadStatus.kt
│ │ │ ├── config
│ │ │ ├── AppUpdateFileProvider.kt
│ │ │ └── Constant.kt
│ │ │ ├── listener
│ │ │ ├── LifecycleCallbacksAdapter.kt
│ │ │ ├── OnButtonClickListener.kt
│ │ │ ├── OnDownloadListener.kt
│ │ │ └── OnDownloadListenerAdapter.kt
│ │ │ ├── manager
│ │ │ ├── DownloadManager.kt
│ │ │ └── HttpDownloadManager.kt
│ │ │ ├── service
│ │ │ └── DownloadService.kt
│ │ │ ├── util
│ │ │ ├── ApkUtil.kt
│ │ │ ├── DensityUtil.kt
│ │ │ ├── FileUtil.kt
│ │ │ ├── LogUtil.kt
│ │ │ └── NotificationUtil.kt
│ │ │ └── view
│ │ │ ├── NumberProgressBar.java
│ │ │ └── UpdateDialogActivity.kt
│ └── res
│ │ ├── drawable
│ │ ├── app_update_bg_button.xml
│ │ ├── app_update_bg_white_radius_6.xml
│ │ ├── app_update_dialog_close.png
│ │ └── app_update_dialog_default.png
│ │ ├── layout
│ │ └── app_update_dialog_update.xml
│ │ ├── values-en-rUS
│ │ └── strings.xml
│ │ ├── values-zh-rTW
│ │ └── strings.xml
│ │ ├── values
│ │ ├── strings.xml
│ │ └── styles.xml
│ │ └── xml
│ │ └── app_update_file.xml
│ └── test
│ └── java
│ └── com
│ └── azhon
│ └── appupdate
│ └── ExampleUnitTest.kt
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── img
├── en
│ ├── en_1.png
│ ├── en_2.png
│ ├── en_3.png
│ ├── en_4.png
│ ├── en_5.png
│ ├── en_6.png
│ └── en_7.png
├── logo.png
├── money.jpg
├── qq_group_0.jpg
├── qq_group_1.jpg
└── zh
│ ├── zh_1.png
│ ├── zh_2.png
│ ├── zh_3.png
│ ├── zh_4.png
│ ├── zh_5.png
│ ├── zh_6.png
│ └── zh_7.png
├── maven.gradle
├── maven_publish.sh
└── settings.gradle
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | custom: ['https://github.com/azhon/AppUpdate#%E8%B5%9E%E8%B5%8F']
4 | #github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
5 | #patreon: # Replace with a single Patreon username
6 | #open_collective: # Replace with a single Open Collective username
7 | #ko_fi: # Replace with a single Ko-fi username
8 | #tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
9 | #community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
10 | #liberapay: # Replace with a single Liberapay username
11 | #issuehunt: # Replace with a single IssueHunt username
12 | #otechie: # Replace with a single Otechie username
13 | #custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
14 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug----.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Question submission
3 | about: bug、future、anything
4 | title: Write title
5 | labels: bug
6 | assignees: ''
7 |
8 | ---
9 |
10 | **AppUpdate parameter**
11 | Screenshot `DownloadManager` configuration
12 |
13 | **Steps to reproduce**
14 |
15 | **Log or something else**
16 |
17 | **Software version**
18 | - Android Studio:
19 | - AppUpdate Version:
20 | - Device Brand:
21 | - Device Model:
22 | - Android Version:
23 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 | local.properties
11 | /secret.gpg
12 |
--------------------------------------------------------------------------------
/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 [azhon]
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-EN.md:
--------------------------------------------------------------------------------
1 | ## [中文 文档](https://github.com/azhon/AppUpdate/blob/main/README.md)
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | ## The core logic of this library:
12 | #### 1、When `apkVersionCode()` is set the latest VersionCode, it will automatically judge whether to display the dialog, download and install
13 | - Adapt to Android 13 notification permission, and when set `showNotification(true)`, clicking the upgrade button will request notification permission, and the download will continue regardless of whether you agree or not
14 | - When set `forcedUpgrade(true)`,display dialog has progress bar
15 | #### 2、When `apkVersionCode()` is not set, it can be regarded as a downloader, which will only download and install
16 | #### 3、Since Android Q version restricts background apps from launching Activity, a notification will be sent to the notification bar when the download is complete (ignoring the showNotification value, you need to allow notifications to be sent)
17 | #### 4、[For more usage,click here](https://github.com/azhon/AppUpdate/blob/main/app/src/main/java/com/azhon/app/MainActivity.kt#L79)
18 |
19 | ### Related Docs Links
20 | - [Activity background starts](https://developer.android.google.cn/guide/components/activities/background-starts)
21 | - [Adapt notification](https://developer.android.google.cn/guide/topics/ui/notifiers/notifications?hl=zh-cn)
22 |
23 | ## Table of Contents
24 |
25 | * Rendering
26 | * Function introduction
27 | * Demo download experience
28 | * Steps for usage
29 | * Skills
30 | * Version update record
31 | * End
32 |
33 | ### Rendering
34 |
35 |
36 |
37 |
38 |
39 |
40 | ### Function introduction
41 |
42 | * [x] Support Java、Kotlin
43 | * [x] Support AndroidX
44 | * [x] Support for custom download process
45 | * [x] Support Android 4.1 and above
46 | * [x] Support notification progress display, adapt to Android 13
47 | * [x] Support Chinese/Traditional/English
48 | * [x] Support for custom built-in dialog styles
49 | * [x] Support for canceling the download (if the notification bar message is sent, it will be removed)
50 | * [x] Support download completion Delete old APK file after opening new version
51 | * [x] Download using HttpURLConnection, no other third-party framework is integrated
52 |
53 | ### [Demo download experience](https://github.com/azhon/AppUpdate/releases/tag/demo)
54 |
55 | ### Steps for usage
56 |
57 | #### Step1:`app/build.gradle`
58 |
59 | ```groovy
60 | implementation 'io.github.azhon:appupdate:4.3.6'
61 | ```
62 |
63 | Since in-app updates are prohibited by GooglePlay policy, it can be handled in productFlavors
64 |
65 | - [GooglePlay policy](https://support.google.com/googleplay/android-developer/answer/9888379?hl=en&ref_topic=9877467)
66 | - Library provides a version without no operation[Click see more](https://github.com/azhon/AppUpdate/blob/main/app/build.gradle)
67 | ```groovy
68 | android {
69 | //...
70 | productFlavors {
71 | other {}
72 | googlePlay {}
73 | }
74 | }
75 |
76 | dependencies {
77 | otherImplementation 'io.github.azhon:appupdate:latest-version'
78 | googlePlayImplementation 'io.github.azhon:appupdate-no-op:latest-version'
79 | }
80 | ```
81 |
82 |
83 | #### Step2:Create `DownloadManager`
84 |
85 |
86 | Kotlin
87 |
88 | ```java
89 | val manager = DownloadManager.Builder(this).run {
90 | apkUrl("your apk url")
91 | apkName("appupdate.apk")
92 | smallIcon(R.mipmap.ic_launcher)
93 | //If this parameter is set, it will automatically determine whether to show dialog
94 | apkVersionCode(2)
95 | apkVersionName('v4.2.2')
96 | apkSize("7.7MB")
97 | apkDescription("description...")
98 | //Optional parameters...
99 | build()
100 | }
101 | manager?.download()
102 | ```
103 |
104 |
105 |
106 | Java
107 |
108 | ```java
109 | DownloadManager manager = new DownloadManager.Builder(this)
110 | .apkUrl("your apk url")
111 | .apkName("appupdate.apk")
112 | .smallIcon(R.mipmap.ic_launcher)
113 | //If this parameter is set, it will automatically determine whether to show dialog
114 | .apkVersionCode(2)
115 | .apkVersionName("v4.2.2")
116 | .apkSize("7.7MB")
117 | .apkDescription("description...")
118 | //Optional parameters...
119 | .build();
120 | manager.download();
121 | ```
122 |
123 |
124 | #### Step3:ProGuard Rules
125 |
126 | ```groovy
127 | -keep public class * extends android.app.Activity
128 | -keep public class * extends android.app.Service
129 | ```
130 |
131 | ### Skills
132 |
133 | * Internationalization support, other languages only need to take the same name in the corresponding `string.xml`
134 | * To view the Log, you only need to filter the Tag at the beginning of `AppUpdate`
135 | * Download completed Delete old APK file after opening new version
136 |
137 | ```java
138 | //Old version apk file save path
139 | val result = ApkUtil.deleteOldApk(this, "${externalCacheDir?.path}/appupdate.apk")
140 | ```
141 |
142 | * Tips: The contents of the upgrade dialog can be swiped up and down!
143 | * If you need to implement your own set of download process, you only need to `extends` `BaseHttpDownloadManager`.
144 |
145 | ```java
146 | class MyDownload : BaseHttpDownloadManager() {}
147 | ```
148 |
149 | ### Version update record
150 |
151 | * v4.3.6(2024/10/22)
152 |
153 | * [Opt] Change DownloadManager release() to public
154 |
155 | #### [More update records click here to view](https://github.com/azhon/AppUpdate/wiki/Home)
156 |
157 | ### End
158 |
159 | * If you encounter problems during use, please feel free to ask Issues.
160 | * If you have any good suggestions, you can also mention Issues or send email to: azhon.cn@gmail.com.
161 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## [English Doc](https://github.com/azhon/AppUpdate/blob/main/README-EN.md)
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | ## 如果你是Flutter,请使用[flutter_app_update](https://github.com/azhon/flutter_app_update)
12 |
13 | > [!NOTE]
14 | > ### 本库核心逻辑(必读):
15 | > #### 1、当调用了`apkVersionCode()`设置了最新的VersionCode,则内部会自动判断是否显示对话框、下载和安装
16 | > - 适配Android 13通知运行权限,且当设置`showNotification(true)`时,点击对话框的升级按钮会申请通知栏权限,无论是否同意都将会继续下载
17 | > - 当设置强制更新`forcedUpgrade(true)`时,显示的对话框会显示下载进度条
18 | > #### 2、当没有调用`apkVersionCode()`,就可以把它当成一个下载器,内部只会进行下载和安装
19 | > #### 3、由于Android 10限制后台应用启动Activity,所以下载完成会发送一个通知至通知栏(忽略showNotification的值,需要允许发送通知)
20 | > #### 4、[更多用法请点此查看](https://github.com/azhon/AppUpdate/blob/main/app/src/main/java/com/azhon/app/MainActivity.kt#L79)
21 |
22 | ### 如果有需要使用[UpgradeLink](http://upgrade.toolsetlink.com)的可以[查阅此文档](http://upgrade.toolsetlink.com/upgrade/example/android-appupdate-example.html)
23 |
24 | ### 相关文档链接
25 | - [限制后台启动Activity](https://developer.android.google.cn/guide/components/activities/background-starts)
26 | - [通知栏适配](https://developer.android.google.cn/guide/topics/ui/notifiers/notifications?hl=zh-cn)
27 |
28 | ## 目录
29 |
30 | * [效果图](#效果图)
31 | * [功能介绍](#功能介绍)
32 | * [Demo下载体验](#demo下载体验)
33 | * [扫码加入QQ群](#扫码加入qq群)
34 | * [使用步骤](#使用步骤)
35 | * [使用技巧](#使用技巧)
36 | * [常见问题](#常见问题)
37 | * [版本更新记录](#版本更新记录)
38 | * [赞赏](#赞赏)
39 |
40 | ### 效果图
41 |
42 |
43 |
44 |
45 |
46 |
47 | ### 功能介绍
48 |
49 | * [x] 支持Java、Kotlin
50 | * [x] 支持AndroidX
51 | * [x] 支持后台下载
52 | * [x] 支持强制更新
53 | * [x] 支持自定义下载过程
54 | * [x] 支持Android4.1及以上版本
55 | * [x] 支持通知栏进度条展示,适配到Android 13
56 | * [x] 支持中文/繁体/英文语言(国际化)
57 | * [x] 支持自定义内置对话框样式
58 | * [x] 支持取消下载(如果发送了通知栏消息,则会移除)
59 | * [x] 支持下载完成,打开新版本后删除旧安装包文件
60 | * [x] 不需要申请存储权限
61 | * [x] 使用HttpURLConnection下载,未集成其他第三方框架
62 |
63 | ### Demo下载体验
64 |
65 | [点击下载Demo进行体验](https://github.com/azhon/AppUpdate/releases/tag/demo)
66 |
67 | ### 扫码加入QQ群
68 | - 或者添加加微信:hb958460248(备注 AppUpdate)
69 | - 611136880
70 | - 828385813(已满)
71 |
72 |
73 |
74 |
75 | ### 使用步骤
76 |
77 | #### 第一步:`app/build.gradle`添加依赖
78 |
79 | ```groovy
80 | implementation 'io.github.azhon:appupdate:4.3.6'
81 | ```
82 |
83 |
84 | 由于GooglePlay政策禁止应用内更新,所以可以通过多渠道的方式进处理
85 |
86 | - [GooglePlay政策](https://support.google.com/googleplay/android-developer/answer/9888379?hl=en&ref_topic=9877467)
87 | - 本库提供了一个没有任何实现的版本[点击查看详细内容](https://github.com/azhon/AppUpdate/blob/main/app/build.gradle)
88 | ```groovy
89 | android {
90 | //...
91 | productFlavors {
92 | other {}
93 | googlePlay {}
94 | }
95 | }
96 |
97 | dependencies {
98 | otherImplementation 'io.github.azhon:appupdate:latest-version'
99 | googlePlayImplementation 'io.github.azhon:appupdate-no-op:latest-version'
100 | }
101 | ```
102 |
103 |
104 | #### 第二步:创建`DownloadManager`
105 |
106 |
107 | Kotlin
108 |
109 | ```java
110 | val manager = DownloadManager.Builder(this).run {
111 | apkUrl("your apk url")
112 | apkName("appupdate.apk")
113 | smallIcon(R.mipmap.ic_launcher)
114 | //设置了此参数,那么内部会自动判断是否需要显示更新对话框,否则需要自己判断是否需要更新
115 | apkVersionCode(2)
116 | //同时下面三个参数也必须要设置
117 | apkVersionName('v4.2.2')
118 | apkSize("7.7MB")
119 | apkDescription("更新描述信息(取服务端返回数据)")
120 | //省略一些非必须参数...
121 | build()
122 | }
123 | manager?.download()
124 | ```
125 |
126 |
127 |
128 | Java
129 |
130 | ```java
131 | DownloadManager manager = new DownloadManager.Builder(this)
132 | .apkUrl("your apk url")
133 | .apkName("appupdate.apk")
134 | .smallIcon(R.mipmap.ic_launcher)
135 | //设置了此参数,那么内部会自动判断是否需要显示更新对话框,否则需要自己判断是否需要更新
136 | .apkVersionCode(2)
137 | //同时下面三个参数也必须要设置
138 | .apkVersionName("v4.2.2")
139 | .apkSize("7.7MB")
140 | .apkDescription("更新描述信息(取服务端返回数据)")
141 | //省略一些非必须参数...
142 | .build();
143 | manager.download();
144 | ```
145 |
146 |
147 | #### 第三步:混淆打包,只需保持`Activity`、`Service`不混淆
148 |
149 | ```groovy
150 | -keep public class * extends android.app.Activity
151 | -keep public class * extends android.app.Service
152 | ```
153 |
154 | ### 使用技巧
155 |
156 | * 框架内部支持国际化(其他语言只需要在对应的`string.xml`中取相同的名字即可)
157 | * 如果你需要修改框架内部的一些文字,你只需要在`string.xml`中取相同的名字即可以覆盖框架内设定的
158 | * 查看版本库中的Log只需要过滤`AppUpdate`开头的Tag
159 | * 支持校验安装包的MD5避免重复下载,只需要`Builder`设置安装包的MD5即可
160 | * 下载完成 打开新版本后删除旧安装包文件
161 |
162 | ```java
163 | //旧版本apk的文件保存地址
164 | val result = ApkUtil.deleteOldApk(this, "${externalCacheDir?.path}/appupdate.apk")
165 | ```
166 |
167 | * 温馨提示:升级对话框中的内容是可以上下滑动的哦!
168 | * 如果需要实现自己一套下载过程,只需要继承`BaseHttpDownloadManager`
169 |
170 | ```java
171 | class MyDownload : BaseHttpDownloadManager() {}
172 | ```
173 | ### 常见问题
174 |
175 | * App设置是横屏时下载完成无法拉起安装问题,可以在Manifest中对应的Activity添加如下代码
176 |
177 | ```xml
178 | android:configChanges="orientation|screenSize|keyboardHidden"
179 | ```
180 |
181 | ### 版本更新记录
182 |
183 | * v4.3.6(2024/10/22)
184 |
185 | * [优化] 修改DownloadManager的release()函数访问权限
186 |
187 | * [更多更新记录点此查看](https://github.com/azhon/AppUpdate/wiki/Home)
188 |
189 | ### 赞赏
190 | > 如果这个库有帮助到你并且你很想支持库的后续开发和维护,那么你可以扫描下方二维码随意打赏我,我将不胜感激[赞赏列表](https://github.com/azhon/AppUpdate/wiki/%E8%B5%9E%E8%B5%8F%E5%88%97%E8%A1%A8)
191 |
192 |
193 |
194 |
--------------------------------------------------------------------------------
/app.jks:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/app.jks
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'org.jetbrains.kotlin.android'
4 | }
5 |
6 | android {
7 | namespace 'com.azhon.app'
8 | compileSdk rootProject.ext.compileSdk
9 | defaultConfig {
10 | applicationId "com.azhon.app"
11 | minSdk rootProject.ext.minSdk
12 | targetSdk rootProject.ext.targetSdk
13 | versionCode 1
14 | versionName "1.0"
15 |
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | }
18 | flavorDimensions "versionCode"
19 |
20 | compileOptions {
21 | sourceCompatibility JavaVersion.VERSION_1_8
22 | targetCompatibility JavaVersion.VERSION_1_8
23 | }
24 | kotlinOptions {
25 | jvmTarget = '1.8'
26 | }
27 |
28 | productFlavors {
29 | other {}
30 | // googlePlay {}
31 | }
32 | signingConfigs {
33 | config {
34 | keyAlias 'appUpdate'
35 | keyPassword '123456'
36 | storeFile file('./../app.jks')
37 | storePassword '123456'
38 | }
39 | }
40 | buildTypes {
41 | release {
42 | minifyEnabled false
43 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
44 | signingConfig signingConfigs.config
45 | }
46 | debug {
47 | signingConfig signingConfigs.config
48 | }
49 | }
50 | }
51 |
52 | dependencies {
53 | otherImplementation project(':appupdate')
54 | // googlePlayImplementation project(':appupdate-no-op')
55 |
56 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1"
57 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1"
58 | implementation 'androidx.core:core-ktx:1.7.0'
59 | implementation 'androidx.appcompat:appcompat:1.4.2'
60 | implementation 'com.google.android.material:material:1.5.0'
61 | testImplementation 'junit:junit:4.13.2'
62 | androidTestImplementation 'androidx.test.ext:junit:1.1.3'
63 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
64 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/azhon/app/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.app
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.azhon.app", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/java/com/azhon/app/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.app
2 |
3 | import android.graphics.Color
4 | import android.os.Bundle
5 | import android.util.Log
6 | import android.view.View
7 | import android.widget.Button
8 | import android.widget.ProgressBar
9 | import android.widget.TextView
10 | import androidx.appcompat.app.AlertDialog
11 | import androidx.appcompat.app.AppCompatActivity
12 | import com.azhon.appupdate.listener.OnButtonClickListener
13 | import com.azhon.appupdate.listener.OnDownloadListenerAdapter
14 | import com.azhon.appupdate.manager.DownloadManager
15 | import com.azhon.appupdate.util.ApkUtil
16 |
17 | /**
18 | * createDate: 2022/04/08 on 14:52
19 | * desc:
20 | *
21 | * @author azhon
22 | */
23 |
24 | class MainActivity : AppCompatActivity(), View.OnClickListener, OnButtonClickListener {
25 |
26 | companion object {
27 | private const val TAG = "MainActivity"
28 | }
29 |
30 | private val url = "https://downv6.qq.com/qqweb/QQ_1/android_apk/Android_9.0.81_64.apk"
31 | private val apkName = "appupdate.apk"
32 | private var manager: DownloadManager? = null
33 | private lateinit var tvPercent: TextView
34 | private lateinit var progressBar: ProgressBar
35 |
36 | override fun onCreate(savedInstanceState: Bundle?) {
37 | super.onCreate(savedInstanceState)
38 | setContentView(R.layout.activity_main)
39 | title = getString(R.string.app_title)
40 | progressBar = findViewById(R.id.number_progress_bar)
41 | tvPercent = findViewById(R.id.tv_percent)
42 | findViewById(R.id.tv_channel).text =
43 | String.format(getString(R.string.layout_channel), BuildConfig.FLAVOR)
44 | findViewById(R.id.btn_1).setOnClickListener(this)
45 | findViewById(R.id.btn_2).setOnClickListener(this)
46 | findViewById(R.id.btn_3).setOnClickListener(this)
47 | findViewById(R.id.btn_4).setOnClickListener(this)
48 |
49 | //delete downloaded old Apk
50 | val result = ApkUtil.deleteOldApk(this, "${externalCacheDir?.path}/$apkName")
51 | }
52 |
53 | override fun onClick(v: View?) {
54 | when (v?.id) {
55 | R.id.btn_1 -> startUpdate1()
56 | R.id.btn_2 -> startUpdate2()
57 | R.id.btn_3 -> startUpdate3()
58 | R.id.btn_4 -> {
59 | manager?.cancel()
60 | }
61 | }
62 | }
63 |
64 | private fun startUpdate1() {
65 | AlertDialog.Builder(this@MainActivity)
66 | .setTitle(R.string.dialog_title)
67 | .setMessage(R.string.dialog_msg)
68 | .setPositiveButton(R.string.dialog_confirm) { _, _ ->
69 | startUpdate2()
70 | }.create()
71 | .show()
72 | }
73 |
74 | private fun startUpdate2() {
75 | resetPb()
76 | manager = DownloadManager.Builder(this).run {
77 | apkUrl(url)
78 | apkName(apkName)
79 | smallIcon(R.mipmap.ic_launcher)
80 | build()
81 | }
82 | manager!!.download()
83 | }
84 |
85 |
86 | private fun startUpdate3() {
87 | manager = DownloadManager.Builder(this).run {
88 | apkUrl(url)
89 | apkName(apkName)
90 | smallIcon(R.mipmap.ic_launcher)
91 | showNewerToast(true)
92 | apkVersionCode(2)
93 | apkVersionName("v4.2.1")
94 | apkSize("7.7MB")
95 | apkDescription(getString(R.string.dialog_msg))
96 | enableLog(true)
97 | jumpInstallPage(true)
98 | dialogButtonTextColor(Color.WHITE)
99 | showNotification(true)
100 | showBgdToast(false)
101 | forcedUpgrade(false)
102 | onDownloadListener(listenerAdapter)
103 | // apkMD5("DC501F04BBAA458C9DC33008EFED5E7F")
104 | // httpManager()
105 | // dialogImage(R.drawable.ic_dialog)
106 | // dialogButtonColor(Color.parseColor("#E743DA"))
107 | // dialogProgressBarColor(Color.parseColor("#E743DA"))
108 | // notificationChannel()
109 | // notifyId(1011)
110 | onButtonClickListener(this@MainActivity)
111 | build()
112 | }
113 | manager?.download()
114 | }
115 |
116 | private fun resetPb() {
117 | progressBar.progress = 0
118 | tvPercent.text = "0%"
119 | }
120 |
121 | private val listenerAdapter: OnDownloadListenerAdapter = object : OnDownloadListenerAdapter() {
122 |
123 | override fun downloading(max: Int, progress: Int) {
124 | val curr = (progress / max.toDouble() * 100.0).toInt()
125 | progressBar.max = 100
126 | progressBar.progress = curr
127 | tvPercent.text = "$curr%"
128 | }
129 | }
130 |
131 |
132 | override fun onButtonClick(id: Int) {
133 | Log.e(TAG, "onButtonClick: $id")
134 | }
135 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/azhon/app/MyDownload.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.app
2 |
3 | import com.azhon.appupdate.base.BaseHttpDownloadManager
4 | import com.azhon.appupdate.base.bean.DownloadStatus
5 | import kotlinx.coroutines.flow.Flow
6 | import kotlinx.coroutines.flow.flow
7 |
8 |
9 | /**
10 | * createDate: 2022/4/8 on 11:23
11 | * desc:
12 | *
13 | * @author azhon
14 | */
15 |
16 | class MyDownload : BaseHttpDownloadManager() {
17 |
18 |
19 | override fun download(
20 | apkUrl: String, apkName: String
21 | ): Flow {
22 | return flow { }
23 | }
24 |
25 | override fun cancel() {
26 | }
27 |
28 | override fun release() {
29 | }
30 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_dialog.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/app/src/main/res/drawable/ic_dialog.png
--------------------------------------------------------------------------------
/app/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 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
16 |
17 |
23 |
24 |
31 |
32 |
33 |
39 |
40 |
49 |
50 |
58 |
59 |
67 |
68 |
76 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values-en-rUS/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | AppUpdate
3 | A simple app update library
4 | New version
5 | 1.Support Android 4.1 and above\n2.Support for custom download process\n3.Support notification bar progress\n4.Support internationalization\n5.Use Kotlin Coroutines
6 | Upgrade
7 | Current flavor:%s
8 | Use your own dialog
9 | Simple to use
10 | Use the dialog built into the library
11 | Cancel download
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/app/src/main/res/values-zh-rTW/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | 版本更新
3 | 一個簡單好用的版本更新庫
4 | 發現新版本
5 | 1.支持Android4.1及以上版本\n2.支持自定義下載過程\n3.支持通知欄進度條展示\n4.支持文字國際化\n5.使用Kotlin協程重構
6 | 升級
7 | 當前渠道:%s
8 | 使用自己的對話框更新
9 | 簡單易用
10 | 使用版本庫內置的對話框更新
11 | 取消下載
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF2196F3
5 | #FF1976D2
6 | #FF2196F3
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | 版本更新
3 | 一个简单好用的版本更新库
4 | 发现新版本
5 | 1.支持Android4.1及以上版本\n2.支持自定义下载过程\n3.支持通知栏进度条展示\n4.支持文字国际化\n5.使用Kotlin协程重构
6 | 升级
7 | 当前渠道:%s
8 | 使用自己的对话框更新
9 | 简单使用
10 | 使用版本库内置的对话框更新
11 | 取消下载
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
14 |
--------------------------------------------------------------------------------
/app/src/test/java/com/azhon/app/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.app
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 | }
--------------------------------------------------------------------------------
/appupdate-no-op/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/appupdate-no-op/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'org.jetbrains.kotlin.android'
3 | apply from: '../maven.gradle'
4 |
5 | android {
6 | namespace 'com.azhon.appupdate'
7 | compileSdk rootProject.ext.compileSdk
8 |
9 | defaultConfig {
10 | minSdk rootProject.ext.minSdk
11 | targetSdk rootProject.ext.targetSdk
12 |
13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
14 | consumerProguardFiles "consumer-rules.pro"
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | compileOptions {
24 | sourceCompatibility JavaVersion.VERSION_1_8
25 | targetCompatibility JavaVersion.VERSION_1_8
26 | }
27 | kotlinOptions {
28 | jvmTarget = '1.8'
29 | }
30 | }
31 |
32 | dependencies {
33 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1"
34 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1"
35 | testImplementation 'junit:junit:4.13.2'
36 | androidTestImplementation 'androidx.test.ext:junit:1.1.3'
37 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
38 | }
--------------------------------------------------------------------------------
/appupdate-no-op/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/appupdate-no-op/consumer-rules.pro
--------------------------------------------------------------------------------
/appupdate-no-op/gradle.properties:
--------------------------------------------------------------------------------
1 | ARTIFACT_ID=appupdate-no-op
--------------------------------------------------------------------------------
/appupdate-no-op/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
--------------------------------------------------------------------------------
/appupdate-no-op/src/androidTest/java/com/azhon/appupdate/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate
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.azhon.appupdate.test", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/appupdate-no-op/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/appupdate-no-op/src/main/java/com/azhon/appupdate/base/BaseHttpDownloadManager.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.base
2 |
3 | import com.azhon.appupdate.base.bean.DownloadStatus
4 | import kotlinx.coroutines.flow.Flow
5 |
6 | /**
7 | * createDate: 2022/4/7 on 10:24
8 | * desc:
9 | *
10 | * @author azhon
11 | */
12 |
13 | abstract class BaseHttpDownloadManager {
14 | /**
15 | * download apk from apkUrl
16 | *
17 | * @param apkUrl
18 | * @param apkName
19 | */
20 | abstract fun download(apkUrl: String, apkName: String): Flow
21 |
22 | /**
23 | * cancel download apk
24 | */
25 | abstract fun cancel()
26 |
27 | /**
28 | * release memory
29 | */
30 | abstract fun release()
31 | }
--------------------------------------------------------------------------------
/appupdate-no-op/src/main/java/com/azhon/appupdate/base/bean/DownloadStatus.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.base.bean
2 |
3 | import java.io.File
4 |
5 |
6 | /**
7 | * createDate: 2022/4/14 on 11:18
8 | * desc:
9 | *
10 | * @author azhon
11 | */
12 |
13 |
14 | sealed class DownloadStatus {
15 |
16 | object Start : DownloadStatus()
17 |
18 | data class Downloading(val max: Int, val progress: Int) : DownloadStatus()
19 |
20 | class Done(val apk: File) : DownloadStatus()
21 |
22 | object Cancel : DownloadStatus()
23 |
24 | data class Error(val e: Throwable) : DownloadStatus()
25 | }
26 |
--------------------------------------------------------------------------------
/appupdate-no-op/src/main/java/com/azhon/appupdate/listener/OnButtonClickListener.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.listener
2 |
3 |
4 | /**
5 | * createDate: 2022/4/7 on 15:56
6 | * desc:
7 | *
8 | * @author azhon
9 | */
10 |
11 | interface OnButtonClickListener {
12 | companion object {
13 | /**
14 | * click update button
15 | */
16 | const val UPDATE = 0
17 |
18 | /**
19 | * click cancel button
20 | */
21 | const val CANCEL = 1
22 | }
23 |
24 | fun onButtonClick(id: Int)
25 | }
--------------------------------------------------------------------------------
/appupdate-no-op/src/main/java/com/azhon/appupdate/listener/OnDownloadListener.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.listener
2 |
3 | import java.io.File
4 |
5 | /**
6 | * createDate: 2022/4/7 on 10:27
7 | * desc:
8 | *
9 | * @author azhon
10 | */
11 |
12 | interface OnDownloadListener {
13 | /**
14 | * start download
15 | */
16 | fun start()
17 |
18 | /**
19 | *
20 | * @param max file length
21 | * @param progress downloaded file size
22 | */
23 | fun downloading(max: Int, progress: Int)
24 |
25 | /**
26 | * @param apk
27 | */
28 | fun done(apk: File)
29 |
30 | /**
31 | * cancel download
32 | */
33 | fun cancel()
34 |
35 | /**
36 | *
37 | * @param e
38 | */
39 | fun error(e: Throwable)
40 | }
--------------------------------------------------------------------------------
/appupdate-no-op/src/main/java/com/azhon/appupdate/listener/OnDownloadListenerAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.listener
2 |
3 | import java.io.File
4 |
5 |
6 | /**
7 | * createDate: 2022/4/8 on 10:58
8 | * desc:
9 | *
10 | * @author azhon
11 | */
12 |
13 | abstract class OnDownloadListenerAdapter : OnDownloadListener {
14 | override fun start() {
15 | }
16 |
17 | override fun downloading(max: Int, progress: Int) {
18 | }
19 |
20 | override fun done(apk: File) {
21 | }
22 |
23 | override fun cancel() {
24 | }
25 |
26 | override fun error(e: Throwable) {
27 | }
28 | }
--------------------------------------------------------------------------------
/appupdate-no-op/src/main/java/com/azhon/appupdate/manager/DownloadManager.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.manager
2 |
3 | import android.app.Activity
4 | import android.app.NotificationChannel
5 | import com.azhon.appupdate.base.BaseHttpDownloadManager
6 | import com.azhon.appupdate.listener.OnButtonClickListener
7 | import com.azhon.appupdate.listener.OnDownloadListener
8 | import java.io.Serializable
9 |
10 | /**
11 | * createDate: 2022/4/7 on 10:36
12 | * desc:
13 | *
14 | * @author azhon
15 | */
16 | class DownloadManager private constructor(builder: Builder) : Serializable {
17 |
18 | companion object {
19 | private var instance: DownloadManager? = null
20 |
21 | fun getInstance(builder: Builder? = null): DownloadManager? {
22 | if (instance == null) {
23 | if (builder == null) return null
24 | instance = DownloadManager(builder)
25 | }
26 | return instance!!
27 | }
28 | }
29 |
30 |
31 | /**
32 | * Start download
33 | */
34 | fun download() {
35 | }
36 |
37 | fun cancel() {
38 | }
39 |
40 | class Builder constructor(activity: Activity) {
41 |
42 | fun apkUrl(apkUrl: String): Builder {
43 | return this
44 | }
45 |
46 | fun apkName(apkName: String): Builder {
47 | return this
48 | }
49 |
50 | fun apkVersionCode(apkVersionCode: Int): Builder {
51 | return this
52 | }
53 |
54 | fun apkVersionName(apkVersionName: String): Builder {
55 | return this
56 | }
57 |
58 | fun showNewerToast(showNewerToast: Boolean): Builder {
59 | return this
60 | }
61 |
62 | fun smallIcon(smallIcon: Int): Builder {
63 | return this
64 | }
65 |
66 | fun apkDescription(apkDescription: String): Builder {
67 | return this
68 | }
69 |
70 | fun apkSize(apkSize: String): Builder {
71 | return this
72 | }
73 |
74 | fun apkMD5(apkMD5: String): Builder {
75 | return this
76 | }
77 |
78 | fun httpManager(httpManager: BaseHttpDownloadManager): Builder {
79 | return this
80 | }
81 |
82 | fun notificationChannel(notificationChannel: NotificationChannel): Builder {
83 | return this
84 | }
85 |
86 | fun onButtonClickListener(onButtonClickListener: OnButtonClickListener): Builder {
87 | return this
88 | }
89 |
90 | fun onDownloadListener(onDownloadListener: OnDownloadListener): Builder {
91 | return this
92 | }
93 |
94 | fun showNotification(showNotification: Boolean): Builder {
95 | return this
96 | }
97 |
98 | fun jumpInstallPage(jumpInstallPage: Boolean): Builder {
99 | return this
100 | }
101 |
102 | fun showBgdToast(showBgdToast: Boolean): Builder {
103 | return this
104 | }
105 |
106 | fun forcedUpgrade(forcedUpgrade: Boolean): Builder {
107 | return this
108 | }
109 |
110 | fun notifyId(notifyId: Int): Builder {
111 | return this
112 | }
113 |
114 | fun dialogImage(dialogImage: Int): Builder {
115 | return this
116 | }
117 |
118 | fun dialogButtonColor(dialogButtonColor: Int): Builder {
119 | return this
120 | }
121 |
122 | fun dialogButtonTextColor(dialogButtonTextColor: Int): Builder {
123 | return this
124 | }
125 |
126 | fun dialogProgressBarColor(dialogProgressBarColor: Int): Builder {
127 | return this
128 | }
129 |
130 | fun enableLog(enable: Boolean): Builder {
131 | return this
132 | }
133 |
134 | fun build(): DownloadManager {
135 | return getInstance(this)!!
136 | }
137 | }
138 | }
--------------------------------------------------------------------------------
/appupdate-no-op/src/main/java/com/azhon/appupdate/util/ApkUtil.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.util
2 |
3 | import android.content.Context
4 | import java.io.File
5 |
6 |
7 | /**
8 | * createDate: 2022/4/7 on 17:02
9 | * desc:
10 | *
11 | * @author azhon
12 | */
13 |
14 | class ApkUtil {
15 | companion object {
16 | fun installApk(context: Context, authorities: String, apk: File) {
17 | }
18 |
19 | fun deleteOldApk(context: Context, oldApkPath: String): Boolean {
20 | return true
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/appupdate-no-op/src/test/java/com/azhon/appupdate/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate
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 | }
--------------------------------------------------------------------------------
/appupdate/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/appupdate/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'org.jetbrains.kotlin.android'
3 | apply from: '../maven.gradle'
4 |
5 | android {
6 | compileSdk rootProject.ext.compileSdk
7 | namespace 'com.azhon.appupdate'
8 |
9 | defaultConfig {
10 | minSdk rootProject.ext.minSdk
11 | targetSdk rootProject.ext.targetSdk
12 |
13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
14 | consumerProguardFiles "consumer-rules.pro"
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | compileOptions {
24 | sourceCompatibility JavaVersion.VERSION_1_8
25 | targetCompatibility JavaVersion.VERSION_1_8
26 | }
27 | kotlinOptions {
28 | jvmTarget = '1.8'
29 | }
30 | }
31 |
32 | dependencies {
33 |
34 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1"
35 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1"
36 | implementation 'androidx.core:core-ktx:1.7.0'
37 | implementation 'androidx.appcompat:appcompat:1.4.2'
38 | testImplementation 'junit:junit:4.13.2'
39 | androidTestImplementation 'androidx.test.ext:junit:1.1.3'
40 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
41 | }
--------------------------------------------------------------------------------
/appupdate/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/appupdate/consumer-rules.pro
--------------------------------------------------------------------------------
/appupdate/gradle.properties:
--------------------------------------------------------------------------------
1 | ARTIFACT_ID=appupdate
--------------------------------------------------------------------------------
/appupdate/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
--------------------------------------------------------------------------------
/appupdate/src/androidTest/java/com/azhon/appupdate/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate
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.azhon.appupdate.test", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/appupdate/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
17 |
20 |
21 |
24 |
25 |
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/base/BaseHttpDownloadManager.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.base
2 |
3 | import com.azhon.appupdate.base.bean.DownloadStatus
4 | import kotlinx.coroutines.flow.Flow
5 |
6 | /**
7 | * createDate: 2022/4/7 on 10:24
8 | * desc:
9 | *
10 | * @author azhon
11 | */
12 |
13 | abstract class BaseHttpDownloadManager {
14 | /**
15 | * download apk from apkUrl
16 | *
17 | * @param apkUrl
18 | * @param apkName
19 | */
20 | abstract fun download(apkUrl: String, apkName: String): Flow
21 |
22 | /**
23 | * cancel download apk
24 | */
25 | abstract fun cancel()
26 |
27 | /**
28 | * release memory
29 | */
30 | abstract fun release()
31 | }
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/base/bean/DownloadStatus.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.base.bean
2 |
3 | import java.io.File
4 |
5 |
6 | /**
7 | * createDate: 2022/4/14 on 11:18
8 | * desc:
9 | *
10 | * @author azhon
11 | */
12 |
13 | sealed class DownloadStatus {
14 |
15 | object Start : DownloadStatus()
16 |
17 | data class Downloading(val max: Int, val progress: Int) : DownloadStatus()
18 |
19 | class Done(val apk: File) : DownloadStatus()
20 |
21 | object Cancel : DownloadStatus()
22 |
23 | data class Error(val e: Throwable) : DownloadStatus()
24 | }
25 |
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/config/AppUpdateFileProvider.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.config
2 |
3 | import androidx.core.content.FileProvider
4 |
5 | /**
6 | * createDate: 2022/4/7 on 10:30
7 | * desc:
8 | *
9 | * @author azhon
10 | */
11 |
12 |
13 | class AppUpdateFileProvider : FileProvider()
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/config/Constant.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.config
2 |
3 | /**
4 | * createDate: 2022/4/7 on 10:28
5 | * desc:
6 | *
7 | * @author azhon
8 | */
9 |
10 | object Constant {
11 |
12 | /**
13 | * Http timeout(ms)
14 | */
15 | const val HTTP_TIME_OUT = 30_000
16 |
17 | /**
18 | * Logcat tag
19 | */
20 | const val TAG = "AppUpdate."
21 |
22 | /**
23 | * Apk file extension
24 | */
25 | const val APK_SUFFIX = ".apk"
26 |
27 | /**
28 | * Coroutine Name
29 | */
30 | const val COROUTINE_NAME = "app-update-coroutine"
31 |
32 | /**
33 | * Notification channel id
34 | */
35 | const val DEFAULT_CHANNEL_ID = "appUpdate"
36 |
37 | /**
38 | * Notification id
39 | */
40 | const val DEFAULT_NOTIFY_ID = 1011
41 |
42 | /**
43 | * Notification channel name
44 | */
45 | const val DEFAULT_CHANNEL_NAME = "AppUpdate"
46 |
47 | /**
48 | * Compat Android N file uri
49 | */
50 | var AUTHORITIES: String? = null
51 |
52 | /**
53 | * Apk path
54 | */
55 | var APK_PATH = "/storage/emulated/0/Android/data/%s/cache"
56 | }
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/listener/LifecycleCallbacksAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.listener
2 |
3 | import android.app.Activity
4 | import android.app.Application
5 | import android.os.Bundle
6 |
7 |
8 | /**
9 | * createDate: 2022/4/8 on 11:26
10 | * desc:
11 | *
12 | * @author azhon
13 | */
14 |
15 | abstract class LifecycleCallbacksAdapter : Application.ActivityLifecycleCallbacks {
16 |
17 | override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
18 | }
19 |
20 | override fun onActivityStarted(activity: Activity) {
21 | }
22 |
23 | override fun onActivityResumed(activity: Activity) {
24 | }
25 |
26 | override fun onActivityPaused(activity: Activity) {
27 | }
28 |
29 | override fun onActivityStopped(activity: Activity) {
30 | }
31 |
32 | override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
33 | }
34 |
35 | override fun onActivityDestroyed(activity: Activity) {
36 | }
37 | }
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/listener/OnButtonClickListener.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.listener
2 |
3 |
4 | /**
5 | * createDate: 2022/4/7 on 15:56
6 | * desc:
7 | *
8 | * @author azhon
9 | */
10 |
11 | interface OnButtonClickListener {
12 | companion object {
13 | /**
14 | * click update button
15 | */
16 | const val UPDATE = 0
17 |
18 | /**
19 | * click cancel button
20 | */
21 | const val CANCEL = 1
22 | }
23 |
24 | fun onButtonClick(id: Int)
25 | }
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/listener/OnDownloadListener.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.listener
2 |
3 | import java.io.File
4 |
5 | /**
6 | * createDate: 2022/4/7 on 10:27
7 | * desc:
8 | *
9 | * @author azhon
10 | */
11 |
12 | interface OnDownloadListener {
13 | /**
14 | * start download
15 | */
16 | fun start()
17 |
18 | /**
19 | *
20 | * @param max file length
21 | * @param progress downloaded file size
22 | */
23 | fun downloading(max: Int, progress: Int)
24 |
25 | /**
26 | * @param apk
27 | */
28 | fun done(apk: File)
29 |
30 | /**
31 | * cancel download
32 | */
33 | fun cancel()
34 |
35 | /**
36 | *
37 | * @param e
38 | */
39 | fun error(e: Throwable)
40 | }
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/listener/OnDownloadListenerAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.listener
2 |
3 | import java.io.File
4 |
5 |
6 | /**
7 | * createDate: 2022/4/8 on 10:58
8 | * desc:
9 | *
10 | * @author azhon
11 | */
12 |
13 | abstract class OnDownloadListenerAdapter : OnDownloadListener {
14 | override fun start() {
15 | }
16 |
17 | override fun downloading(max: Int, progress: Int) {
18 | }
19 |
20 | override fun done(apk: File) {
21 | }
22 |
23 | override fun cancel() {
24 | }
25 |
26 | override fun error(e: Throwable) {
27 | }
28 | }
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/manager/DownloadManager.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.manager
2 |
3 | import android.app.Activity
4 | import android.app.Application
5 | import android.app.NotificationChannel
6 | import android.content.Intent
7 | import android.widget.Toast
8 | import com.azhon.appupdate.R
9 | import com.azhon.appupdate.base.BaseHttpDownloadManager
10 | import com.azhon.appupdate.config.Constant
11 | import com.azhon.appupdate.listener.LifecycleCallbacksAdapter
12 | import com.azhon.appupdate.listener.OnButtonClickListener
13 | import com.azhon.appupdate.listener.OnDownloadListener
14 | import com.azhon.appupdate.service.DownloadService
15 | import com.azhon.appupdate.util.ApkUtil
16 | import com.azhon.appupdate.util.LogUtil
17 | import com.azhon.appupdate.view.UpdateDialogActivity
18 | import java.io.Serializable
19 |
20 | /**
21 | * createDate: 2022/4/7 on 10:36
22 | * desc:
23 | *
24 | * @author azhon
25 | */
26 | class DownloadManager private constructor(builder: Builder) : Serializable {
27 |
28 | companion object {
29 | private const val TAG = "DownloadManager"
30 | private var instance: DownloadManager? = null
31 |
32 | internal fun getInstance(builder: Builder? = null): DownloadManager? {
33 | if (instance == null) {
34 | if (builder == null) return null
35 | instance = DownloadManager(builder)
36 | }
37 | return instance!!
38 | }
39 | }
40 |
41 | private var application: Application = builder.application
42 | private var apkVersionCode: Int
43 | private var showNewerToast: Boolean
44 | internal var contextClsName: String = builder.contextClsName
45 | internal var apkUrl: String
46 | internal var apkName: String
47 | internal var apkVersionName: String
48 | internal var downloadPath: String
49 | internal var smallIcon: Int
50 | internal var apkDescription: String
51 | internal var apkSize: String
52 | internal var apkMD5: String
53 | internal var httpManager: BaseHttpDownloadManager?
54 | internal var notificationChannel: NotificationChannel?
55 | internal var onDownloadListeners: MutableList
56 | internal var onButtonClickListener: OnButtonClickListener?
57 | internal var showNotification: Boolean
58 | internal var jumpInstallPage: Boolean
59 | internal var showBgdToast: Boolean
60 | internal var forcedUpgrade: Boolean
61 | internal var notifyId: Int
62 | internal var dialogImage: Int
63 | internal var dialogButtonColor: Int
64 | internal var dialogButtonTextColor: Int
65 | internal var dialogProgressBarColor: Int
66 | var downloadState: Boolean = false
67 |
68 |
69 | init {
70 | apkUrl = builder.apkUrl
71 | apkName = builder.apkName
72 | apkVersionCode = builder.apkVersionCode
73 | apkVersionName = builder.apkVersionName
74 | downloadPath =
75 | builder.downloadPath ?: String.format(Constant.APK_PATH, application.packageName)
76 | showNewerToast = builder.showNewerToast
77 | smallIcon = builder.smallIcon
78 | apkDescription = builder.apkDescription
79 | apkSize = builder.apkSize
80 | apkMD5 = builder.apkMD5
81 | httpManager = builder.httpManager
82 | notificationChannel = builder.notificationChannel
83 | onDownloadListeners = builder.onDownloadListeners
84 | onButtonClickListener = builder.onButtonClickListener
85 | showNotification = builder.showNotification
86 | jumpInstallPage = builder.jumpInstallPage
87 | showBgdToast = builder.showBgdToast
88 | forcedUpgrade = builder.forcedUpgrade
89 | notifyId = builder.notifyId
90 | dialogImage = builder.dialogImage
91 | dialogButtonColor = builder.dialogButtonColor
92 | dialogButtonTextColor = builder.dialogButtonTextColor
93 | dialogProgressBarColor = builder.dialogProgressBarColor
94 | // Fix memory leak
95 | application.registerActivityLifecycleCallbacks(object : LifecycleCallbacksAdapter() {
96 | override fun onActivityDestroyed(activity: Activity) {
97 | super.onActivityDestroyed(activity)
98 | if (contextClsName == activity.javaClass.name) {
99 | clearListener()
100 | }
101 | }
102 | })
103 | }
104 |
105 | /**
106 | * Start download
107 | */
108 | fun download() {
109 | if (!checkParams()) {
110 | return
111 | }
112 | if (checkVersionCode()) {
113 | application.startService(Intent(application, DownloadService::class.java))
114 | } else {
115 | if (apkVersionCode > ApkUtil.getVersionCode(application)) {
116 | application.startActivity(
117 | Intent(application, UpdateDialogActivity::class.java)
118 | .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
119 | )
120 | } else {
121 | if (showNewerToast) {
122 | Toast.makeText(
123 | application, R.string.app_update_latest_version, Toast.LENGTH_SHORT
124 | ).show()
125 | }
126 | LogUtil.d(TAG, application.resources.getString(R.string.app_update_latest_version))
127 | }
128 | }
129 |
130 | }
131 |
132 | private fun checkParams(): Boolean {
133 | if (apkUrl.isEmpty()) {
134 | LogUtil.e(TAG, "apkUrl can not be empty!")
135 | return false
136 | }
137 | if (apkName.isEmpty()) {
138 | LogUtil.e(TAG, "apkName can not be empty!")
139 | return false
140 | }
141 | if (!apkName.endsWith(Constant.APK_SUFFIX)) {
142 | LogUtil.e(TAG, "apkName must endsWith .apk!")
143 | return false
144 | }
145 | if (smallIcon == -1) {
146 | LogUtil.e(TAG, "smallIcon can not be empty!");
147 | return false
148 | }
149 | Constant.AUTHORITIES = "${application.packageName}.fileProvider"
150 | return true
151 | }
152 |
153 | /**
154 | * Check the set apkVersionCode if it is not the default then use the built-in dialog
155 | * If it is the default value Int.MIN_VALUE, directly start the service download
156 | */
157 | private fun checkVersionCode(): Boolean {
158 | if (apkVersionCode == Int.MIN_VALUE) {
159 | return true
160 | }
161 | if (apkDescription.isEmpty()) {
162 | LogUtil.e(TAG, "apkDescription can not be empty!")
163 | }
164 | return false
165 | }
166 |
167 | fun cancel() {
168 | httpManager?.cancel()
169 | }
170 |
171 | /**
172 | * release objects
173 | * Call this method when you need to destroy the previous download and re-download,
174 | * otherwise don't use it.
175 | */
176 | fun release() {
177 | httpManager?.release()
178 | clearListener()
179 | instance = null
180 | }
181 |
182 | private fun clearListener() {
183 | onButtonClickListener = null
184 | onDownloadListeners.clear()
185 | }
186 |
187 | class Builder constructor(activity: Activity) {
188 |
189 | /**
190 | * library context
191 | */
192 | internal var application: Application = activity.application
193 |
194 | /**
195 | * Fix the memory leak caused by Activity destroy
196 | */
197 | internal var contextClsName: String = activity.javaClass.name
198 |
199 | /**
200 | * Apk download url
201 | */
202 | internal var apkUrl = ""
203 |
204 | /**
205 | * Apk file name on disk
206 | */
207 | internal var apkName = ""
208 |
209 | /**
210 | * The apk versionCode that needs to be downloaded
211 | */
212 | internal var apkVersionCode = Int.MIN_VALUE
213 |
214 | /**
215 | * The versionName of the dialog reality
216 | */
217 | internal var apkVersionName = ""
218 |
219 | /**
220 | * The file path where the Apk is saved
221 | * eg: /storage/emulated/0/Android/data/ your packageName /cache
222 | */
223 | internal var downloadPath = application.externalCacheDir?.path
224 |
225 | /**
226 | * whether to tip to user "Currently the latest version!"
227 | */
228 | internal var showNewerToast = false
229 |
230 | /**
231 | * Notification icon resource
232 | */
233 | internal var smallIcon = -1
234 |
235 | /**
236 | * New version description information
237 | */
238 | internal var apkDescription = ""
239 |
240 | /**
241 | * Apk Size,Unit MB
242 | */
243 | internal var apkSize = ""
244 |
245 | /**
246 | * Apk md5 file verification(32-bit) verification repeated download
247 | */
248 | internal var apkMD5 = ""
249 |
250 | /**
251 | * Apk download manager
252 | */
253 | internal var httpManager: BaseHttpDownloadManager? = null
254 |
255 | /**
256 | * The following are unimportant filed
257 | */
258 |
259 | /**
260 | * adapter above Android O notification
261 | */
262 | internal var notificationChannel: NotificationChannel? = null
263 |
264 | /**
265 | * download listeners
266 | */
267 | internal var onDownloadListeners = mutableListOf()
268 |
269 | /**
270 | * dialog button click listener
271 | */
272 | internal var onButtonClickListener: OnButtonClickListener? = null
273 |
274 | /**
275 | * Whether to show the progress of the notification
276 | */
277 | internal var showNotification = true
278 |
279 | /**
280 | * Whether the installation page will pop up automatically after the download is complete
281 | */
282 | internal var jumpInstallPage = true
283 |
284 | /**
285 | * Does the download start tip "Downloading a new version in the background..."
286 | */
287 | internal var showBgdToast = true
288 |
289 | /**
290 | * Whether to force an upgrade
291 | */
292 | internal var forcedUpgrade = false
293 |
294 | /**
295 | * Notification id
296 | */
297 | internal var notifyId = Constant.DEFAULT_NOTIFY_ID
298 |
299 | /**
300 | * dialog background Image resource
301 | */
302 | internal var dialogImage = -1
303 |
304 | /**
305 | * dialog button background color
306 | */
307 | internal var dialogButtonColor = -1
308 |
309 | /**
310 | * dialog button text color
311 | */
312 | internal var dialogButtonTextColor = -1
313 |
314 | /**
315 | * dialog progress bar color and progress-text color
316 | */
317 | internal var dialogProgressBarColor = -1
318 |
319 |
320 | fun apkUrl(apkUrl: String): Builder {
321 | this.apkUrl = apkUrl
322 | return this
323 | }
324 |
325 | fun apkName(apkName: String): Builder {
326 | this.apkName = apkName
327 | return this
328 | }
329 |
330 | fun apkVersionCode(apkVersionCode: Int): Builder {
331 | this.apkVersionCode = apkVersionCode
332 | return this
333 | }
334 |
335 | fun apkVersionName(apkVersionName: String): Builder {
336 | this.apkVersionName = apkVersionName
337 | return this
338 | }
339 |
340 | fun showNewerToast(showNewerToast: Boolean): Builder {
341 | this.showNewerToast = showNewerToast
342 | return this
343 | }
344 |
345 | fun smallIcon(smallIcon: Int): Builder {
346 | this.smallIcon = smallIcon
347 | return this
348 | }
349 |
350 | fun apkDescription(apkDescription: String): Builder {
351 | this.apkDescription = apkDescription
352 | return this
353 | }
354 |
355 | fun apkSize(apkSize: String): Builder {
356 | this.apkSize = apkSize
357 | return this
358 | }
359 |
360 | fun apkMD5(apkMD5: String): Builder {
361 | this.apkMD5 = apkMD5
362 | return this
363 | }
364 |
365 | fun httpManager(httpManager: BaseHttpDownloadManager): Builder {
366 | this.httpManager = httpManager
367 | return this
368 | }
369 |
370 | fun notificationChannel(notificationChannel: NotificationChannel): Builder {
371 | this.notificationChannel = notificationChannel
372 | return this
373 | }
374 |
375 | fun onButtonClickListener(onButtonClickListener: OnButtonClickListener): Builder {
376 | this.onButtonClickListener = onButtonClickListener
377 | return this
378 | }
379 |
380 | fun onDownloadListener(onDownloadListener: OnDownloadListener): Builder {
381 | this.onDownloadListeners.add(onDownloadListener)
382 | return this
383 | }
384 |
385 | fun showNotification(showNotification: Boolean): Builder {
386 | this.showNotification = showNotification
387 | return this
388 | }
389 |
390 | fun jumpInstallPage(jumpInstallPage: Boolean): Builder {
391 | this.jumpInstallPage = jumpInstallPage
392 | return this
393 | }
394 |
395 | fun showBgdToast(showBgdToast: Boolean): Builder {
396 | this.showBgdToast = showBgdToast
397 | return this
398 | }
399 |
400 | fun forcedUpgrade(forcedUpgrade: Boolean): Builder {
401 | this.forcedUpgrade = forcedUpgrade
402 | return this
403 | }
404 |
405 | fun notifyId(notifyId: Int): Builder {
406 | this.notifyId = notifyId
407 | return this
408 | }
409 |
410 | fun dialogImage(dialogImage: Int): Builder {
411 | this.dialogImage = dialogImage
412 | return this
413 | }
414 |
415 | fun dialogButtonColor(dialogButtonColor: Int): Builder {
416 | this.dialogButtonColor = dialogButtonColor
417 | return this
418 | }
419 |
420 | fun dialogButtonTextColor(dialogButtonTextColor: Int): Builder {
421 | this.dialogButtonTextColor = dialogButtonTextColor
422 | return this
423 | }
424 |
425 | fun dialogProgressBarColor(dialogProgressBarColor: Int): Builder {
426 | this.dialogProgressBarColor = dialogProgressBarColor
427 | return this
428 | }
429 |
430 | fun enableLog(enable: Boolean): Builder {
431 | LogUtil.enable(enable)
432 | return this
433 | }
434 |
435 | fun build(): DownloadManager {
436 | return getInstance(this)!!
437 | }
438 | }
439 | }
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/manager/HttpDownloadManager.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.manager
2 |
3 | import com.azhon.appupdate.base.BaseHttpDownloadManager
4 | import com.azhon.appupdate.base.bean.DownloadStatus
5 | import com.azhon.appupdate.config.Constant
6 | import com.azhon.appupdate.util.LogUtil
7 | import kotlinx.coroutines.*
8 | import kotlinx.coroutines.flow.*
9 | import java.io.File
10 | import java.io.FileOutputStream
11 | import java.net.HttpURLConnection
12 | import java.net.SocketTimeoutException
13 | import java.net.URL
14 | import java.security.SecureRandom
15 | import java.security.cert.X509Certificate
16 | import javax.net.ssl.HttpsURLConnection
17 | import javax.net.ssl.SSLContext
18 | import javax.net.ssl.TrustManager
19 | import javax.net.ssl.X509TrustManager
20 |
21 |
22 | /**
23 | * createDate: 2022/4/7 on 14:29
24 | * desc:
25 | *
26 | * @author azhon
27 | */
28 |
29 | @Suppress("BlockingMethodInNonBlockingContext")
30 | class HttpDownloadManager(private val path: String) : BaseHttpDownloadManager() {
31 | companion object {
32 | private const val TAG = "HttpDownloadManager"
33 | }
34 |
35 | private var shutdown: Boolean = false
36 |
37 | override fun download(apkUrl: String, apkName: String): Flow {
38 | trustAllHosts()
39 | shutdown = false
40 | File(path, apkName).let {
41 | if (it.exists()) it.delete()
42 | }
43 | return flow {
44 | emit(DownloadStatus.Start)
45 | connectToDownload(apkUrl, apkName, this)
46 | }.catch {
47 | emit(DownloadStatus.Error(it))
48 | }.flowOn(Dispatchers.IO)
49 | }
50 |
51 | private suspend fun connectToDownload(
52 | apkUrl: String, apkName: String, flow: FlowCollector
53 | ) {
54 | val con = URL(apkUrl).openConnection() as HttpURLConnection
55 | con.apply {
56 | requestMethod = "GET"
57 | readTimeout = Constant.HTTP_TIME_OUT
58 | connectTimeout = Constant.HTTP_TIME_OUT
59 | setRequestProperty("Accept-Encoding", "identity")
60 | }
61 | if (con.responseCode == HttpURLConnection.HTTP_OK) {
62 | val inStream = con.inputStream
63 | val length = con.contentLength
64 | var len: Int
65 | var progress = 0
66 | val buffer = ByteArray(1024 * 2)
67 | val file = File(path, apkName)
68 | FileOutputStream(file).use { out ->
69 | while (inStream.read(buffer).also { len = it } != -1 && !shutdown) {
70 | out.write(buffer, 0, len)
71 | progress += len
72 | flow.emit(DownloadStatus.Downloading(length, progress))
73 | }
74 | out.flush()
75 | }
76 | inStream.close()
77 | if (shutdown) {
78 | flow.emit(DownloadStatus.Cancel)
79 | } else {
80 | flow.emit(DownloadStatus.Done(file))
81 | }
82 | } else if (con.responseCode == HttpURLConnection.HTTP_MOVED_PERM
83 | || con.responseCode == HttpURLConnection.HTTP_MOVED_TEMP
84 | ) {
85 | con.disconnect()
86 | val locationUrl = con.getHeaderField("Location")
87 | LogUtil.d(
88 | TAG,
89 | "The current url is the redirect Url, the redirected url is $locationUrl"
90 | )
91 | connectToDownload(locationUrl, apkName, flow)
92 | } else {
93 | val e = SocketTimeoutException("Error: Http response code = ${con.responseCode}")
94 | flow.emit(DownloadStatus.Error(e))
95 | }
96 | con.disconnect()
97 | }
98 |
99 | /**
100 | * fix https url (SSLHandshakeException) exception
101 | */
102 | private fun trustAllHosts() {
103 | val manager: TrustManager = object : X509TrustManager {
104 | override fun getAcceptedIssuers(): Array {
105 | return arrayOf()
106 | }
107 |
108 | override fun checkClientTrusted(chain: Array?, authType: String?) {
109 | LogUtil.d(TAG, "checkClientTrusted")
110 | }
111 |
112 | override fun checkServerTrusted(chain: Array?, authType: String?) {
113 | LogUtil.d(TAG, "checkServerTrusted")
114 | }
115 | }
116 | try {
117 | val sslContext = SSLContext.getInstance("TLS")
118 | sslContext.init(null, arrayOf(manager), SecureRandom())
119 | HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.socketFactory)
120 | } catch (e: Exception) {
121 | LogUtil.e(TAG, "trustAllHosts error: $e")
122 | }
123 | }
124 |
125 | override fun cancel() {
126 | shutdown = true
127 | }
128 |
129 | override fun release() {
130 | cancel()
131 | }
132 | }
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/service/DownloadService.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.service
2 |
3 | import android.app.Service
4 | import android.content.Intent
5 | import android.os.Build
6 | import android.os.IBinder
7 | import android.widget.Toast
8 | import com.azhon.appupdate.R
9 | import com.azhon.appupdate.base.bean.DownloadStatus
10 | import com.azhon.appupdate.config.Constant
11 | import com.azhon.appupdate.listener.OnDownloadListener
12 | import com.azhon.appupdate.manager.DownloadManager
13 | import com.azhon.appupdate.manager.HttpDownloadManager
14 | import com.azhon.appupdate.util.ApkUtil
15 | import com.azhon.appupdate.util.FileUtil
16 | import com.azhon.appupdate.util.LogUtil
17 | import com.azhon.appupdate.util.NotificationUtil
18 | import kotlinx.coroutines.*
19 | import java.io.File
20 |
21 | /**
22 | * createDate: 2022/4/7 on 11:42
23 | * desc:
24 | *
25 | * @author azhon
26 | */
27 |
28 | class DownloadService : Service(), OnDownloadListener {
29 | companion object {
30 | private const val TAG = "DownloadService"
31 | }
32 |
33 | private lateinit var manager: DownloadManager
34 | private var lastProgress = 0
35 |
36 | override fun onBind(intent: Intent?): IBinder? = null
37 |
38 | override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
39 | if (intent == null) {
40 | return START_NOT_STICKY
41 | }
42 | init()
43 | return super.onStartCommand(intent, flags, startId)
44 | }
45 |
46 | private fun init() {
47 | val tempManager = DownloadManager.getInstance()
48 | if (tempManager == null) {
49 | LogUtil.e(TAG, "An exception occurred by DownloadManager=null,please check your code!")
50 | return
51 | }
52 | manager = tempManager
53 | FileUtil.createDirDirectory(manager.downloadPath)
54 |
55 | val enable = NotificationUtil.notificationEnable(this@DownloadService)
56 | LogUtil.d(
57 | TAG,
58 | if (enable) "Notification switch status: opened" else "Notification switch status: closed"
59 | )
60 | if (checkApkMd5()) {
61 | LogUtil.d(TAG, "Apk already exist and install it directly.")
62 | //install apk
63 | done(File(manager.downloadPath, manager.apkName))
64 | } else {
65 | LogUtil.d(TAG, "Apk don't exist will start download.")
66 | download()
67 | }
68 | }
69 |
70 | /**
71 | * Check whether the Apk has been downloaded, don't download again
72 | */
73 | private fun checkApkMd5(): Boolean {
74 | if (manager.apkMD5.isBlank()) {
75 | return false
76 | }
77 | val file = File(manager.downloadPath, manager.apkName)
78 | if (file.exists()) {
79 | return FileUtil.md5(file).equals(manager.apkMD5, ignoreCase = true)
80 | }
81 | return false
82 | }
83 |
84 | @Synchronized
85 | private fun download() {
86 | if (manager.downloadState) {
87 | LogUtil.e(TAG, "Currently downloading, please don't download again!")
88 | return
89 | }
90 | if (manager.httpManager == null) {
91 | manager.httpManager = HttpDownloadManager(manager.downloadPath)
92 | }
93 | GlobalScope.launch(Dispatchers.Main + CoroutineName(Constant.COROUTINE_NAME)) {
94 | manager.httpManager!!.download(manager.apkUrl, manager.apkName)
95 | .collect {
96 | when (it) {
97 | is DownloadStatus.Start -> start()
98 | is DownloadStatus.Downloading -> downloading(it.max, it.progress)
99 | is DownloadStatus.Done -> done(it.apk)
100 | is DownloadStatus.Cancel -> this@DownloadService.cancel()
101 | is DownloadStatus.Error -> error(it.e)
102 | }
103 | }
104 | }
105 | manager.downloadState = true
106 | }
107 |
108 | override fun start() {
109 | LogUtil.i(TAG, "download start")
110 | if (manager.showBgdToast) {
111 | Toast.makeText(this, R.string.app_update_background_downloading, Toast.LENGTH_SHORT)
112 | .show()
113 | }
114 | if (manager.showNotification) {
115 | NotificationUtil.showNotification(
116 | this@DownloadService, manager.smallIcon,
117 | resources.getString(R.string.app_update_start_download),
118 | resources.getString(R.string.app_update_start_download_hint)
119 | )
120 | }
121 | manager.onDownloadListeners.forEach { it.start() }
122 | }
123 |
124 | override fun downloading(max: Int, progress: Int) {
125 | if (manager.showNotification) {
126 | val curr = (progress / max.toDouble() * 100.0).toInt()
127 | if (curr == lastProgress) return
128 | LogUtil.i(TAG, "downloading max: $max --- progress: $progress")
129 | lastProgress = curr
130 | val content = if (curr < 0) "" else "$curr%"
131 | NotificationUtil.showProgressNotification(
132 | this@DownloadService, manager.smallIcon,
133 | resources.getString(R.string.app_update_start_downloading),
134 | content, if (max == -1) -1 else 100, curr
135 | )
136 | }
137 | manager.onDownloadListeners.forEach { it.downloading(max, progress) }
138 | }
139 |
140 | override fun done(apk: File) {
141 | LogUtil.d(TAG, "apk downloaded to ${apk.path}")
142 | manager.downloadState = false
143 | //If it is android Q (api=29) and above, (showNotification=false) will also send a
144 | // download completion notification
145 | if (manager.showNotification || Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
146 | NotificationUtil.showDoneNotification(
147 | this@DownloadService, manager.smallIcon,
148 | resources.getString(R.string.app_update_download_completed),
149 | resources.getString(R.string.app_update_click_hint),
150 | Constant.AUTHORITIES!!, apk
151 | )
152 | }
153 | if (manager.jumpInstallPage) {
154 | ApkUtil.installApk(this@DownloadService, Constant.AUTHORITIES!!, apk)
155 | }
156 | manager.onDownloadListeners.forEach { it.done(apk) }
157 |
158 | // release objects
159 | releaseResources()
160 | }
161 |
162 | override fun cancel() {
163 | LogUtil.i(TAG, "download cancel")
164 | manager.downloadState = false
165 | if (manager.showNotification) {
166 | NotificationUtil.cancelNotification(this@DownloadService)
167 | }
168 | manager.onDownloadListeners.forEach { it.cancel() }
169 | }
170 |
171 | override fun error(e: Throwable) {
172 | LogUtil.e(TAG, "download error: $e")
173 | manager.downloadState = false
174 | if (manager.showNotification) {
175 | NotificationUtil.showErrorNotification(
176 | this@DownloadService, manager.smallIcon,
177 | resources.getString(R.string.app_update_download_error),
178 | resources.getString(R.string.app_update_continue_downloading),
179 | )
180 | }
181 | manager.onDownloadListeners.forEach { it.error(e) }
182 | }
183 |
184 | private fun releaseResources() {
185 | manager.release()
186 | stopSelf()
187 | }
188 | }
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/util/ApkUtil.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.util
2 |
3 | import android.content.Context
4 | import android.content.Intent
5 | import android.content.pm.PackageManager
6 | import android.net.Uri
7 | import android.os.Build
8 | import android.os.PatternMatcher
9 | import androidx.core.content.FileProvider
10 | import java.io.File
11 |
12 |
13 | /**
14 | * createDate: 2022/4/7 on 17:02
15 | * desc:
16 | *
17 | * @author azhon
18 | */
19 |
20 | class ApkUtil {
21 | companion object {
22 | /**
23 | * install package form file
24 | */
25 | fun installApk(context: Context, authorities: String, apk: File) {
26 | context.startActivity(createInstallIntent(context, authorities, apk))
27 | }
28 |
29 | fun createInstallIntent(context: Context, authorities: String, apk: File): Intent {
30 | val intent = Intent().apply {
31 | action = Intent.ACTION_VIEW
32 | addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
33 | addCategory(Intent.CATEGORY_DEFAULT)
34 | }
35 | val uri: Uri
36 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
37 | uri = FileProvider.getUriForFile(context, authorities, apk)
38 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
39 | } else {
40 | uri = Uri.fromFile(apk)
41 | }
42 | intent.setDataAndType(uri, "application/vnd.android.package-archive")
43 | return intent
44 | }
45 |
46 | fun getVersionCode(context: Context): Long {
47 | val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
48 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
49 | packageInfo.longVersionCode
50 | } else {
51 | return packageInfo.versionCode.toLong()
52 | }
53 | }
54 |
55 | fun deleteOldApk(context: Context, oldApkPath: String): Boolean {
56 | val curVersionCode = getVersionCode(context)
57 | try {
58 | val apk = File(oldApkPath)
59 | if (apk.exists()) {
60 | val oldVersionCode = getVersionCodeByPath(context, oldApkPath)
61 | if (curVersionCode > oldVersionCode) {
62 | return apk.delete()
63 | }
64 | }
65 | } catch (e: Exception) {
66 | }
67 | return false
68 | }
69 |
70 | private fun getVersionCodeByPath(context: Context, path: String): Long {
71 | val packageInfo =
72 | context.packageManager.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES)
73 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
74 | packageInfo?.longVersionCode ?: 1
75 | } else {
76 | return packageInfo?.versionCode?.toLong() ?: 1
77 | }
78 | }
79 | }
80 | }
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/util/DensityUtil.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.util
2 |
3 | import android.content.Context
4 |
5 |
6 | /**
7 | * createDate: 2022/4/7 on 17:52
8 | * desc:
9 | *
10 | * @author azhon
11 | */
12 |
13 | class DensityUtil {
14 | companion object {
15 | fun dip2px(context: Context, dpValue: Float): Float {
16 | val scale = context.resources.displayMetrics.density
17 | return dpValue * scale + 0.5f
18 | }
19 | }
20 | }
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/util/FileUtil.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.util
2 |
3 | import java.io.File
4 | import java.io.FileInputStream
5 | import java.math.BigInteger
6 | import java.security.MessageDigest
7 |
8 | /**
9 | * createDate: 2022/4/7 on 11:52
10 | * desc:
11 | *
12 | * @author azhon
13 | */
14 |
15 | class FileUtil {
16 | companion object {
17 | fun createDirDirectory(path: String) {
18 | File(path).let {
19 | if (!it.exists()) {
20 | it.mkdirs()
21 | }
22 | }
23 | }
24 |
25 | fun md5(file: File): String {
26 | try {
27 | val buffer = ByteArray(1024)
28 | var len: Int
29 | val digest = MessageDigest.getInstance("MD5")
30 | val inStream = FileInputStream(file)
31 | while (inStream.read(buffer).also { len = it } != -1) {
32 | digest.update(buffer, 0, len)
33 | }
34 | inStream.close()
35 | val bigInt = BigInteger(1, digest.digest())
36 | return bigInt.toString(16).padStart(32, '0').uppercase()
37 | } catch (e: Exception) {
38 | e.printStackTrace()
39 | }
40 | return ""
41 | }
42 | }
43 | }
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/util/LogUtil.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.util
2 |
3 | import android.util.Log
4 | import com.azhon.appupdate.config.Constant
5 |
6 |
7 | /**
8 | * createDate: 2022/4/7 on 11:23
9 | * desc:
10 | *
11 | * @author azhon
12 | */
13 |
14 | class LogUtil {
15 |
16 | companion object {
17 | var b = true
18 |
19 | fun enable(enable: Boolean) {
20 | b = enable
21 | }
22 |
23 | fun e(tag: String, msg: String) {
24 | if (b) Log.e(Constant.TAG + tag, msg)
25 | }
26 |
27 | fun d(tag: String, msg: String) {
28 | if (b) Log.d(Constant.TAG + tag, msg)
29 | }
30 |
31 | fun i(tag: String, msg: String) {
32 | if (b) Log.i(Constant.TAG + tag, msg)
33 | }
34 |
35 | }
36 | }
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/util/NotificationUtil.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.util
2 |
3 | import android.app.Notification
4 | import android.app.NotificationChannel
5 | import android.app.NotificationManager
6 | import android.app.PendingIntent
7 | import android.content.Context
8 | import android.content.Intent
9 | import android.os.Build
10 | import androidx.annotation.RequiresApi
11 | import androidx.core.app.NotificationCompat
12 | import androidx.core.app.NotificationManagerCompat
13 | import com.azhon.appupdate.config.Constant
14 | import com.azhon.appupdate.manager.DownloadManager
15 | import com.azhon.appupdate.service.DownloadService
16 | import java.io.File
17 |
18 | /**
19 | * createDate: 2022/4/7 on 13:36
20 | * desc:
21 | *
22 | * @author azhon
23 | */
24 | class NotificationUtil {
25 | companion object {
26 |
27 | fun notificationEnable(context: Context): Boolean {
28 | return NotificationManagerCompat.from(context).areNotificationsEnabled()
29 | }
30 |
31 | @RequiresApi(api = Build.VERSION_CODES.O)
32 | private fun getNotificationChannelId(): String {
33 | val channel = DownloadManager.getInstance()?.notificationChannel
34 | return if (channel == null) {
35 | Constant.DEFAULT_CHANNEL_ID
36 | } else {
37 | channel.id
38 | }
39 | }
40 |
41 | private fun builderNotification(
42 | context: Context, icon: Int, title: String, content: String
43 | ): NotificationCompat.Builder {
44 | var channelId = ""
45 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
46 | channelId = getNotificationChannelId()
47 | }
48 | return NotificationCompat.Builder(context, channelId)
49 | .setSmallIcon(icon)
50 | .setContentTitle(title)
51 | .setWhen(System.currentTimeMillis())
52 | .setContentText(content)
53 | .setAutoCancel(false)
54 | .setOngoing(true)
55 | }
56 |
57 | fun showNotification(context: Context, icon: Int, title: String, content: String) {
58 | val manager =
59 | context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
60 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
61 | afterO(manager)
62 | }
63 | val notify = builderNotification(context, icon, title, content)
64 | .setDefaults(Notification.DEFAULT_SOUND)
65 | .build()
66 | manager.notify(
67 | DownloadManager.getInstance()?.notifyId ?: Constant.DEFAULT_NOTIFY_ID,
68 | notify
69 | )
70 | }
71 |
72 | /**
73 | * send a downloading Notification
74 | */
75 | fun showProgressNotification(
76 | context: Context, icon: Int, title: String, content: String, max: Int, progress: Int
77 | ) {
78 | val manager =
79 | context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
80 | val notify = builderNotification(context, icon, title, content)
81 | .setProgress(max, progress, max == -1).build()
82 | manager.notify(
83 | DownloadManager.getInstance()?.notifyId ?: Constant.DEFAULT_NOTIFY_ID,
84 | notify
85 | )
86 | }
87 |
88 | /**
89 | * send a downloaded Notification
90 | */
91 | fun showDoneNotification(
92 | context: Context, icon: Int, title: String, content: String,
93 | authorities: String, apk: File
94 | ) {
95 | val manager =
96 | context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
97 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
98 | afterO(manager)
99 | }
100 | manager.cancel(DownloadManager.getInstance()?.notifyId ?: Constant.DEFAULT_NOTIFY_ID)
101 | val intent = ApkUtil.createInstallIntent(context, authorities, apk)
102 | val pi = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
103 | PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
104 | } else {
105 | PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT)
106 | }
107 | val notify = builderNotification(context, icon, title, content)
108 | .setContentIntent(pi)
109 | .build()
110 | notify.flags = notify.flags or Notification.FLAG_AUTO_CANCEL
111 | manager.notify(
112 | DownloadManager.getInstance()?.notifyId ?: Constant.DEFAULT_NOTIFY_ID,
113 | notify
114 | )
115 | }
116 |
117 | /**
118 | * send a error Notification
119 | */
120 | fun showErrorNotification(
121 | context: Context, icon: Int, title: String, content: String
122 | ) {
123 | val manager =
124 | context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
125 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
126 | afterO(manager)
127 | }
128 | val intent = Intent(context, DownloadService::class.java)
129 | val pi = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
130 | PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
131 | } else {
132 | PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_ONE_SHOT)
133 | }
134 | val notify = builderNotification(context, icon, title, content)
135 | .setAutoCancel(true)
136 | .setOngoing(false)
137 | .setContentIntent(pi)
138 | .setDefaults(Notification.DEFAULT_SOUND)
139 | .build()
140 | manager.notify(
141 | DownloadManager.getInstance()?.notifyId ?: Constant.DEFAULT_NOTIFY_ID,
142 | notify
143 | )
144 | }
145 |
146 | /**
147 | * cancel Notification by id
148 | */
149 | fun cancelNotification(context: Context) {
150 | val manager =
151 | context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
152 | manager.cancel(DownloadManager.getInstance()?.notifyId ?: Constant.DEFAULT_NOTIFY_ID)
153 |
154 | }
155 |
156 | @RequiresApi(api = Build.VERSION_CODES.O)
157 | private fun afterO(manager: NotificationManager) {
158 | var channel = DownloadManager.getInstance()?.notificationChannel
159 | if (channel == null) {
160 | channel = NotificationChannel(
161 | Constant.DEFAULT_CHANNEL_ID, Constant.DEFAULT_CHANNEL_NAME,
162 | NotificationManager.IMPORTANCE_LOW
163 | ).apply {
164 | enableLights(true)
165 | setShowBadge(true)
166 | }
167 | }
168 | manager.createNotificationChannel(channel)
169 | }
170 | }
171 | }
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/view/NumberProgressBar.java:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.view;
2 |
3 | import android.content.Context;
4 | import android.content.res.TypedArray;
5 | import android.graphics.Canvas;
6 | import android.graphics.Color;
7 | import android.graphics.Paint;
8 | import android.graphics.RectF;
9 | import android.os.Bundle;
10 | import android.os.Parcelable;
11 | import android.util.AttributeSet;
12 | import android.view.View;
13 |
14 | import com.azhon.appupdate.R;
15 |
16 |
17 | /**
18 | * Created by daimajia on 14-4-30.
19 | *
20 | */
21 | public class NumberProgressBar extends View {
22 |
23 | private int mMaxProgress = 100;
24 |
25 | /**
26 | * Current progress, can not exceed the max progress.
27 | */
28 | private int mCurrentProgress = 0;
29 |
30 | /**
31 | * The progress area bar color.
32 | */
33 | private int mReachedBarColor;
34 |
35 | /**
36 | * The bar unreached area color.
37 | */
38 | private int mUnreachedBarColor;
39 |
40 | /**
41 | * The progress text color.
42 | */
43 | private int mTextColor;
44 |
45 | /**
46 | * The progress text size.
47 | */
48 | private float mTextSize;
49 |
50 | /**
51 | * The height of the reached area.
52 | */
53 | private float mReachedBarHeight;
54 |
55 | /**
56 | * The height of the unreached area.
57 | */
58 | private float mUnreachedBarHeight;
59 |
60 | /**
61 | * The suffix of the number.
62 | */
63 | private String mSuffix = "%";
64 |
65 | /**
66 | * The prefix.
67 | */
68 | private String mPrefix = "";
69 |
70 |
71 | private final int default_text_color = Color.rgb(255, 137, 91);
72 | private final int default_reached_color = Color.rgb(255, 137, 91);
73 | private final int default_unreached_color = Color.rgb(204, 204, 204);
74 | private final float default_progress_text_offset;
75 | private final float default_text_size;
76 |
77 | /**
78 | * For save and restore instance of progressbar.
79 | */
80 | private static final String INSTANCE_STATE = "saved_instance";
81 | private static final String INSTANCE_TEXT_COLOR = "text_color";
82 | private static final String INSTANCE_TEXT_SIZE = "text_size";
83 | private static final String INSTANCE_REACHED_BAR_HEIGHT = "reached_bar_height";
84 | private static final String INSTANCE_REACHED_BAR_COLOR = "reached_bar_color";
85 | private static final String INSTANCE_UNREACHED_BAR_HEIGHT = "unreached_bar_height";
86 | private static final String INSTANCE_UNREACHED_BAR_COLOR = "unreached_bar_color";
87 | private static final String INSTANCE_MAX = "max";
88 | private static final String INSTANCE_PROGRESS = "progress";
89 | private static final String INSTANCE_SUFFIX = "suffix";
90 | private static final String INSTANCE_PREFIX = "prefix";
91 | private static final String INSTANCE_TEXT_VISIBILITY = "text_visibility";
92 |
93 | private static final int PROGRESS_TEXT_VISIBLE = 0;
94 |
95 |
96 | /**
97 | * The width of the text that to be drawn.
98 | */
99 | private float mDrawTextWidth;
100 |
101 | /**
102 | * The drawn text start.
103 | */
104 | private float mDrawTextStart;
105 |
106 | /**
107 | * The drawn text end.
108 | */
109 | private float mDrawTextEnd;
110 |
111 | /**
112 | * The text that to be drawn in onDraw().
113 | */
114 | private String mCurrentDrawText;
115 |
116 | /**
117 | * The Paint of the reached area.
118 | */
119 | private Paint mReachedBarPaint;
120 | /**
121 | * The Paint of the unreached area.
122 | */
123 | private Paint mUnreachedBarPaint;
124 | /**
125 | * The Paint of the progress text.
126 | */
127 | private Paint mTextPaint;
128 |
129 | /**
130 | * Unreached bar area to draw rect.
131 | */
132 | private RectF mUnreachedRectF = new RectF(0, 0, 0, 0);
133 | /**
134 | * Reached bar area rect.
135 | */
136 | private RectF mReachedRectF = new RectF(0, 0, 0, 0);
137 |
138 | /**
139 | * The progress text offset.
140 | */
141 | private float mOffset;
142 |
143 | /**
144 | * Determine if need to draw unreached area.
145 | */
146 | private boolean mDrawUnreachedBar = true;
147 |
148 | private boolean mDrawReachedBar = true;
149 |
150 | private boolean mIfDrawText = true;
151 |
152 | public enum ProgressTextVisibility {
153 | Visible, Invisible
154 | }
155 |
156 | public NumberProgressBar(Context context) {
157 | this(context, null);
158 | }
159 |
160 | public NumberProgressBar(Context context, AttributeSet attrs) {
161 | this(context, attrs, 0);
162 | }
163 |
164 | public NumberProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
165 | super(context, attrs, defStyleAttr);
166 |
167 | mReachedBarHeight = dp2px(1.5f);
168 | mUnreachedBarHeight = dp2px(1.0f);
169 | default_text_size = sp2px(10);
170 | default_progress_text_offset = dp2px(3.0f);
171 |
172 | //load styled attributes.
173 | final TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.AppUpdate_NumberProgressBar,
174 | defStyleAttr, 0);
175 |
176 | mReachedBarColor = attributes.getColor(R.styleable.AppUpdate_NumberProgressBar_progress_reached_color, default_reached_color);
177 | mUnreachedBarColor = attributes.getColor(R.styleable.AppUpdate_NumberProgressBar_progress_unreached_color, default_unreached_color);
178 | mTextColor = attributes.getColor(R.styleable.AppUpdate_NumberProgressBar_progress_text_color, default_text_color);
179 | mTextSize = attributes.getDimension(R.styleable.AppUpdate_NumberProgressBar_progress_text_size, default_text_size);
180 | attributes.recycle();
181 | initializePainters();
182 | }
183 |
184 | @Override
185 | protected int getSuggestedMinimumWidth() {
186 | return (int) mTextSize;
187 | }
188 |
189 | @Override
190 | protected int getSuggestedMinimumHeight() {
191 | return Math.max((int) mTextSize, Math.max((int) mReachedBarHeight, (int) mUnreachedBarHeight));
192 | }
193 |
194 | @Override
195 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
196 | setMeasuredDimension(measure(widthMeasureSpec, true), measure(heightMeasureSpec, false));
197 | }
198 |
199 | private int measure(int measureSpec, boolean isWidth) {
200 | int result;
201 | int mode = MeasureSpec.getMode(measureSpec);
202 | int size = MeasureSpec.getSize(measureSpec);
203 | int padding = isWidth ? getPaddingLeft() + getPaddingRight() : getPaddingTop() + getPaddingBottom();
204 | if (mode == MeasureSpec.EXACTLY) {
205 | result = size;
206 | } else {
207 | result = isWidth ? getSuggestedMinimumWidth() : getSuggestedMinimumHeight();
208 | result += padding;
209 | if (mode == MeasureSpec.AT_MOST) {
210 | if (isWidth) {
211 | result = Math.max(result, size);
212 | } else {
213 | result = Math.min(result, size);
214 | }
215 | }
216 | }
217 | return result;
218 | }
219 |
220 | @Override
221 | protected void onDraw(Canvas canvas) {
222 | if (mIfDrawText) {
223 | calculateDrawRectF();
224 | } else {
225 | calculateDrawRectFWithoutProgressText();
226 | }
227 |
228 | if (mDrawReachedBar) {
229 | canvas.drawRect(mReachedRectF, mReachedBarPaint);
230 | }
231 |
232 | if (mDrawUnreachedBar) {
233 | canvas.drawRect(mUnreachedRectF, mUnreachedBarPaint);
234 | }
235 |
236 | if (mIfDrawText)
237 | canvas.drawText(mCurrentDrawText, mDrawTextStart, mDrawTextEnd, mTextPaint);
238 | }
239 |
240 | private void initializePainters() {
241 | mReachedBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
242 | mReachedBarPaint.setColor(mReachedBarColor);
243 |
244 | mUnreachedBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
245 | mUnreachedBarPaint.setColor(mUnreachedBarColor);
246 |
247 | mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
248 | mTextPaint.setColor(mTextColor);
249 | mTextPaint.setTextSize(mTextSize);
250 | }
251 |
252 |
253 | private void calculateDrawRectFWithoutProgressText() {
254 | mReachedRectF.left = getPaddingLeft();
255 | mReachedRectF.top = getHeight() / 2.0f - mReachedBarHeight / 2.0f;
256 | mReachedRectF.right = (getWidth() - getPaddingLeft() - getPaddingRight()) / (getMax() * 1.0f) * getProgress() + getPaddingLeft();
257 | mReachedRectF.bottom = getHeight() / 2.0f + mReachedBarHeight / 2.0f;
258 |
259 | mUnreachedRectF.left = mReachedRectF.right;
260 | mUnreachedRectF.right = getWidth() - getPaddingRight();
261 | mUnreachedRectF.top = getHeight() / 2.0f + -mUnreachedBarHeight / 2.0f;
262 | mUnreachedRectF.bottom = getHeight() / 2.0f + mUnreachedBarHeight / 2.0f;
263 | }
264 |
265 | private void calculateDrawRectF() {
266 |
267 | mCurrentDrawText = String.format("%d", getProgress() * 100 / getMax());
268 | mCurrentDrawText = mPrefix + mCurrentDrawText + mSuffix;
269 | mDrawTextWidth = mTextPaint.measureText(mCurrentDrawText);
270 |
271 | if (getProgress() == 0) {
272 | mDrawReachedBar = false;
273 | mDrawTextStart = getPaddingLeft();
274 | } else {
275 | mDrawReachedBar = true;
276 | mReachedRectF.left = getPaddingLeft();
277 | mReachedRectF.top = getHeight() / 2.0f - mReachedBarHeight / 2.0f;
278 | mReachedRectF.right = (getWidth() - getPaddingLeft() - getPaddingRight()) / (getMax() * 1.0f) * getProgress() - mOffset + getPaddingLeft();
279 | mReachedRectF.bottom = getHeight() / 2.0f + mReachedBarHeight / 2.0f;
280 | mDrawTextStart = (mReachedRectF.right + mOffset);
281 | }
282 |
283 | mDrawTextEnd = (int) ((getHeight() / 2.0f) - ((mTextPaint.descent() + mTextPaint.ascent()) / 2.0f));
284 |
285 | if ((mDrawTextStart + mDrawTextWidth) >= getWidth() - getPaddingRight()) {
286 | mDrawTextStart = getWidth() - getPaddingRight() - mDrawTextWidth;
287 | mReachedRectF.right = mDrawTextStart - mOffset;
288 | }
289 |
290 | float unreachedBarStart = mDrawTextStart + mDrawTextWidth + mOffset;
291 | if (unreachedBarStart >= getWidth() - getPaddingRight()) {
292 | mDrawUnreachedBar = false;
293 | } else {
294 | mDrawUnreachedBar = true;
295 | mUnreachedRectF.left = unreachedBarStart;
296 | mUnreachedRectF.right = getWidth() - getPaddingRight();
297 | mUnreachedRectF.top = getHeight() / 2.0f + -mUnreachedBarHeight / 2.0f;
298 | mUnreachedRectF.bottom = getHeight() / 2.0f + mUnreachedBarHeight / 2.0f;
299 | }
300 | }
301 |
302 | /**
303 | * Get progress text color.
304 | *
305 | * @return progress text color.
306 | */
307 | public int getTextColor() {
308 | return mTextColor;
309 | }
310 |
311 | /**
312 | * Get progress text size.
313 | *
314 | * @return progress text size.
315 | */
316 | public float getProgressTextSize() {
317 | return mTextSize;
318 | }
319 |
320 | public int getUnreachedBarColor() {
321 | return mUnreachedBarColor;
322 | }
323 |
324 | public int getReachedBarColor() {
325 | return mReachedBarColor;
326 | }
327 |
328 | public int getProgress() {
329 | return mCurrentProgress;
330 | }
331 |
332 | public int getMax() {
333 | return mMaxProgress;
334 | }
335 |
336 | public float getReachedBarHeight() {
337 | return mReachedBarHeight;
338 | }
339 |
340 | public float getUnreachedBarHeight() {
341 | return mUnreachedBarHeight;
342 | }
343 |
344 | public void setProgressTextSize(float textSize) {
345 | this.mTextSize = textSize;
346 | mTextPaint.setTextSize(mTextSize);
347 | invalidate();
348 | }
349 |
350 | public void setProgressTextColor(int textColor) {
351 | this.mTextColor = textColor;
352 | mTextPaint.setColor(mTextColor);
353 | invalidate();
354 | }
355 |
356 | public void setUnreachedBarColor(int barColor) {
357 | this.mUnreachedBarColor = barColor;
358 | mUnreachedBarPaint.setColor(mUnreachedBarColor);
359 | invalidate();
360 | }
361 |
362 | public void setReachedBarColor(int progressColor) {
363 | this.mReachedBarColor = progressColor;
364 | mReachedBarPaint.setColor(mReachedBarColor);
365 | invalidate();
366 | }
367 |
368 | public void setReachedBarHeight(float height) {
369 | mReachedBarHeight = height;
370 | }
371 |
372 | public void setUnreachedBarHeight(float height) {
373 | mUnreachedBarHeight = height;
374 | }
375 |
376 | public void setMax(int maxProgress) {
377 | if (maxProgress > 0) {
378 | this.mMaxProgress = maxProgress;
379 | invalidate();
380 | }
381 | }
382 |
383 | public void setSuffix(String suffix) {
384 | if (suffix == null) {
385 | mSuffix = "";
386 | } else {
387 | mSuffix = suffix;
388 | }
389 | }
390 |
391 | public String getSuffix() {
392 | return mSuffix;
393 | }
394 |
395 | public void setPrefix(String prefix) {
396 | if (prefix == null)
397 | mPrefix = "";
398 | else {
399 | mPrefix = prefix;
400 | }
401 | }
402 |
403 | public String getPrefix() {
404 | return mPrefix;
405 | }
406 |
407 | public void incrementProgressBy(int by) {
408 | if (by > 0) {
409 | setProgress(getProgress() + by);
410 | }
411 | }
412 |
413 | public void setProgress(int progress) {
414 | if (progress <= getMax() && progress >= 0) {
415 | this.mCurrentProgress = progress;
416 | invalidate();
417 | }
418 | }
419 |
420 | @Override
421 | protected Parcelable onSaveInstanceState() {
422 | final Bundle bundle = new Bundle();
423 | bundle.putParcelable(INSTANCE_STATE, super.onSaveInstanceState());
424 | bundle.putInt(INSTANCE_TEXT_COLOR, getTextColor());
425 | bundle.putFloat(INSTANCE_TEXT_SIZE, getProgressTextSize());
426 | bundle.putFloat(INSTANCE_REACHED_BAR_HEIGHT, getReachedBarHeight());
427 | bundle.putFloat(INSTANCE_UNREACHED_BAR_HEIGHT, getUnreachedBarHeight());
428 | bundle.putInt(INSTANCE_REACHED_BAR_COLOR, getReachedBarColor());
429 | bundle.putInt(INSTANCE_UNREACHED_BAR_COLOR, getUnreachedBarColor());
430 | bundle.putInt(INSTANCE_MAX, getMax());
431 | bundle.putInt(INSTANCE_PROGRESS, getProgress());
432 | bundle.putString(INSTANCE_SUFFIX, getSuffix());
433 | bundle.putString(INSTANCE_PREFIX, getPrefix());
434 | bundle.putBoolean(INSTANCE_TEXT_VISIBILITY, getProgressTextVisibility());
435 | return bundle;
436 | }
437 |
438 | @Override
439 | protected void onRestoreInstanceState(Parcelable state) {
440 | if (state instanceof Bundle) {
441 | final Bundle bundle = (Bundle) state;
442 | mTextColor = bundle.getInt(INSTANCE_TEXT_COLOR);
443 | mTextSize = bundle.getFloat(INSTANCE_TEXT_SIZE);
444 | mReachedBarHeight = bundle.getFloat(INSTANCE_REACHED_BAR_HEIGHT);
445 | mUnreachedBarHeight = bundle.getFloat(INSTANCE_UNREACHED_BAR_HEIGHT);
446 | mReachedBarColor = bundle.getInt(INSTANCE_REACHED_BAR_COLOR);
447 | mUnreachedBarColor = bundle.getInt(INSTANCE_UNREACHED_BAR_COLOR);
448 | initializePainters();
449 | setMax(bundle.getInt(INSTANCE_MAX));
450 | setProgress(bundle.getInt(INSTANCE_PROGRESS));
451 | setPrefix(bundle.getString(INSTANCE_PREFIX));
452 | setSuffix(bundle.getString(INSTANCE_SUFFIX));
453 | setProgressTextVisibility(bundle.getBoolean(INSTANCE_TEXT_VISIBILITY) ? ProgressTextVisibility.Visible : ProgressTextVisibility.Invisible);
454 | super.onRestoreInstanceState(bundle.getParcelable(INSTANCE_STATE));
455 | return;
456 | }
457 | super.onRestoreInstanceState(state);
458 | }
459 |
460 | public float dp2px(float dp) {
461 | final float scale = getResources().getDisplayMetrics().density;
462 | return dp * scale + 0.5f;
463 | }
464 |
465 | public float sp2px(float sp) {
466 | final float scale = getResources().getDisplayMetrics().scaledDensity;
467 | return sp * scale;
468 | }
469 |
470 | public void setProgressTextVisibility(ProgressTextVisibility visibility) {
471 | mIfDrawText = visibility == ProgressTextVisibility.Visible;
472 | invalidate();
473 | }
474 |
475 | public boolean getProgressTextVisibility() {
476 | return mIfDrawText;
477 | }
478 |
479 | }
480 |
--------------------------------------------------------------------------------
/appupdate/src/main/java/com/azhon/appupdate/view/UpdateDialogActivity.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate.view
2 |
3 | import android.Manifest
4 | import android.content.Intent
5 | import android.content.pm.PackageManager
6 | import android.graphics.drawable.GradientDrawable
7 | import android.graphics.drawable.StateListDrawable
8 | import android.os.Build
9 | import android.os.Bundle
10 | import android.view.Gravity
11 | import android.view.View
12 | import android.view.WindowManager
13 | import android.widget.Button
14 | import android.widget.ImageView
15 | import android.widget.TextView
16 | import androidx.activity.OnBackPressedCallback
17 | import androidx.appcompat.app.AppCompatActivity
18 | import androidx.core.app.ActivityCompat
19 | import com.azhon.appupdate.R
20 | import com.azhon.appupdate.config.Constant
21 | import com.azhon.appupdate.listener.OnButtonClickListener
22 | import com.azhon.appupdate.listener.OnDownloadListenerAdapter
23 | import com.azhon.appupdate.manager.DownloadManager
24 | import com.azhon.appupdate.service.DownloadService
25 | import com.azhon.appupdate.util.ApkUtil
26 | import com.azhon.appupdate.util.DensityUtil
27 | import com.azhon.appupdate.util.LogUtil
28 | import java.io.File
29 |
30 |
31 | /**
32 | * createDate: 2022/4/7 on 17:40
33 | * desc:
34 | *
35 | * @author azhon
36 | */
37 |
38 | class UpdateDialogActivity : AppCompatActivity(), View.OnClickListener {
39 |
40 | private val install = 0x45
41 | private val error = 0x46
42 | private val permissionCode = 0x47
43 | private var manager: DownloadManager? = null
44 | private lateinit var apk: File
45 | private lateinit var progressBar: NumberProgressBar
46 | private lateinit var btnUpdate: Button
47 |
48 | companion object {
49 | private const val TAG = "UpdateDialogActivity"
50 | }
51 |
52 | override fun onCreate(savedInstanceState: Bundle?) {
53 | super.onCreate(savedInstanceState)
54 | overridePendingTransition(0, 0)
55 | title = ""
56 | setContentView(R.layout.app_update_dialog_update)
57 | //system back button
58 | onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
59 | override fun handleOnBackPressed() {
60 | backPressed()
61 | }
62 | })
63 | init()
64 | }
65 |
66 | private fun init() {
67 | manager = DownloadManager.getInstance()
68 | if (manager == null) {
69 | LogUtil.e(TAG, "An exception occurred by DownloadManager=null,please check your code!")
70 | return
71 | }
72 | if (manager!!.forcedUpgrade) {
73 | manager!!.onDownloadListeners.add(listenerAdapter)
74 | }
75 | setWindowSize()
76 | initView(manager!!)
77 | }
78 |
79 | private fun initView(manager: DownloadManager) {
80 | val ibClose = findViewById(R.id.ib_close)
81 | val vLine = findViewById(R.id.line)
82 | val ivBg = findViewById(R.id.iv_bg)
83 | val tvTitle = findViewById(R.id.tv_title)
84 | val tvSize = findViewById(R.id.tv_size)
85 | val tvDescription = findViewById(R.id.tv_description)
86 | progressBar = findViewById(R.id.np_bar)
87 | btnUpdate = findViewById(R.id.btn_update)
88 | progressBar.visibility = if (manager.forcedUpgrade) View.VISIBLE else View.GONE
89 | btnUpdate.tag = 0
90 | btnUpdate.setOnClickListener(this)
91 | ibClose.setOnClickListener(this)
92 | if (manager.dialogImage != -1) {
93 | ivBg.setBackgroundResource(manager.dialogImage)
94 | }
95 | if (manager.dialogButtonTextColor != -1) {
96 | btnUpdate.setTextColor(manager.dialogButtonTextColor)
97 | }
98 | if (manager.dialogProgressBarColor != -1) {
99 | progressBar.reachedBarColor = manager.dialogProgressBarColor
100 | progressBar.setProgressTextColor(manager.dialogProgressBarColor)
101 | }
102 | if (manager.dialogButtonColor != -1) {
103 | val colorDrawable = GradientDrawable().apply {
104 | setColor(manager.dialogButtonColor)
105 | cornerRadius = DensityUtil.dip2px(this@UpdateDialogActivity, 3f)
106 | }
107 | val drawable = StateListDrawable().apply {
108 | addState(intArrayOf(android.R.attr.state_pressed), colorDrawable)
109 | addState(IntArray(0), colorDrawable)
110 | }
111 | btnUpdate.background = drawable
112 | }
113 | if (manager.forcedUpgrade) {
114 | vLine.visibility = View.GONE
115 | ibClose.visibility = View.GONE
116 | }
117 | if (manager.apkVersionName.isNotEmpty()) {
118 | tvTitle.text = String.format(
119 | resources.getString(R.string.app_update_dialog_new), manager.apkVersionName
120 | )
121 | }
122 | if (manager.apkSize.isNotEmpty()) {
123 | tvSize.text = String.format(
124 | resources.getString(R.string.app_update_dialog_new_size), manager.apkSize
125 | )
126 | tvSize.visibility = View.VISIBLE
127 | }
128 | tvDescription.text = manager.apkDescription
129 | }
130 |
131 | private fun setWindowSize() {
132 | val attributes = window.attributes
133 | attributes.width = DensityUtil.dip2px(this@UpdateDialogActivity, 280f).toInt()
134 | attributes.height = WindowManager.LayoutParams.WRAP_CONTENT
135 | attributes.gravity = Gravity.CENTER
136 | window.attributes = attributes
137 | }
138 |
139 | override fun onClick(v: View?) {
140 | when (v?.id) {
141 | R.id.ib_close -> {
142 | if (manager?.forcedUpgrade == false) {
143 | finish()
144 | }
145 | manager?.onButtonClickListener?.onButtonClick(OnButtonClickListener.CANCEL)
146 | }
147 | R.id.btn_update -> {
148 | if (btnUpdate.tag == install) {
149 | ApkUtil.installApk(this, Constant.AUTHORITIES!!, apk)
150 | return
151 | }
152 | if (!checkPermission()) {
153 | startUpdate()
154 | }
155 | }
156 | }
157 | }
158 |
159 | /**
160 | * check Notification runtime permission [DownloadManager.showNotification] is true && when api>=33.
161 | * @return false: can continue to download, true: request permission.
162 | */
163 | private fun checkPermission(): Boolean {
164 | if (manager?.showNotification == false) {
165 | LogUtil.d(TAG, "checkPermission: manager.showNotification = false")
166 | return false
167 | }
168 | if (ActivityCompat.checkSelfPermission(
169 | this, Manifest.permission.POST_NOTIFICATIONS
170 | ) == PackageManager.PERMISSION_GRANTED
171 | ) {
172 | LogUtil.d(TAG, "checkPermission: has permission")
173 | return false
174 | }
175 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
176 | LogUtil.d(TAG, "checkPermission: request permission")
177 | ActivityCompat.requestPermissions(
178 | this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), permissionCode
179 | )
180 | return true
181 | }
182 | return false
183 | }
184 |
185 | private fun startUpdate() {
186 | if (manager?.forcedUpgrade == true) {
187 | btnUpdate.isEnabled = false
188 | btnUpdate.text = resources.getString(R.string.app_update_background_downloading)
189 | } else {
190 | finish()
191 | }
192 | manager?.onButtonClickListener?.onButtonClick(OnButtonClickListener.UPDATE)
193 | startService(Intent(this, DownloadService::class.java))
194 | }
195 |
196 | private fun backPressed() {
197 | if (manager?.forcedUpgrade == true) return
198 | finish()
199 | manager?.onButtonClickListener?.onButtonClick(OnButtonClickListener.CANCEL)
200 | }
201 |
202 | override fun finish() {
203 | super.finish()
204 | overridePendingTransition(0, 0)
205 | }
206 |
207 | private val listenerAdapter: OnDownloadListenerAdapter = object : OnDownloadListenerAdapter() {
208 | override fun start() {
209 | btnUpdate.isEnabled = false
210 | btnUpdate.text = resources.getString(R.string.app_update_background_downloading)
211 | }
212 |
213 | override fun downloading(max: Int, progress: Int) {
214 | if (max != -1) {
215 | val curr = (progress / max.toDouble() * 100.0).toInt()
216 | progressBar.progress = curr
217 | } else {
218 | progressBar.visibility = View.GONE
219 | }
220 | }
221 |
222 | override fun done(apk: File) {
223 | this@UpdateDialogActivity.apk = apk
224 | btnUpdate.tag = install
225 | btnUpdate.isEnabled = true
226 | btnUpdate.text = resources.getString(R.string.app_update_click_hint)
227 | }
228 |
229 | override fun error(e: Throwable) {
230 | btnUpdate.tag = error
231 | btnUpdate.isEnabled = true
232 | btnUpdate.text = resources.getString(R.string.app_update_continue_downloading)
233 | }
234 | }
235 |
236 | override fun onRequestPermissionsResult(
237 | requestCode: Int, permissions: Array, grantResults: IntArray
238 | ) {
239 | super.onRequestPermissionsResult(requestCode, permissions, grantResults)
240 | if (permissionCode == requestCode) {
241 | startUpdate()
242 | }
243 | }
244 |
245 | override fun onDestroy() {
246 | super.onDestroy()
247 | manager?.onDownloadListeners?.remove(listenerAdapter)
248 | }
249 | }
--------------------------------------------------------------------------------
/appupdate/src/main/res/drawable/app_update_bg_button.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | -
4 |
5 |
6 |
7 |
8 |
9 | -
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/appupdate/src/main/res/drawable/app_update_bg_white_radius_6.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
--------------------------------------------------------------------------------
/appupdate/src/main/res/drawable/app_update_dialog_close.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/appupdate/src/main/res/drawable/app_update_dialog_close.png
--------------------------------------------------------------------------------
/appupdate/src/main/res/drawable/app_update_dialog_default.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/appupdate/src/main/res/drawable/app_update_dialog_default.png
--------------------------------------------------------------------------------
/appupdate/src/main/res/layout/app_update_dialog_update.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
14 |
15 |
20 |
21 |
30 |
31 |
42 |
43 |
50 |
51 |
59 |
60 |
61 |
68 |
69 |
81 |
82 |
83 |
89 |
90 |
97 |
--------------------------------------------------------------------------------
/appupdate/src/main/res/values-en-rUS/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Currently the latest version!
3 | Start download
4 | You can check the download progress later
5 | Downloading new version
6 | Download completed
7 | Click to install
8 | Download error
9 | Click to continue downloading
10 | Downloading new version in the background…
11 | The new version %s can be downloaded!
12 | New version size:%s
13 | Update
14 | Close
15 |
16 |
--------------------------------------------------------------------------------
/appupdate/src/main/res/values-zh-rTW/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | 當前已是最新版本!
3 | 開始下載
4 | 可稍後查看下載進度
5 | 正在下載新版本
6 | 下載完成
7 | 點擊進行安裝
8 | 下載出錯
9 | 點擊繼續下載
10 | 正在後臺下載新版本…
11 | 發現新版本%s可以下載啦!
12 | 新版本大小:%s
13 | 升級
14 | 關閉
15 |
16 |
--------------------------------------------------------------------------------
/appupdate/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | 当前已是最新版本!
3 | 开始下载
4 | 可稍后查看下载进度
5 | 正在下载新版本
6 | 下载完成
7 | 点击进行安装
8 | 下载出错
9 | 点击继续下载
10 | 正在后台下载新版本…
11 | 发现新版本%s可以下载啦!
12 | 新版本大小:%s
13 | 升级
14 | 关闭
15 |
16 |
--------------------------------------------------------------------------------
/appupdate/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
13 |
14 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/appupdate/src/main/res/xml/app_update_file.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
9 |
--------------------------------------------------------------------------------
/appupdate/src/test/java/com/azhon/appupdate/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.azhon.appupdate
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 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | plugins {
3 | id 'com.android.application' version '8.5.1' apply false
4 | id 'com.android.library' version '8.5.1' apply false
5 | id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
6 | }
7 |
8 | task clean(type: Delete) {
9 | delete rootProject.buildDir
10 | }
11 | ext {
12 | compileSdk = 33
13 | targetSdk = 33
14 | minSdk = 16
15 | publishVersion = "4.3.6"
16 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
24 | android.defaults.buildfeatures.buildconfig=true
25 | android.nonFinalResIds=false
26 | # signing information
27 | signing.keyId=C505FA8A
28 | signing.password=12345678
29 | signing.secretKeyRingFile=../secret.gpg
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Apr 07 10:15:47 CST 2022
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/img/en/en_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/en/en_1.png
--------------------------------------------------------------------------------
/img/en/en_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/en/en_2.png
--------------------------------------------------------------------------------
/img/en/en_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/en/en_3.png
--------------------------------------------------------------------------------
/img/en/en_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/en/en_4.png
--------------------------------------------------------------------------------
/img/en/en_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/en/en_5.png
--------------------------------------------------------------------------------
/img/en/en_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/en/en_6.png
--------------------------------------------------------------------------------
/img/en/en_7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/en/en_7.png
--------------------------------------------------------------------------------
/img/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/logo.png
--------------------------------------------------------------------------------
/img/money.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/money.jpg
--------------------------------------------------------------------------------
/img/qq_group_0.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/qq_group_0.jpg
--------------------------------------------------------------------------------
/img/qq_group_1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/qq_group_1.jpg
--------------------------------------------------------------------------------
/img/zh/zh_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/zh/zh_1.png
--------------------------------------------------------------------------------
/img/zh/zh_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/zh/zh_2.png
--------------------------------------------------------------------------------
/img/zh/zh_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/zh/zh_3.png
--------------------------------------------------------------------------------
/img/zh/zh_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/zh/zh_4.png
--------------------------------------------------------------------------------
/img/zh/zh_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/zh/zh_5.png
--------------------------------------------------------------------------------
/img/zh/zh_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/zh/zh_6.png
--------------------------------------------------------------------------------
/img/zh/zh_7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/azhon/AppUpdate/a7b0839870948d180b86d7aceaf946fd27a4739b/img/zh/zh_7.png
--------------------------------------------------------------------------------
/maven.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'maven-publish'
2 | apply plugin: 'signing'
3 |
4 | tasks.register('generateSourcesJar', Jar) {
5 | from android.sourceSets.main.java.srcDirs
6 | archiveClassifier.set("sources")
7 | }
8 |
9 | Properties localProperties = new Properties()
10 | localProperties.load(project.rootProject.file('local.properties').newDataInputStream())
11 |
12 | afterEvaluate {
13 | publishing {
14 | publications {
15 | maven(MavenPublication) {
16 | from components.release
17 | groupId "io.github.azhon"
18 | artifactId project.ARTIFACT_ID
19 | version rootProject.ext.publishVersion
20 | artifact generateSourcesJar
21 | pom {
22 | name = 'AppUpdate'
23 | description = 'Android App update library. Android版本更新库,简单、轻量、可随意定制'
24 | url = 'https://github.com/azhon/AppUpdate'
25 | licenses {
26 | license {
27 | name = 'The Apache License, Version 2.0'
28 | url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
29 | }
30 | }
31 | developers {
32 | developer {
33 | id = 'azhon'
34 | name = 'azhon'
35 | email = 'azhon.cn@gmail.com'
36 | }
37 | }
38 | scm {
39 | connection = 'https://github.com/azhon/AppUpdate.git'
40 | developerConnection = 'https://github.com/azhon/AppUpdate.git'
41 | url = 'https://github.com/azhon/AppUpdate'
42 | }
43 | }
44 | }
45 | }
46 | repositories {
47 | maven {
48 | url "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/"
49 | credentials {
50 | username localProperties.getProperty('sonatype.name')
51 | password localProperties.getProperty('sonatype.password')
52 | }
53 | }
54 | }
55 | }
56 | }
57 | signing {
58 | sign publishing.publications
59 | }
--------------------------------------------------------------------------------
/maven_publish.sh:
--------------------------------------------------------------------------------
1 | #upload to mavenCentral()
2 | #https://s01.oss.sonatype.org/#stagingRepositories
3 | ./gradlew :appupdate:publishMavenPublicationToMavenRepository
4 |
5 | ./gradlew :appupdate-no-op:publishMavenPublicationToMavenRepository
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | gradlePluginPortal()
4 | google()
5 | mavenCentral()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 | rootProject.name = "AppUpdate"
16 | include ':app'
17 | include ':appupdate'
18 | include ':appupdate-no-op'
19 |
--------------------------------------------------------------------------------