├── .github
├── CODEOWNERS
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── enhancement.md
└── pull_request_template.md
├── .gitignore
├── .idea
├── checkstyle-idea.xml
├── codeStyles
│ └── Project.xml
├── compiler.xml
├── copyright
│ ├── Apache_2_0.xml
│ └── profiles_settings.xml
├── encodings.xml
├── kotlinc.xml
├── markdown-navigator.xml
└── markdown-navigator
│ └── profiles_settings.xml
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── hyperdevs
│ │ └── appupdateshelper
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── kotlin
│ │ └── com
│ │ │ └── hyperdevs
│ │ │ └── appupdateshelper
│ │ │ └── app
│ │ │ ├── MainActivity.kt
│ │ │ ├── fake
│ │ │ └── FakeUpdateActivity.kt
│ │ │ ├── flexible
│ │ │ └── FlexibleUpdateActivity.kt
│ │ │ ├── fragment
│ │ │ ├── FragmentUpdateActivity.kt
│ │ │ └── FragmentUpdateFragment.kt
│ │ │ ├── immediate
│ │ │ └── ImmediateUpdateActivity.kt
│ │ │ └── misc
│ │ │ ├── ActivityExtensions.kt
│ │ │ └── FragmentExtensions.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ ├── fake_update_activity.xml
│ │ ├── flexible_update_activity.xml
│ │ ├── fragment_update_activity.xml
│ │ ├── fragment_update_fragment.xml
│ │ ├── immediate_update_activity.xml
│ │ └── main_activity.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── hyperdevs
│ └── appupdateshelper
│ └── ExampleUnitTest.kt
├── build.gradle
├── checkstyle.xml
├── code-style.xml
├── debug.keystore
├── gradle.properties
├── gradle
├── properties_utils.gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── jitpack-android.gradle
├── jitpack.yml
├── lib
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── hyperdevs
│ │ └── appupdateshelper
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── hyperdevs
│ │ │ └── appupdateshelper
│ │ │ ├── AppUpdateInfoResult.java
│ │ │ ├── AppUpdateInstallState.java
│ │ │ ├── AppUpdatesHelper.java
│ │ │ ├── ContextUtils.java
│ │ │ ├── FakeAppUpdatesHelper.java
│ │ │ ├── GetUpdateInfoListener.java
│ │ │ └── InstallStateListener.java
│ └── res
│ │ └── values
│ │ └── strings.xml
│ └── test
│ └── java
│ └── com
│ └── hyperdevs
│ └── appupdateshelper
│ └── ExampleUnitTest.java
└── settings.gradle
/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 | # This is a comment.
2 | # Each line is a file pattern followed by one or more owners.
3 |
4 | # Current code owners
5 | # @adriangl -> Adrián García
6 |
7 | * @adriangl
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a bug report to help us improve
4 | title: ''
5 | labels: bug
6 | assignees: adriangl
7 |
8 | ---
9 |
10 | **Device and SW details**
11 | - Device: [e.g. Google Pixel 3]
12 | - OS: [e.g. Android 9]
13 | - Library Version [e.g. 1.0.0]
14 |
15 | **Conditions for the library to work**
16 | - [ ] I have set the package name of the app to **exactly** the one I'd like to test in-app updates with.
17 | - [ ] I have signed the app with the same key that I used to sign the app I want to test in-app updates with.
18 | - [ ] I've ensured that any of my Google accounts in my test device has access to said app in Google Play Store.
19 | - [ ] The Google Play Store displays updates for the app I want to use to test in-app updates with.
20 |
21 | **Summary and background of the bug**
22 | A clear and concise description of what the bug is.
23 |
24 | **Steps to reproduce**
25 | Steps to reproduce the behavior:
26 | 1. Go to '...'
27 | 2. Click on '...'
28 | 3. Scroll down to '...'
29 | 4. See error
30 |
31 | Also attach notes or stack traces if applicable.
32 |
33 | **Expected behavior**
34 | A clear and concise description of what you expected to happen.
35 |
36 | **Current behavior**
37 | The summary of what currently happens in your use case.
38 |
39 | **Screenshots**
40 | If applicable, add screenshots to help explain your problem.
41 |
42 | **Additional context**
43 | Add any other context about the problem here.
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/enhancement.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Enhancement
3 | about: Create a report to propose new features and improvements
4 | title: ''
5 | labels: enhancement
6 | assignees: adriangl
7 |
8 | ---
9 |
10 | **Summary and context of the enhancement**
11 | A clear and concise description of what the bug is.
12 |
13 | **Suggested implementation**
14 | Add suggestions about how the enhancement should be implemented.
15 |
16 | **Additional documentation**
17 | Useful links to review the enhancement.
--------------------------------------------------------------------------------
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 | ### Github issue (if applies)
2 | https://github.com/bq/AppUpdatesHelper/issues/change_me_issue_number
3 |
4 | ### PR's key points
5 |
6 | ### How to review this PR?
7 |
8 | ### Related Issues
9 |
10 | ### Definition of Done
11 | - [ ] Tests pass
12 | - [ ] Works with Proguard
13 | - [ ] There is no outcommented or debug code left (if there is a good reason, use a // FIXME: comment or // TODO: comment and create a follow-up issue)
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | # Intellij
36 | *.iml
37 | .idea/workspace.xml
38 | .idea/tasks.xml
39 | .idea/gradle.xml
40 | .idea/dictionaries
41 | .idea/libraries
42 | .idea/caches
43 | .idea/modules.xml
44 | .idea/misc.xml
45 | .idea/jarRepositories.xml
46 | .idea/vcs.xml
47 |
48 | # Keystore files
49 | *.jks
50 |
51 | # External native build folder generated in Android Studio 2.2 and later
52 | .externalNativeBuild
53 |
54 | # Google Services (e.g. APIs or Firebase)
55 | google-services.json
56 |
57 | # Freeline
58 | freeline.py
59 | freeline/
60 | freeline_project_description.json
61 |
62 | # App configuration properties
63 | app_config.properties
--------------------------------------------------------------------------------
/.idea/checkstyle-idea.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
17 |
18 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | xmlns:android
32 |
33 | ^$
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 | xmlns:.*
43 |
44 | ^$
45 |
46 |
47 | BY_NAME
48 |
49 |
50 |
51 |
52 |
53 |
54 | .*:id
55 |
56 | http://schemas.android.com/apk/res/android
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 | .*:name
66 |
67 | http://schemas.android.com/apk/res/android
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 | name
77 |
78 | ^$
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 | style
88 |
89 | ^$
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 | .*
99 |
100 | ^$
101 |
102 |
103 | BY_NAME
104 |
105 |
106 |
107 |
108 |
109 |
110 | .*
111 |
112 | http://schemas.android.com/apk/res/android
113 |
114 |
115 | ANDROID_ATTRIBUTE_ORDER
116 |
117 |
118 |
119 |
120 |
121 |
122 | .*
123 |
124 | .*
125 |
126 |
127 | BY_NAME
128 |
129 |
130 |
131 |
132 |
133 |
134 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/copyright/Apache_2_0.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/markdown-navigator.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
--------------------------------------------------------------------------------
/.idea/markdown-navigator/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 | All notable changes to this project will be documented in this file.
3 |
4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6 |
7 |
22 |
23 | ## [Unreleased]
24 | ### Added
25 | - No new features!
26 | ### Changed
27 | - No changed features!
28 | ### Deprecated
29 | - No deprecated features!
30 | ### Removed
31 | - No removed features!
32 | ### Fixed
33 | - No fixed issues!
34 | ### Security
35 | - No security issues fixed!
36 |
37 | ## [2.1.4] - 2022-09-03
38 | ### Changed
39 | - Updated up to Android 14
40 |
41 | ## [2.0.0] - 2021-04-28
42 | ### Changed
43 | - Changed repo ownership to [hyperdevs-team](https://github.com/hyperdevs-team). Thanks [bq](https://github.com/bq) for all the work!
44 | - Changed package names from `com.bq.*` to `com.hyperdevs.*`
45 | - Updated dependencies
46 |
47 | ## [1.1.0] - 2020-11-05
48 | ### Added
49 | - Add in-app update stale status (added in `play-core` 1.6.5)
50 | - Add download progress in install listener (added in `play-core` 1.6.5)
51 | - Return in-app update priority set via Google Play Developer API (added in `play-core` 1.6.5)
52 | - More error codes tweaked (added in multiple `play-core` releases)
53 | - Set-up listeners from both `Activity` and `Fragment`
54 | - Add sample app configuration
55 | ### Changed
56 | - `play-core` library version upgrade to 1.8.2
57 |
58 | ## [1.0.2] - 2020-10-07
59 | ### Changed
60 | - `play-core` library version upgrade to 1.8.0
61 | - Bump library versions in both library and sample app
62 |
63 | ## [1.0.1] - 2019-06-26
64 | ### Added
65 | - Add automatic version name via Git tags and refactor versions
66 | ### Fixed
67 | - Fix import issues with api instead of implementation when importing `play-core` libs.
68 |
69 | ## [1.0.0] - 2019-06-20
70 | ### Added
71 | - Initial release.
72 |
73 | [Unreleased]: https://github.com/hyperdevs-team/android-app-updates-helper/compare/2.1.4...HEAD
74 | [2.1.4]: https://github.com/hyperdevs-team/android-app-updates-helper/compare/1.1.0...2.0.0
75 | [2.0.0]: https://github.com/hyperdevs-team/android-app-updates-helper/compare/1.1.0...2.0.0
76 | [1.1.0]: https://github.com/hyperdevs-team/android-app-updates-helper/compare/1.0.2...1.1.0
77 | [1.0.2]: https://github.com/hyperdevs-team/android-app-updates-helper/compare/1.0.1...1.0.2
78 | [1.0.1]: https://github.com/hyperdevs-team/android-app-updates-helper/compare/1.0.0...1.0.1
79 | [1.0.0]: https://github.com/hyperdevs-team/android-app-updates-helper/releases/tag/1.0.0
80 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to AppUpdatesHelper
2 |
3 | We love your input! We want to make contributing to this project as easy as possible, whether it's:
4 |
5 | - Reporting a bug
6 | - Submitting a fix
7 | - Proposing new features
8 | - Discussing the current state of the code
9 |
10 | ## We Develop with GitHub
11 | We use GitHub to host code, to track issues and feature requests, as well as to accept pull requests.
12 |
13 | ## Report bugs using Github's [issues](https://github.com/bq/AppUpdatesHelper/issues)
14 | We use GitHub issues to track public bugs. Report a bug by [opening a new issue](https://github.com/bq/AppUpdatesHelper/issues/new)!
15 |
16 | ## Code Changes Happen Through Pull Requests
17 | Pull requests are the best way to propose changes to the codebase. We actively welcome your pull requests:
18 |
19 | 1. Fork the repo and create your branch from `master`.
20 | 2. If you've added code that should be tested, add tests.
21 | 3. If you've changed APIs, update the documentation.
22 | 4. Make sure your code lints and passes the Checkstyle rules.
23 | 5. Issue that pull request!
24 |
25 | ## Any contributions you make will be under the Apache 2.0 Software License
26 | When you submit code changes, your submissions are understood to be under the same [Apache License 2.0](http://choosealicense.com/licenses/apache-2.0/) that covers the project.
27 | Feel free to contact the maintainers if that's a concern.
28 |
29 | ## Write bug reports with detail, background, and sample code
30 | **Great Bug Reports** tend to have:
31 |
32 | - A quick summary and/or background
33 | - Steps to reproduce
34 | - Be specific!
35 | - Give sample code if you can in order to reproduce the issue
36 | - Add the stack traces you find in case the library makes your app crash
37 | - What you expected would happen
38 | - What actually happens
39 | - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work)
40 |
41 | ## Use a Consistent Coding Style
42 | We provide a [code-style](code-style.xml) and [checkstyle](checkstyle.xml) configuration files so you can ensure that all code is properly formatted according to our guidelines.
43 | Please be sure to use these files to format your files when submitting pull requests.
44 |
45 | ## References
46 | This document was adapted from the contribution guidelines proposed by [Brian A. Danielak](https://gist.github.com/briandk/3d2e8b3ec8daf5a27a62) which are itself based on the open-source contribution guidelines for [Facebook's Draft](https://github.com/facebook/draft-js/blob/a9316a723f9e918afde44dea68b5f9f39b7d9b00/CONTRIBUTING.md)
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android App Updates Helper
2 | [](https://jitpack.io/#hyperdevs-team/android-app-updates-helper)
3 |
4 | This utility library aims to help Android developers to use the [Google Play In-App Updates API](https://developer.android.com/guide/app-bundle/in-app-updates) in an easy way.
5 |
6 | > It's highly encouraged that you first read the [Google Play In-App Updates API](https://developer.android.com/guide/app-bundle/in-app-updates) documentation before using this library in order to understand the core concepts of the library.
7 |
8 | ## Setting Up
9 | In your main `build.gradle`, add [jitpack.io](https://jitpack.io/) repository in the `allprojects` block:
10 |
11 | Groovy
12 |
13 | ```groovy
14 | allprojects {
15 | repositories {
16 | maven { url "https://jitpack.io" }
17 | }
18 | }
19 | ```
20 |
21 |
22 | Kotlin
23 |
24 | ```kotlin
25 | allprojects {
26 | repositories {
27 | maven(url = "https://jitpack.io")
28 | }
29 | }
30 | ```
31 |
32 |
33 |
34 | Add the following dependencies to your app or library's `build.gradle`:
35 |
36 | Groovy
37 |
38 | ```groovy
39 | dependencies {
40 | implementation "com.github.hyperdevs-team:android-app-updates-helper:2.0.0"
41 | }
42 | ```
43 |
44 |
45 |
46 | Kotlin
47 |
48 | ```kotlin
49 | dependencies {
50 | implementation("com.github.hyperdevs-team:android-app-updates-helper:2.0.0")
51 | }
52 | ```
53 |
54 |
55 | You'll also need to add support for Java 8 in your project. To do so:
56 | Groovy
57 |
58 | ```groovy
59 | android {
60 | compileOptions {
61 | sourceCompatibility JavaVersion.VERSION_1_8
62 | targetCompatibility JavaVersion.VERSION_1_8
63 | }
64 | kotlinOptions {
65 | jvmTarget = "1.8"
66 | }
67 | }
68 | ```
69 |
70 |
71 | Kotlin
72 |
73 | ```kotlin
74 | android {
75 | compileOptions {
76 | sourceCompatibility = JavaVersion.VERSION_1_8
77 | targetCompatibility = JavaVersion.VERSION_1_8
78 | }
79 | kotlinOptions {
80 | jvmTarget = "1.8"
81 | }
82 | }
83 | ```
84 |
85 |
86 | ## How to use
87 | * Create a new _AppUpdatesHelper_.
88 | * Start listening for app update changes with _AppUpdatesHelper.startListening()_, for example in _Activity.onCreate()_ or in _Fragment.onViewCreated()_.
89 | * Stop listening for app update changes with _AppUpdatesHelper.stopListening()_ in _Activity.onDestroy()_ or in _Fragment.onDestroyView()_.
90 | * Request app update information with _AppUpdatesHelper.getAppUpdateInfo()_.
91 | * Request a flexible or immediate update with _AppUpdatesHelper.startFlexibleUpdate()_ or _AppUpdatesHelper.startImmediateUpdate()_
92 |
93 | Check the [example app](app) for more implementation details about [flexible](app/src/main/kotlin/com/bq/appupdateshelper/flexible/FlexibleUpdateActivity.kt)
94 | and [immediate](app/src/main/kotlin/com/bq/appupdateshelper/immediate/ImmediateUpdateActivity.kt) updates.
95 |
96 | You can also use a [fake implementation](app/src/main/kotlin/com/bq/appupdateshelper/fake/FakeUpdateActivity.kt) to test in-app updates.
97 |
98 | Keep in mind that you may not see in-app updates if these conditions don't match:
99 | * The package name of the app is **exactly** the one you'd like to test in-app updates with.
100 | * The app must be signed with the same keys that you used to sign the app you want to test in-app updates with.
101 | * If the app is not published yet or you want to test with internal app sharing or closed tracks,
102 | ensure that any of your Google accounts in your device has access to said app in Google Play Store.
103 | * Check if the Google Play Store displays updates for the app you want to use to test in-app updates.
104 |
105 | Please ensure that all conditions apply when using this library in order to avoid unnecessary headaches.
106 |
107 | ### Using the example app
108 | In order to ease using the example app with the sample data of your own app,
109 | you can create an `app_config.properties` file in the root of the project with the following content:
110 | ```properties
111 | applicationId=your.application.id
112 | keystorePath=/full/path/to/your/keystore/file
113 | keystorePwd=your_keystore_password
114 | keystoreAlias=your_keystore_alias
115 | keystoreAliasPwd=your_keystore_alias_password
116 | ```
117 |
118 | These values will be picked up by the compilation process of the example app
119 | and will set the application ID and signing configurations for you.
120 |
121 | ## Authors & Collaborators
122 | * **[Adrián García](https://github.com/adriangl)** - *Author and maintainer*
123 | * **[Daniel Sánchez Ceinos](https://github.com/danielceinos)** - *Contributor*
124 |
125 | ## Acknowledgements
126 | The work in this repository up to April 28th, 2021 was done by [bq](https://github.com/bq).
127 | Thanks for all the work!!
128 |
129 | ## License
130 | This project is licensed under the Apache Software License, Version 2.0.
131 | ```
132 | Copyright (C) 2021 HyperDevs
133 |
134 | Copyright (C) 2019 BQ
135 |
136 | Licensed under the Apache License, Version 2.0 (the "License");
137 | you may not use this file except in compliance with the License.
138 | You may obtain a copy of the License at
139 |
140 | http://www.apache.org/licenses/LICENSE-2.0
141 |
142 | Unless required by applicable law or agreed to in writing, software
143 | distributed under the License is distributed on an "AS IS" BASIS,
144 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
145 | See the License for the specific language governing permissions and
146 | limitations under the License.
147 | ```
148 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | apply plugin: "com.android.application"
20 |
21 | apply plugin: "kotlin-android"
22 |
23 | apply plugin: "com.gladed.androidgitversion"
24 |
25 | apply from: "$rootDir/gradle/properties_utils.gradle"
26 |
27 | ext {
28 | /*
29 | ********************
30 | * Android variables
31 | ********************
32 | */
33 | compile_sdk_version = 34
34 | min_sdk_version = 21
35 | target_sdk_version = 34
36 | build_tools_version = "34.0.0"
37 | }
38 |
39 | android {
40 | namespace "com.hyperdevs.appupdateshelper.app"
41 | compileSdk = compile_sdk_version
42 | buildToolsVersion = build_tools_version
43 |
44 | defaultConfig {
45 | /*
46 | * Change your application ID to the app you want to test with
47 | *
48 | * Requires configuration via app_config.properties file or injected via environment variables.
49 | * The loadEnvOrProperty will try to find the environment variable (in snake_case) or the
50 | * property in signing.properties (converted to camelCase)
51 | */
52 | applicationId loadEnvOrProperty("APPLICATION_ID", "com.hyperdevs.appupdateshelper.app", "app_config.properties")
53 | minSdkVersion min_sdk_version
54 | targetSdkVersion target_sdk_version
55 | versionCode 1
56 | versionName androidGitVersion.name()
57 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
58 | }
59 |
60 | buildFeatures {
61 | viewBinding true
62 | }
63 |
64 | signingConfigs {
65 | /*
66 | * Local release signing configuration
67 | *
68 | * Requires configuration via app_config.properties file or injected via environment variables.
69 | * The loadEnvOrProperty will try to find the environment variable (in snake_case) or the
70 | * property in signing.properties (converted to camelCase)
71 | */
72 | localRelease {
73 | storeFile file(loadEnvOrProperty("KEYSTORE_PATH", new File(rootDir, "debug.keystore").path, "app_config.properties"))
74 | storePassword loadEnvOrProperty("KEYSTORE_PWD", "android", "app_config.properties")
75 | keyAlias loadEnvOrProperty("KEYSTORE_ALIAS", "androiddebugkey", "app_config.properties")
76 | keyPassword loadEnvOrProperty("KEYSTORE_ALIAS_PWD", "android", "app_config.properties")
77 | }
78 | }
79 |
80 | buildTypes {
81 | debug {
82 | signingConfig signingConfigs.localRelease
83 | }
84 |
85 | release {
86 | minifyEnabled false
87 | proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"
88 | signingConfig signingConfigs.localRelease
89 | }
90 | }
91 |
92 | sourceSets.configureEach {
93 | java.srcDirs += "src/${name}/kotlin"
94 | }
95 |
96 | compileOptions {
97 | sourceCompatibility JavaVersion.VERSION_1_8
98 | targetCompatibility JavaVersion.VERSION_1_8
99 | }
100 |
101 | kotlinOptions {
102 | jvmTarget = "1.8"
103 | }
104 | }
105 |
106 | dependencies {
107 | implementation project(":lib")
108 | implementation fileTree(dir: "libs", include: ["*.jar"])
109 |
110 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
111 |
112 | implementation "androidx.appcompat:appcompat:1.6.1"
113 | implementation "androidx.core:core-ktx:1.10.1"
114 | implementation "androidx.constraintlayout:constraintlayout:2.1.4"
115 |
116 | testImplementation "junit:junit:4.13.2"
117 |
118 | androidTestImplementation "androidx.test:runner:1.5.2"
119 | androidTestImplementation "androidx.test.espresso:espresso-core:3.5.1"
120 | implementation "com.google.android.material:material:1.9.0"
121 | }
122 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/hyperdevs/appupdateshelper/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper
20 |
21 | import androidx.test.InstrumentationRegistry
22 | import androidx.test.runner.AndroidJUnit4
23 |
24 | import org.junit.Test
25 | import org.junit.runner.RunWith
26 |
27 | import org.junit.Assert.*
28 |
29 | /**
30 | * Instrumented test, which will execute on an Android device.
31 | *
32 | * See [testing documentation](http://d.android.com/tools/testing).
33 | */
34 | @RunWith(AndroidJUnit4::class)
35 | class ExampleInstrumentedTest {
36 | @Test
37 | fun useAppContext() {
38 | // Context of the app under test.
39 | val appContext = InstrumentationRegistry.getTargetContext()
40 | assertEquals("com.bq.appupdateshelper", appContext.packageName)
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
20 |
22 |
23 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/hyperdevs/appupdateshelper/app/MainActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper.app
20 |
21 | import android.os.Bundle
22 | import android.widget.Button
23 | import androidx.appcompat.app.AppCompatActivity
24 | import com.hyperdevs.appupdateshelper.app.databinding.MainActivityBinding
25 | import com.hyperdevs.appupdateshelper.app.fake.FakeUpdateActivity
26 | import com.hyperdevs.appupdateshelper.app.flexible.FlexibleUpdateActivity
27 | import com.hyperdevs.appupdateshelper.app.fragment.FragmentUpdateActivity
28 | import com.hyperdevs.appupdateshelper.app.immediate.ImmediateUpdateActivity
29 |
30 | class MainActivity : AppCompatActivity() {
31 | private lateinit var binding: MainActivityBinding
32 |
33 | private val immediateButton: Button
34 | get() = binding.immediateButton
35 |
36 | private val flexibleButton: Button
37 | get() = binding.flexibleButton
38 |
39 | private val fragmentButton: Button
40 | get() = binding.fragmentButton
41 |
42 | private val fakeButton: Button
43 | get() = binding.fakeButton
44 |
45 | override fun onCreate(savedInstanceState: Bundle?) {
46 | super.onCreate(savedInstanceState)
47 | binding = MainActivityBinding.inflate(layoutInflater).apply {
48 | setContentView(root)
49 | }
50 |
51 | immediateButton.setOnClickListener {
52 | startActivity(ImmediateUpdateActivity.newIntent(this))
53 | }
54 |
55 | flexibleButton.setOnClickListener {
56 | startActivity(FlexibleUpdateActivity.newIntent(this))
57 | }
58 |
59 | fragmentButton.setOnClickListener {
60 | startActivity(FragmentUpdateActivity.newIntent(this))
61 | }
62 |
63 | fakeButton.setOnClickListener {
64 | startActivity(FakeUpdateActivity.newIntent(this))
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/hyperdevs/appupdateshelper/app/fake/FakeUpdateActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper.app.fake
20 |
21 | import android.content.Context
22 | import android.content.Intent
23 | import android.os.Bundle
24 | import android.os.Handler
25 | import android.util.Log
26 | import android.widget.Button
27 | import androidx.appcompat.app.AppCompatActivity
28 | import com.hyperdevs.appupdateshelper.AppUpdateInfoResult
29 | import com.hyperdevs.appupdateshelper.AppUpdateInstallState.Status.*
30 | import com.hyperdevs.appupdateshelper.FakeAppUpdatesHelper
31 | import com.hyperdevs.appupdateshelper.app.databinding.FakeUpdateActivityBinding
32 | import com.hyperdevs.appupdateshelper.app.R
33 | import com.hyperdevs.appupdateshelper.app.misc.showToast
34 | import com.google.android.material.snackbar.Snackbar
35 |
36 | /**
37 | * Activity that illustrates the use of the [FakeAppUpdatesHelper] class of the lib to simulate
38 | * app updates in test environments.
39 | *
40 | * In this class we'll simulate a flexible update scenario. In order to understand how flexible
41 | * updates work, please review [com.hyperdevs.appupdateshelper.flexible.FlexibleUpdateActivity].
42 | */
43 | class FakeUpdateActivity : AppCompatActivity() {
44 |
45 | companion object {
46 | private const val TAG = "FakeUpdateActivity"
47 | fun newIntent(context: Context): Intent {
48 | return Intent(context, FakeUpdateActivity::class.java)
49 | }
50 | }
51 |
52 | private lateinit var fakeAppUpdatesHelper: FakeAppUpdatesHelper
53 |
54 | private lateinit var binding: FakeUpdateActivityBinding
55 |
56 | private val startUpdateButton: Button
57 | get() = binding.startUpdateButton
58 |
59 | override fun onCreate(savedInstanceState: Bundle?) {
60 | super.onCreate(savedInstanceState)
61 |
62 | binding = FakeUpdateActivityBinding.inflate(layoutInflater).apply {
63 | setContentView(root)
64 | }
65 |
66 | setTitle(R.string.activity_fake_update_title)
67 |
68 | fakeAppUpdatesHelper = FakeAppUpdatesHelper(this)
69 |
70 | fakeAppUpdatesHelper.startListening { installState ->
71 |
72 | Log.d(TAG, "Update install state: $installState")
73 |
74 | when (installState.status) {
75 | UNKNOWN -> {
76 | showToast("Unknown install state")
77 | }
78 | DENIED -> {
79 | showToast("The user denied the flexible update!")
80 | finish()
81 | }
82 | REQUIRES_UI_INTENT -> {
83 | showToast("The update needs an UI intent!")
84 | }
85 | UPDATE_ACCEPTED -> {
86 | showToast("The user accepted the update!")
87 | }
88 | PENDING -> {
89 | showToast("Waiting for update to start!")
90 | }
91 | DOWNLOADING -> {
92 | showToast("The update is downloading!")
93 | }
94 | DOWNLOADED -> {
95 | showToast("The update is downloading! Progress: ${installState.downloadProgress}")
96 |
97 | Snackbar.make(binding.root, "Install the update?", Snackbar.LENGTH_INDEFINITE)
98 | .apply {
99 | setAction("Install") {
100 | fakeAppUpdatesHelper.completeUpdate()
101 |
102 | // Fake installation process
103 | fakeAppUpdatesHelper.completeFakeUpdate()
104 | }
105 | }
106 | .show()
107 | }
108 | INSTALLING -> {
109 | showToast("The update is being installed!")
110 | }
111 | INSTALLED -> {
112 | showToast("The update has been installed!")
113 | }
114 | FAILED -> {
115 | showToast("The update failed! Reason: ${installState.errorCode}")
116 |
117 | Snackbar.make(binding.root, "Retry?", Snackbar.LENGTH_LONG)
118 | .apply {
119 | setAction("Retry") {
120 | fakeAppUpdatesHelper.startImmediateUpdate(this@FakeUpdateActivity)
121 | }
122 | }
123 | .show()
124 | }
125 | CANCELED -> {
126 | showToast("The user canceled the flexible update!")
127 | }
128 | }
129 | }
130 |
131 | startUpdateButton.setOnClickListener {
132 | // We're going to set-up the fake in order to simulate an available update
133 | fakeAppUpdatesHelper.configAvailableUpdate()
134 |
135 | fakeAppUpdatesHelper.getAppUpdateInfo { appUpdateInfoResult ->
136 | Log.d(TAG, "App update info: $appUpdateInfoResult")
137 |
138 | if (appUpdateInfoResult.isSuccessful) {
139 | when (appUpdateInfoResult.updateAvailability!!) {
140 | AppUpdateInfoResult.Availability.UNKNOWN -> {
141 | showToast("The state of the update is unknown!")
142 | }
143 | AppUpdateInfoResult.Availability.UPDATE_NOT_AVAILABLE -> {
144 | showToast("No update available!")
145 | }
146 | AppUpdateInfoResult.Availability.UPDATE_AVAILABLE -> {
147 | showToast("Update available!")
148 | if (appUpdateInfoResult.canInstallFlexibleUpdate()) {
149 | // Start the update flow
150 | showToast("Can install flexible update!")
151 | fakeAppUpdatesHelper.startFlexibleUpdate(this)
152 |
153 | // Start faking the update flow
154 | fakeAppUpdatesHelper.startFakeInstallFlow()
155 | } else {
156 | showToast("Can not install flexible update!")
157 | }
158 | }
159 | AppUpdateInfoResult.Availability.UPDATE_IN_PROGRESS -> {
160 | showToast("Update in progress!")
161 | }
162 | AppUpdateInfoResult.Availability.UPDATE_DOWNLOADED -> {
163 | showToast("Update downloaded!")
164 | fakeAppUpdatesHelper.completeUpdate()
165 |
166 | // Start faking installation process
167 | fakeAppUpdatesHelper.completeFakeUpdate()
168 | }
169 | }
170 | } else {
171 | showToast("The update info could not be retrieved, " +
172 | "cause: ${appUpdateInfoResult.exception!!.message}")
173 | }
174 | }
175 | }
176 | }
177 |
178 | override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
179 | super.onActivityResult(requestCode, resultCode, data)
180 |
181 | // We bind this but the fake will not launch an external activity, so it won't effect
182 | // the flow
183 | fakeAppUpdatesHelper.onUpdateStatusResult(requestCode, resultCode)
184 | }
185 |
186 | override fun onDestroy() {
187 | super.onDestroy()
188 | fakeAppUpdatesHelper.stopListening()
189 | }
190 | }
191 |
192 | private fun FakeAppUpdatesHelper.configAvailableUpdate() {
193 | setUpdateAvailable(12345)
194 | }
195 |
196 | private fun FakeAppUpdatesHelper.startFakeInstallFlow() {
197 | val handler = Handler()
198 |
199 | with(handler) {
200 | postDelayed({ userAcceptsUpdate() }, 0)
201 | postDelayed({ downloadStarts() }, 1000)
202 | postDelayed({ downloadCompletes() }, 4000)
203 | }
204 | }
205 |
206 | private fun FakeAppUpdatesHelper.completeFakeUpdate() {
207 | val handler = Handler()
208 |
209 | with(handler) {
210 | postDelayed({ installCompletes() }, 4000)
211 | }
212 | }
213 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/hyperdevs/appupdateshelper/app/flexible/FlexibleUpdateActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper.app.flexible
20 |
21 | import android.content.Context
22 | import android.content.Intent
23 | import android.os.Bundle
24 | import android.util.Log
25 | import android.widget.Button
26 | import androidx.appcompat.app.AppCompatActivity
27 | import com.hyperdevs.appupdateshelper.AppUpdateInfoResult
28 | import com.hyperdevs.appupdateshelper.AppUpdateInstallState.Status.*
29 | import com.hyperdevs.appupdateshelper.AppUpdatesHelper
30 | import com.hyperdevs.appupdateshelper.app.databinding.FlexibleUpdateActivityBinding
31 | import com.hyperdevs.appupdateshelper.app.R
32 | import com.hyperdevs.appupdateshelper.app.misc.showToast
33 | import com.google.android.material.snackbar.Snackbar
34 |
35 | /**
36 | * Activity that illustrates the use of the [AppUpdatesHelper] class of the lib start flexible
37 | * updates.
38 | */
39 | class FlexibleUpdateActivity : AppCompatActivity() {
40 |
41 | companion object {
42 | private const val TAG = "FlexibleUpdateActivity"
43 | fun newIntent(context: Context): Intent {
44 | return Intent(context, FlexibleUpdateActivity::class.java)
45 | }
46 | }
47 |
48 | private lateinit var appUpdatesHelper: AppUpdatesHelper
49 |
50 | private lateinit var binding: FlexibleUpdateActivityBinding
51 |
52 | private val startUpdateButton: Button
53 | get() = binding.startUpdateButton
54 |
55 | override fun onCreate(savedInstanceState: Bundle?) {
56 | super.onCreate(savedInstanceState)
57 | binding = FlexibleUpdateActivityBinding.inflate(layoutInflater).apply {
58 | setContentView(root)
59 | }
60 |
61 | setTitle(R.string.activity_flexible_update_title)
62 |
63 | // Instantiate the app updates helper and start using it with startListening()
64 | appUpdatesHelper = AppUpdatesHelper(this)
65 |
66 | appUpdatesHelper.startListening { installState ->
67 | // The update process is tracked here from the moment the user clicks "Update" until the
68 | // app is fully installed
69 | Log.d(TAG, "Update install state: $installState")
70 |
71 | when (installState.status) {
72 | UNKNOWN -> {
73 | showToast("Unknown install state")
74 | }
75 | DENIED -> {
76 | // This should only be reached in immediate updates
77 | showToast("The user denied the flexible update!")
78 | finish()
79 | }
80 | REQUIRES_UI_INTENT -> {
81 | // The docs don't really say anything about this state or when it's triggered
82 | // so...
83 | showToast("The update needs an UI intent!")
84 | }
85 | UPDATE_ACCEPTED -> {
86 | // The user has accepted the update, so you can notify the user
87 | showToast("The user accepted the update!")
88 | }
89 | PENDING -> {
90 | showToast("Waiting for update to start!")
91 | }
92 | DOWNLOADING -> {
93 | showToast("The update is downloading! Progress: ${installState.downloadProgress}")
94 | }
95 | DOWNLOADED -> {
96 | showToast("The update has been downloaded!")
97 | // Prompt the user to install the update when we know that the update has been
98 | // downloaded successfully
99 | Snackbar.make(binding.root, "Install the update?", Snackbar.LENGTH_INDEFINITE)
100 | .apply {
101 | setAction("Install") {
102 | appUpdatesHelper.completeUpdate()
103 | }
104 | }
105 | .show()
106 | }
107 | INSTALLING -> {
108 | showToast("The update is being installed!")
109 | }
110 | INSTALLED -> {
111 | // Usually you won't get up to this state, since the app closes automatically
112 | // in the installation process. Anyway, it's not a bad practice to consider this
113 | // case
114 | showToast("The update has been installed!")
115 | }
116 | FAILED -> {
117 | // The installation failed for some reason, here you can retry the update
118 | // process if needed
119 | showToast("The update failed! Reason: ${installState.errorCode}")
120 |
121 | Snackbar.make(binding.root, "Retry?", Snackbar.LENGTH_LONG)
122 | .apply {
123 | setAction("Retry") {
124 | appUpdatesHelper.startFlexibleUpdate(this@FlexibleUpdateActivity)
125 | }
126 | }
127 | .show()
128 | }
129 | CANCELED -> {
130 | // This state is only reachable in flexible updates and it happens when the
131 | // user cancels a flexible update. There's no need to do anything in this case.
132 | showToast("The user canceled the flexible update!")
133 | }
134 | }
135 | }
136 |
137 | startUpdateButton.setOnClickListener {
138 | // Start the update flow by first checking if there's any update available for the app
139 | // in the Play Store using getAppUpdateInfo()
140 | appUpdatesHelper.getAppUpdateInfo { appUpdateInfoResult ->
141 | Log.d(TAG, "App update info: $appUpdateInfoResult")
142 |
143 | if (appUpdateInfoResult.isSuccessful) {
144 | // If the request went well, you can check the state of the app update
145 | when (appUpdateInfoResult.updateAvailability!!) {
146 | AppUpdateInfoResult.Availability.UNKNOWN -> {
147 | showToast("The state of the update is unknown!")
148 | }
149 | AppUpdateInfoResult.Availability.UPDATE_NOT_AVAILABLE -> {
150 | showToast("No update available!")
151 | }
152 | AppUpdateInfoResult.Availability.UPDATE_AVAILABLE -> {
153 | showToast("Update available!")
154 | // When we know that the update is available, we must check if we can
155 | // perform the desired type of update
156 | if (appUpdateInfoResult.canInstallFlexibleUpdate()) {
157 | // Start the update flow
158 | showToast("Can install flexible update!")
159 | appUpdatesHelper.startFlexibleUpdate(this)
160 | } else {
161 | showToast("Can not install flexible update!")
162 | }
163 | }
164 | AppUpdateInfoResult.Availability.UPDATE_IN_PROGRESS -> {
165 | // If the update is in progress, we don't need to jump to the flexible flow again
166 | showToast("Update in progress!")
167 | }
168 | AppUpdateInfoResult.Availability.UPDATE_DOWNLOADED -> {
169 | // The app update is downloaded, but the install flow has not started
170 | // yet, so complete the update
171 | showToast("Update downloaded!")
172 | appUpdatesHelper.completeUpdate()
173 | }
174 | }
175 | } else {
176 | showToast("The update info could not be retrieved, " +
177 | "cause: ${appUpdateInfoResult.exception!!.message}")
178 | }
179 | }
180 | }
181 | }
182 |
183 | override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
184 | super.onActivityResult(requestCode, resultCode, data)
185 |
186 | // We have to bind the helper to the activity results so it can properly dispatch some
187 | // update events
188 | appUpdatesHelper.onUpdateStatusResult(requestCode, resultCode)
189 | }
190 |
191 | override fun onDestroy() {
192 | // Stop listening for updates with stopListening()
193 | super.onDestroy()
194 | appUpdatesHelper.stopListening()
195 | }
196 | }
197 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/hyperdevs/appupdateshelper/app/fragment/FragmentUpdateActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper.app.fragment
20 |
21 | import android.content.Context
22 | import android.content.Intent
23 | import android.os.Bundle
24 | import androidx.appcompat.app.AppCompatActivity
25 | import com.hyperdevs.appupdateshelper.AppUpdatesHelper
26 | import com.hyperdevs.appupdateshelper.app.R
27 | import com.hyperdevs.appupdateshelper.app.databinding.FragmentUpdateActivityBinding
28 |
29 | /**
30 | * Activity that illustrates the use of the [AppUpdatesHelper] class of the lib to start flexible
31 | * updates in a fragment.
32 | */
33 | class FragmentUpdateActivity : AppCompatActivity() {
34 | companion object {
35 | fun newIntent(context: Context): Intent {
36 | return Intent(context, FragmentUpdateActivity::class.java)
37 | }
38 | }
39 |
40 | private lateinit var binding: FragmentUpdateActivityBinding
41 |
42 | override fun onCreate(savedInstanceState: Bundle?) {
43 | super.onCreate(savedInstanceState)
44 | binding = FragmentUpdateActivityBinding.inflate(layoutInflater).apply {
45 | setContentView(root)
46 | }
47 |
48 | setTitle(R.string.activity_fragment_update_title)
49 | }
50 | }
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/hyperdevs/appupdateshelper/app/fragment/FragmentUpdateFragment.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper.app.fragment
20 |
21 | import android.content.Intent
22 | import android.os.Bundle
23 | import android.util.Log
24 | import android.view.LayoutInflater
25 | import android.view.View
26 | import android.view.ViewGroup
27 | import android.widget.Button
28 | import androidx.fragment.app.Fragment
29 | import com.hyperdevs.appupdateshelper.AppUpdateInfoResult
30 | import com.hyperdevs.appupdateshelper.AppUpdateInstallState
31 | import com.hyperdevs.appupdateshelper.AppUpdatesHelper
32 | import com.hyperdevs.appupdateshelper.app.databinding.FragmentUpdateFragmentBinding
33 | import com.hyperdevs.appupdateshelper.app.misc.showToast
34 | import com.google.android.material.snackbar.Snackbar
35 |
36 | /**
37 | * Fragment that illustrates the use of the [AppUpdatesHelper] class of the lib to start flexible
38 | * updates in a fragment.
39 | */
40 | class FragmentUpdateFragment : Fragment() {
41 | companion object {
42 | private const val TAG = "FragmentUpdateFragment"
43 |
44 | fun newInstance(): FragmentUpdateFragment {
45 | val args = Bundle()
46 |
47 | val fragment = FragmentUpdateFragment()
48 | fragment.arguments = args
49 | return fragment
50 | }
51 | }
52 |
53 | private lateinit var appUpdatesHelper: AppUpdatesHelper
54 |
55 | private lateinit var binding: FragmentUpdateFragmentBinding
56 |
57 | private val startUpdateButton: Button
58 | get() = binding.startUpdateButton
59 |
60 | override fun onCreateView(inflater: LayoutInflater,
61 | container: ViewGroup?,
62 | savedInstanceState: Bundle?): View? =
63 | FragmentUpdateFragmentBinding.inflate(inflater, container, false)
64 | .also { binding = it }.root
65 |
66 |
67 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
68 | super.onViewCreated(view, savedInstanceState)
69 | // Instantiate the app updates helper and start using it with startListening()
70 | appUpdatesHelper = AppUpdatesHelper(requireContext())
71 |
72 | appUpdatesHelper.startListening { installState ->
73 | // The update process is tracked here from the moment the user clicks "Update" until the
74 | // app is fully installed
75 | Log.d(TAG, "Update install state: $installState")
76 |
77 | when (installState.status) {
78 | AppUpdateInstallState.Status.UNKNOWN -> {
79 | showToast("Unknown install state")
80 | }
81 | AppUpdateInstallState.Status.DENIED -> {
82 | // This should only be reached in immediate updates
83 | showToast("The user denied the flexible update!")
84 | requireActivity().finish()
85 | }
86 | AppUpdateInstallState.Status.REQUIRES_UI_INTENT -> {
87 | // The docs don't really say anything about this state or when it's triggered
88 | // so...
89 | showToast("The update needs an UI intent!")
90 | }
91 | AppUpdateInstallState.Status.UPDATE_ACCEPTED -> {
92 | // The user has accepted the update, so you can notify the user
93 | showToast("The user accepted the update!")
94 | }
95 | AppUpdateInstallState.Status.PENDING -> {
96 | showToast("Waiting for update to start!")
97 | }
98 | AppUpdateInstallState.Status.DOWNLOADING -> {
99 | showToast("The update is downloading! Progress: ${installState.downloadProgress}")
100 | }
101 | AppUpdateInstallState.Status.DOWNLOADED -> {
102 | showToast("The update has been downloaded!")
103 | // Prompt the user to install the update when we know that the update has been
104 | // downloaded successfully
105 | Snackbar.make(binding.root, "Install the update?", Snackbar.LENGTH_INDEFINITE)
106 | .apply {
107 | setAction("Install") {
108 | appUpdatesHelper.completeUpdate()
109 | }
110 | }
111 | .show()
112 | }
113 | AppUpdateInstallState.Status.INSTALLING -> {
114 | showToast("The update is being installed!")
115 | }
116 | AppUpdateInstallState.Status.INSTALLED -> {
117 | // Usually you won't get up to this state, since the app closes automatically
118 | // in the installation process. Anyway, it's not a bad practice to consider this
119 | // case
120 | showToast("The update has been installed!")
121 | }
122 | AppUpdateInstallState.Status.FAILED -> {
123 | // The installation failed for some reason, here you can retry the update
124 | // process if needed
125 | showToast("The update failed! Reason: ${installState.errorCode}")
126 |
127 | Snackbar.make(binding.root, "Retry?", Snackbar.LENGTH_LONG)
128 | .apply {
129 | setAction("Retry") {
130 | appUpdatesHelper.startFlexibleUpdate(this@FragmentUpdateFragment)
131 | }
132 | }
133 | .show()
134 | }
135 | AppUpdateInstallState.Status.CANCELED -> {
136 | // This state is only reachable in flexible updates and it happens when the
137 | // user cancels a flexible update. There's no need to do anything in this case.
138 | showToast("The user canceled the flexible update!")
139 | }
140 | }
141 | }
142 |
143 | startUpdateButton.setOnClickListener {
144 | // Start the update flow by first checking if there's any update available for the app
145 | // in the Play Store using getAppUpdateInfo()
146 | appUpdatesHelper.getAppUpdateInfo { appUpdateInfoResult ->
147 | Log.d(TAG, "App update info: $appUpdateInfoResult")
148 |
149 | if (appUpdateInfoResult.isSuccessful) {
150 | // If the request went well, you can check the state of the app update
151 | when (appUpdateInfoResult.updateAvailability!!) {
152 | AppUpdateInfoResult.Availability.UNKNOWN -> {
153 | showToast("The state of the update is unknown!")
154 | }
155 | AppUpdateInfoResult.Availability.UPDATE_NOT_AVAILABLE -> {
156 | showToast("No update available!")
157 | }
158 | AppUpdateInfoResult.Availability.UPDATE_AVAILABLE -> {
159 | showToast("Update available!")
160 | // When we know that the update is available, we must check if we can
161 | // perform the desired type of update
162 | if (appUpdateInfoResult.canInstallFlexibleUpdate()) {
163 | // Start the update flow
164 | showToast("Can install flexible update!")
165 | appUpdatesHelper.startFlexibleUpdate(this)
166 | } else {
167 | showToast("Can not install flexible update!")
168 | }
169 | }
170 | AppUpdateInfoResult.Availability.UPDATE_IN_PROGRESS -> {
171 | // If the update is in progress, we don't need to jump to the flexible flow again
172 | showToast("Update in progress!")
173 | }
174 | AppUpdateInfoResult.Availability.UPDATE_DOWNLOADED -> {
175 | // The app update is downloaded, but the install flow has not started
176 | // yet, so complete the update
177 | showToast("Update downloaded!")
178 | appUpdatesHelper.completeUpdate()
179 | }
180 | }
181 | } else {
182 | showToast("The update info could not be retrieved, " +
183 | "cause: ${appUpdateInfoResult.exception!!.message}")
184 | }
185 | }
186 | }
187 | }
188 |
189 | override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
190 | super.onActivityResult(requestCode, resultCode, data)
191 |
192 | // We have to bind the helper to the activity results so it can properly dispatch some
193 | // update events
194 | appUpdatesHelper.onUpdateStatusResult(requestCode, resultCode)
195 | }
196 |
197 | override fun onDestroyView() {
198 | // Stop listening for updates with stopListening()
199 | super.onDestroyView()
200 | appUpdatesHelper.stopListening()
201 | }
202 | }
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/hyperdevs/appupdateshelper/app/immediate/ImmediateUpdateActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper.app.immediate
20 |
21 | import android.content.Context
22 | import android.content.Intent
23 | import android.os.Bundle
24 | import android.util.Log
25 | import android.widget.Button
26 | import androidx.appcompat.app.AppCompatActivity
27 | import com.hyperdevs.appupdateshelper.AppUpdateInfoResult
28 | import com.hyperdevs.appupdateshelper.AppUpdateInstallState.Status.*
29 | import com.hyperdevs.appupdateshelper.AppUpdatesHelper
30 | import com.hyperdevs.appupdateshelper.app.databinding.ImmediateUpdateActivityBinding
31 | import com.hyperdevs.appupdateshelper.app.R
32 | import com.hyperdevs.appupdateshelper.app.misc.showToast
33 | import com.google.android.material.snackbar.Snackbar
34 |
35 | /**
36 | * Activity that illustrates the use of the [AppUpdatesHelper] class of the lib start immediate
37 | * updates.
38 | */
39 | class ImmediateUpdateActivity : AppCompatActivity() {
40 |
41 | companion object {
42 | private const val TAG = "ImmediateUpdateActivity"
43 | fun newIntent(context: Context): Intent {
44 | return Intent(context, ImmediateUpdateActivity::class.java)
45 | }
46 | }
47 |
48 | private lateinit var appUpdatesHelper: AppUpdatesHelper
49 |
50 | private lateinit var binding: ImmediateUpdateActivityBinding
51 |
52 | private val startUpdateButton: Button
53 | get() = binding.startUpdateButton
54 |
55 | override fun onCreate(savedInstanceState: Bundle?) {
56 | super.onCreate(savedInstanceState)
57 | binding = ImmediateUpdateActivityBinding.inflate(layoutInflater).apply {
58 | setContentView(root)
59 | }
60 |
61 | setTitle(R.string.activity_immediate_update_title)
62 |
63 | // Instantiate the app updates helper and start using it with startListening()
64 | appUpdatesHelper = AppUpdatesHelper(this)
65 |
66 | appUpdatesHelper.startListening { installState ->
67 | // The update process is tracked here from the moment the user clicks "Update" until the
68 | // app is fully installed
69 | Log.d(TAG, "Update install state: $installState")
70 |
71 | when (installState.status) {
72 | UNKNOWN -> {
73 | showToast("Unknown install state")
74 | }
75 | DENIED -> {
76 | // This state is only reachable in immediate updates, and it happens when the
77 | // user cancels an immediate update. Here you can finish your activity.
78 | showToast("The user denied the immediate update!")
79 | finish()
80 | }
81 | REQUIRES_UI_INTENT -> {
82 | // The docs don't really say anything about this state or when it's triggered
83 | // so...
84 | showToast("The update needs an UI intent!")
85 | }
86 | UPDATE_ACCEPTED -> {
87 | // The user has accepted the update, so you can notify the user
88 | // This is not guaranteed to arrive in immediate updates.
89 | showToast("The user accepted the update!")
90 | }
91 | PENDING -> {
92 | showToast("Waiting for update to start!")
93 | }
94 | DOWNLOADING -> {
95 | showToast("The update is downloading! Progress: ${installState.downloadProgress}")
96 | }
97 | DOWNLOADED -> {
98 | showToast("The update has been downloaded!")
99 | }
100 | INSTALLING -> {
101 | showToast("The update is being installed!")
102 | }
103 | INSTALLED -> {
104 | // Usually you won't get up to this state, since the app closes automatically
105 | // in the installation process. Anyway, it's not a bad practice to consider this
106 | // case
107 | showToast("The update has been installed!")
108 | }
109 | FAILED -> {
110 | // The installation failed for some reason, here you can retry the update
111 | // process if needed
112 | showToast("The update failed! Reason: ${installState.errorCode}")
113 |
114 | Snackbar.make(binding.root, "Retry?", Snackbar.LENGTH_LONG)
115 | .apply {
116 | setAction("Retry") {
117 | appUpdatesHelper.startImmediateUpdate(this@ImmediateUpdateActivity)
118 | }
119 | }
120 | .show()
121 | }
122 | CANCELED -> {
123 | // This state is only reachable in flexible updates.
124 | showToast("The user canceled the immediate update!")
125 | }
126 | }
127 | }
128 |
129 | startUpdateButton.setOnClickListener {
130 | // Start the update flow by first checking if there's any update available for the app
131 | // in the Play Store using getAppUpdateInfo()
132 | appUpdatesHelper.getAppUpdateInfo { appUpdateInfoResult ->
133 | Log.d(TAG, "App update info: $appUpdateInfoResult")
134 |
135 | if (appUpdateInfoResult.isSuccessful) {
136 | // If the request went well, you can check the state of the app update
137 | when (appUpdateInfoResult.updateAvailability!!) {
138 | AppUpdateInfoResult.Availability.UNKNOWN -> {
139 | showToast("The state of the update is unknown!")
140 | }
141 | AppUpdateInfoResult.Availability.UPDATE_NOT_AVAILABLE -> {
142 | showToast("No update available!")
143 | }
144 | AppUpdateInfoResult.Availability.UPDATE_AVAILABLE -> {
145 | showToast("Update available!")
146 | // When we know that the update is available, we must check if we can
147 | // perform the desired type of update
148 | if (appUpdateInfoResult.canInstallImmediateUpdate()) {
149 | // Start the update flow immediately
150 | showToast("Can install immediate update!")
151 | appUpdatesHelper.startImmediateUpdate(this)
152 | } else {
153 | showToast("Can not install immediate update!")
154 | }
155 | }
156 | AppUpdateInfoResult.Availability.UPDATE_IN_PROGRESS -> {
157 | // If the update is in progress, we can jump to the immediate flow again
158 | showToast("Update in progress!")
159 | appUpdatesHelper.startImmediateUpdate(this)
160 | }
161 | AppUpdateInfoResult.Availability.UPDATE_DOWNLOADED -> {
162 | // The app update is downloaded, but the install flow has not started
163 | // yet, so complete the update
164 | showToast("Update downloaded!")
165 | appUpdatesHelper.completeUpdate()
166 | }
167 | }
168 | } else {
169 | showToast("The update info could not be retrieved, " +
170 | "cause: ${appUpdateInfoResult.exception!!.message}")
171 | }
172 | }
173 | }
174 | }
175 |
176 | override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
177 | super.onActivityResult(requestCode, resultCode, data)
178 |
179 | // We have to bind the helper to the activity results so it can properly dispatch some
180 | // update events
181 | appUpdatesHelper.onUpdateStatusResult(requestCode, resultCode)
182 | }
183 |
184 | override fun onDestroy() {
185 | // Stop listening for updates with stopListening()
186 | super.onDestroy()
187 | appUpdatesHelper.stopListening()
188 | }
189 | }
190 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/hyperdevs/appupdateshelper/app/misc/ActivityExtensions.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper.app.misc
20 |
21 | import android.app.Activity
22 | import android.widget.Toast
23 | import androidx.annotation.StringRes
24 |
25 | /**
26 | * Displays a text as a toast in the current activity.
27 | *
28 | * @param text Text to display in the toast
29 | * @param duration Duration, one of [Toast.LENGTH_SHORT] or [Toast.LENGTH_LONG]
30 | */
31 | fun Activity.showToast(text: String, duration: Int = Toast.LENGTH_SHORT) {
32 | Toast.makeText(this, text, duration).show()
33 | }
34 |
35 | /**
36 | * Displays a text as a toast in the current activity.
37 | *
38 | * @param stringResId Text to display in the toast as a string resource ID
39 | * @param duration Duration, one of [Toast.LENGTH_SHORT] or [Toast.LENGTH_LONG]
40 | */
41 | fun Activity.showToast(@StringRes stringResId: Int, duration: Int = Toast.LENGTH_SHORT) {
42 | Toast.makeText(this, stringResId, duration).show()
43 | }
44 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/hyperdevs/appupdateshelper/app/misc/FragmentExtensions.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper.app.misc
20 |
21 | import android.widget.Toast
22 | import androidx.annotation.StringRes
23 | import androidx.fragment.app.Fragment
24 |
25 | /**
26 | * Displays a text as a toast in the current fragment.
27 | *
28 | * @param text Text to display in the toast
29 | * @param duration Duration, one of [Toast.LENGTH_SHORT] or [Toast.LENGTH_LONG]
30 | */
31 | fun Fragment.showToast(text: String, duration: Int = Toast.LENGTH_SHORT) {
32 | Toast.makeText(context, text, duration).show()
33 | }
34 |
35 | /**
36 | * Displays a text as a toast in the current fragment.
37 | *
38 | * @param stringResId Text to display in the toast as a string resource ID
39 | * @param duration Duration, one of [Toast.LENGTH_SHORT] or [Toast.LENGTH_LONG]
40 | */
41 | fun Fragment.showToast(@StringRes stringResId: Int, duration: Int = Toast.LENGTH_SHORT) {
42 | Toast.makeText(context, stringResId, duration).show()
43 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 |
25 |
30 |
31 |
37 |
40 |
43 |
44 |
45 |
46 |
52 |
53 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
20 |
26 |
28 |
30 |
32 |
34 |
36 |
38 |
40 |
42 |
44 |
46 |
48 |
50 |
52 |
54 |
56 |
58 |
60 |
62 |
64 |
66 |
68 |
70 |
72 |
74 |
76 |
78 |
80 |
82 |
84 |
86 |
88 |
90 |
92 |
93 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fake_update_activity.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
20 |
28 |
29 |
36 |
37 |
45 |
46 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/flexible_update_activity.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
20 |
28 |
29 |
36 |
37 |
45 |
46 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_update_activity.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
20 |
23 |
24 |
29 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_update_fragment.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
20 |
28 |
29 |
36 |
37 |
45 |
46 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/immediate_update_activity.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
20 |
29 |
30 |
37 |
38 |
46 |
47 |
56 |
57 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/main_activity.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 |
26 |
27 |
37 |
38 |
47 |
48 |
57 |
58 |
67 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hyperdevs-team/android-app-updates-helper/b44973e2807294477b524a7ae9d1d390ccff3e31/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hyperdevs-team/android-app-updates-helper/b44973e2807294477b524a7ae9d1d390ccff3e31/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hyperdevs-team/android-app-updates-helper/b44973e2807294477b524a7ae9d1d390ccff3e31/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hyperdevs-team/android-app-updates-helper/b44973e2807294477b524a7ae9d1d390ccff3e31/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hyperdevs-team/android-app-updates-helper/b44973e2807294477b524a7ae9d1d390ccff3e31/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hyperdevs-team/android-app-updates-helper/b44973e2807294477b524a7ae9d1d390ccff3e31/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hyperdevs-team/android-app-updates-helper/b44973e2807294477b524a7ae9d1d390ccff3e31/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hyperdevs-team/android-app-updates-helper/b44973e2807294477b524a7ae9d1d390ccff3e31/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hyperdevs-team/android-app-updates-helper/b44973e2807294477b524a7ae9d1d390ccff3e31/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hyperdevs-team/android-app-updates-helper/b44973e2807294477b524a7ae9d1d390ccff3e31/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
20 |
21 | #008577
22 | #00574B
23 | #D81B60
24 |
25 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 |
20 | App Updates Helper
21 | App Updates Helper
22 | Flexible updates example
23 | Immediate updates example
24 | Fake updates example
25 | In-app updates in Fragments
26 |
27 |
28 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 |
20 |
21 |
22 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/app/src/test/java/com/hyperdevs/appupdateshelper/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper
20 |
21 | import org.junit.Test
22 |
23 | import org.junit.Assert.*
24 |
25 | /**
26 | * Example local unit test, which will execute on the development machine (host).
27 | *
28 | * See [testing documentation](http://d.android.com/tools/testing).
29 | */
30 | class ExampleUnitTest {
31 | @Test
32 | fun addition_isCorrect() {
33 | assertEquals(4, 2 + 2)
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2019 BQ
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
18 |
19 | buildscript {
20 | ext.kotlin_version = "1.8.22"
21 |
22 | repositories {
23 | google()
24 | mavenCentral()
25 | maven { url "https://plugins.gradle.org/m2/" }
26 | }
27 | dependencies {
28 | classpath "com.android.tools.build:gradle:7.4.2"
29 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
30 | classpath "com.gladed.androidgitversion:gradle-android-git-version:0.4.14"
31 | }
32 | }
33 |
34 | allprojects {
35 | repositories {
36 | google()
37 | mavenCentral()
38 | maven { url "https://plugins.gradle.org/m2/" }
39 | }
40 |
41 | ext {
42 | kotlin_version = "1.8.22"
43 | }
44 | }
45 |
46 | task clean(type: Delete) {
47 | delete rootProject.buildDir
48 | }
49 |
--------------------------------------------------------------------------------
/checkstyle.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
20 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
--------------------------------------------------------------------------------
/code-style.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 |
20 |
21 |
22 |
25 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | xmlns:android
107 | ^$
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 | xmlns:.*
117 | ^$
118 |
119 |
120 | BY_NAME
121 |
122 |
123 |
124 |
125 |
126 |
127 | .*:id
128 | http://schemas.android.com/apk/res/android\n
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 | .*:name
139 | http://schemas.android.com/apk/res/android\n
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 | name
150 | ^$
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 | style
160 | ^$
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 | .*
170 | ^$
171 |
172 |
173 | BY_NAME
174 |
175 |
176 |
177 |
178 |
179 |
180 | .*:layout_width
181 | http://schemas.android.com/apk/res/android\n
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 | .*:layout_height
192 | http://schemas.android.com/apk/res/android\n
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 | .*:layout_.*
203 | http://schemas.android.com/apk/res/android\n
204 |
205 |
206 |
207 | BY_NAME
208 |
209 |
210 |
211 |
212 |
213 |
214 | .*:width
215 | http://schemas.android.com/apk/res/android\n
216 |
217 |
218 |
219 | BY_NAME
220 |
221 |
222 |
223 |
224 |
225 |
226 | .*:height
227 | http://schemas.android.com/apk/res/android\n
228 |
229 |
230 |
231 | BY_NAME
232 |
233 |
234 |
235 |
236 |
237 |
238 | .*
239 | http://schemas.android.com/apk/res/android\n
240 |
241 |
242 |
243 | BY_NAME
244 |
245 |
246 |
247 |
248 |
249 |
250 | .*
251 | .*
252 |
253 |
254 | BY_NAME
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 |
263 |
264 |
265 |
266 |
267 |
268 |
269 |
270 |
271 |
--------------------------------------------------------------------------------
/debug.keystore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hyperdevs-team/android-app-updates-helper/b44973e2807294477b524a7ae9d1d390ccff3e31/debug.keystore
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (C) 2021 HyperDevs
3 | #
4 | # Copyright (C) 2019 BQ
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 | # http://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 | # Project-wide Gradle settings.
20 | #
21 | # IDE (e.g. Android Studio) users:
22 | # Gradle settings configured through the IDE *will override*
23 | # any settings specified in this file.
24 | # For more details on how to configure your build environment visit
25 | # http://www.gradle.org/docs/current/userguide/build_environment.html
26 |
27 | # Specifies the JVM arguments used for the daemon process.
28 | # The setting is particularly useful for tweaking memory settings.
29 | org.gradle.jvmargs=-Xmx1536m
30 |
31 | # When configured, Gradle will run in incubating parallel mode.
32 | # This option should only be used with decoupled projects. More details, visit
33 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
34 | # org.gradle.parallel=true
35 |
36 | # AndroidX package structure to make it clearer which packages are bundled with the
37 | # Android operating system, and which are packaged with your app's APK
38 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
39 | android.useAndroidX=true
40 | # Automatically convert third-party libraries to use AndroidX
41 | android.enableJetifier=true
--------------------------------------------------------------------------------
/gradle/properties_utils.gradle:
--------------------------------------------------------------------------------
1 | /**
2 | * Utility method that loads a Properties object from a given file name.
3 | *
4 | * @param fileName name of the properties file
5 | * @return a Properties object, empty if the file could not be loaded
6 | */
7 | def loadPropertiesFile(fileName) {
8 | try {
9 | Properties properties = new Properties()
10 | properties.load(new FileInputStream(rootProject.file(fileName)))
11 |
12 | return properties
13 | }
14 | catch (ignored) {
15 | logger.info("File \"$fileName\" not found, returning empty properties object")
16 | return new Properties()
17 | }
18 | }
19 |
20 | /**
21 | * Utility method that tries to find a variable in the following places:
22 | * - System environment variable
23 | * - Property in project properties
24 | * - Property in a properties file (the property will try to find the name in camel case)
25 | *
26 | * System environment property takes precedence over the property in a properties file.
27 | *
28 | * @param key Key to find in snake case
29 | * @param defaultValue Default value in case the key is not found, null by default
30 | * @param propertiesFileName file in the root of the project to check for properties. If not defined,
31 | * it will default to the project's gradle.properties
32 | */
33 | def loadEnvOrProperty(String key, defaultValue = null, String propertiesFileName = "gradle.properties") {
34 | def envVarKey = key
35 | def propertyKey = toCamelCase(key)
36 |
37 | logger.info("Trying to find environment variable \"$envVarKey\" (or $propertiesFileName property \"$propertyKey\")")
38 |
39 | // First try to get the value from the environment variable
40 | def result = System.getenv(envVarKey)
41 |
42 | if (result == null) {
43 | logger.info("Environment variable \"$envVarKey\" not found, trying to find it in project property \"$propertyKey\"")
44 |
45 | // Then, try to get it from project properties
46 | try {
47 | result = project.property(propertyKey)
48 | } catch (e) {
49 | result = null
50 | }
51 |
52 | if (result == null) {
53 | logger.info("Project property \"$propertyKey\" not found, trying to find it in $propertiesFileName property \"$propertyKey\"")
54 |
55 | // Finally, try to get it from the properties file
56 | def properties = loadPropertiesFile(propertiesFileName)
57 |
58 | if (properties == null) {
59 | // If none could be found, return the default value
60 | logger.error("Requested file $propertiesFileName not found, returning default value")
61 | return defaultValue
62 | }
63 |
64 | result = properties[propertyKey]
65 | }
66 | }
67 |
68 | if (result == null) {
69 | logger.error("Environment variable \"$envVarKey\" (or property \"$propertyKey\" in project properties or $propertiesFileName) not found, returning default value")
70 | return defaultValue
71 | }
72 | else {
73 | return result
74 | }
75 | }
76 |
77 | static String toCamelCase(String text, boolean capitalized = false) {
78 | def newText = text.toLowerCase().replaceAll("(_)([A-Za-z0-9])", { Object[] it -> it[2].toUpperCase() })
79 | return capitalized ? capitalize(newText) : newText
80 | }
81 |
82 | ext {
83 | loadPropertiesFile = this.&loadPropertiesFile
84 | loadEnvOrProperty = this.&loadEnvOrProperty
85 | }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hyperdevs-team/android-app-updates-helper/b44973e2807294477b524a7ae9d1d390ccff3e31/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Apr 28 22:10:44 CEST 2021
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/jitpack-android.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 HyperDevs
3 | *
4 | * Copyright 2020 BQ
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 | * http://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 | apply plugin: "maven-publish"
20 |
21 | group = "com.hyperdevs"
22 | version = androidGitVersion.name()
23 |
24 | android {
25 | publishing {
26 | singleVariant("release") {
27 | withSourcesJar()
28 | withJavadocJar()
29 | }
30 | }
31 | }
32 |
33 | afterEvaluate {
34 | publishing {
35 | publications {
36 | // Creates a Maven publication called "release".
37 | release(MavenPublication) {
38 | from components.release
39 | artifactId = "appupdateshelper"
40 |
41 | pom {
42 | name = "Android App Updates Helper"
43 | description = "This utility library aims to help Android developers to use the Google Play In-App Updates API in an easy way."
44 | url = "https://github.com/hyperdevs-team/android-app-updates-helper"
45 | version = androidGitVersion.name()
46 | inceptionYear = "2019"
47 |
48 | licenses {
49 | license {
50 | name = "The Apache License, Version 2.0"
51 | url = "http://www.apache.org/licenses/LICENSE-2.0.txt"
52 | }
53 | }
54 |
55 | organization {
56 | name = "HyperDevs"
57 | url = "https://github.com/hyperdevs-team"
58 | }
59 |
60 | issueManagement {
61 | system = "GitHub Issues"
62 | url = "https://github.com/hyperdevs-team/android-app-updates-helper/issues"
63 | }
64 |
65 | scm {
66 | connection = "git@github.com:hyperdevs-team/android-app-updates-helper.git"
67 | url = "https://github.com/hyperdevs-team/android-app-updates-helper.git"
68 | }
69 |
70 | developers {
71 | developer {
72 | name = "Adrián García"
73 | id = "adriangl"
74 | url = "https://github.com/adriangl"
75 | roles = ["Maintainer"]
76 | }
77 | }
78 | }
79 | }
80 | }
81 | }
82 | }
--------------------------------------------------------------------------------
/jitpack.yml:
--------------------------------------------------------------------------------
1 | jdk:
2 | - openjdk11
--------------------------------------------------------------------------------
/lib/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/lib/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | apply plugin: "com.android.library"
20 | apply plugin: "com.gladed.androidgitversion"
21 |
22 | androidGitVersion {
23 | codeFormat "MMNNPP"
24 | format "%tag%"
25 | tagPattern(/^[0-9]+.*/) // Tag names should follow the pattern MM.NN.PP
26 | }
27 |
28 | ext {
29 | /*
30 | ********************
31 | * Android variables
32 | ********************
33 | */
34 | compile_sdk_version = 34
35 | min_sdk_version = 21
36 | target_sdk_version = 34
37 | build_tools_version = "34.0.0"
38 | }
39 |
40 | android {
41 | namespace = "com.hyperdevs.appupdateshelper"
42 | compileSdk = compile_sdk_version
43 | buildToolsVersion = build_tools_version
44 |
45 | defaultConfig {
46 | minSdkVersion min_sdk_version
47 | targetSdkVersion target_sdk_version
48 | versionName androidGitVersion.name()
49 | versionCode androidGitVersion.code()
50 |
51 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
52 | }
53 |
54 | buildTypes {
55 | release {
56 | minifyEnabled false
57 | proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"
58 | }
59 | }
60 |
61 | compileOptions {
62 | sourceCompatibility JavaVersion.VERSION_1_8
63 | targetCompatibility JavaVersion.VERSION_1_8
64 | }
65 | }
66 |
67 | dependencies {
68 | implementation fileTree(dir: "libs", include: ["*.jar"])
69 |
70 | implementation "androidx.annotation:annotation:1.6.0"
71 | implementation "androidx.appcompat:appcompat:1.6.1"
72 |
73 | // Needed for the in-app updates API
74 | api "com.google.android.play:app-update:2.1.0"
75 |
76 | testImplementation "junit:junit:4.13.2"
77 |
78 | androidTestImplementation "androidx.test:runner:1.5.2"
79 | androidTestImplementation "androidx.test.espresso:espresso-core:3.5.1"
80 | }
81 |
82 | apply from: "../jitpack-android.gradle"
83 |
84 |
--------------------------------------------------------------------------------
/lib/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/lib/src/androidTest/java/com/hyperdevs/appupdateshelper/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper;
20 |
21 | import android.content.Context;
22 | import androidx.test.InstrumentationRegistry;
23 | import androidx.test.runner.AndroidJUnit4;
24 |
25 | import org.junit.Test;
26 | import org.junit.runner.RunWith;
27 |
28 | import static org.junit.Assert.*;
29 |
30 | /**
31 | * Instrumented test, which will execute on an Android device.
32 | *
33 | * @see Testing documentation
34 | */
35 | @RunWith(AndroidJUnit4.class)
36 | public class ExampleInstrumentedTest {
37 | @Test
38 | public void useAppContext() {
39 | // Context of the app under test.
40 | Context appContext = InstrumentationRegistry.getTargetContext();
41 |
42 | assertEquals("com.bq.appupdateshelper.test", appContext.getPackageName());
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/lib/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
20 |
--------------------------------------------------------------------------------
/lib/src/main/java/com/hyperdevs/appupdateshelper/AppUpdateInfoResult.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper;
20 |
21 | import com.google.android.play.core.appupdate.AppUpdateInfo;
22 | import com.google.android.play.core.install.model.AppUpdateType;
23 | import com.google.android.play.core.install.model.InstallStatus;
24 | import com.google.android.play.core.install.model.UpdateAvailability;
25 |
26 | import java.util.Objects;
27 |
28 | import androidx.annotation.Nullable;
29 | import androidx.annotation.VisibleForTesting;
30 |
31 | import static com.google.android.play.core.install.model.InstallStatus.DOWNLOADED;
32 |
33 | /**
34 | * Class that represents the result of
35 | * {@link AppUpdatesHelper#getAppUpdateInfo(GetUpdateInfoListener)}.
36 | */
37 | public class AppUpdateInfoResult {
38 | public static final int VERSION_UNKNOWN = -1;
39 | public static final int VERSION_STALENESS_UNKNOWN = -1;
40 | public static final int UPDATE_PRIORITY_UNKNOWN = -1;
41 |
42 |
43 | private final boolean isSuccessful;
44 | private final int versionCode;
45 | private final Availability updateAvailability;
46 | private final int updatePriority;
47 | private final boolean canInstallFlexibleUpdate;
48 | private final boolean canInstallImmediateUpdate;
49 | private final int clientVersionStalenessDays;
50 | private final Exception exception;
51 |
52 | AppUpdateInfoResult(@Nullable AppUpdateInfo info,
53 | @Nullable Exception exception) {
54 | this.isSuccessful = info != null && exception == null;
55 | this.versionCode = (info != null) ? info.availableVersionCode() : VERSION_UNKNOWN;
56 | this.updateAvailability = Availability.from(
57 | (info != null) ? info.updateAvailability() : UpdateAvailability.UNKNOWN,
58 | (info != null) ? info.installStatus() : InstallStatus.UNKNOWN);
59 | this.updatePriority = info != null ? info.updatePriority() : UPDATE_PRIORITY_UNKNOWN;
60 | this.canInstallFlexibleUpdate = info != null && info.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE);
61 | this.canInstallImmediateUpdate = info != null && info.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE);
62 |
63 | Integer infoVersionStalenessDays =
64 | info != null ? info.clientVersionStalenessDays() : Integer.valueOf(VERSION_STALENESS_UNKNOWN);
65 | //noinspection ConstantConditions
66 | this.clientVersionStalenessDays = infoVersionStalenessDays != null ? infoVersionStalenessDays : VERSION_STALENESS_UNKNOWN;
67 |
68 | this.exception = exception;
69 | }
70 |
71 | @VisibleForTesting
72 | @SuppressWarnings("checkstyle:ParameterNumber")
73 | AppUpdateInfoResult(boolean isSuccessful,
74 | int versionCode,
75 | Availability updateAvailability,
76 | int updatePriority,
77 | boolean canInstallFlexibleUpdate,
78 | boolean canInstallImmediateUpdate,
79 | int clientVersionStalenessDays,
80 | Exception exception) {
81 | this.isSuccessful = isSuccessful;
82 | this.versionCode = versionCode;
83 | this.updateAvailability = updateAvailability;
84 | this.updatePriority = updatePriority;
85 | this.canInstallFlexibleUpdate = canInstallFlexibleUpdate;
86 | this.canInstallImmediateUpdate = canInstallImmediateUpdate;
87 | this.clientVersionStalenessDays = clientVersionStalenessDays;
88 | this.exception = exception;
89 | }
90 |
91 | public boolean isSuccessful() {
92 | return isSuccessful;
93 | }
94 |
95 | public int getVersionCode() {
96 | return versionCode;
97 | }
98 |
99 | public Availability getUpdateAvailability() {
100 | return updateAvailability;
101 | }
102 |
103 | public int getUpdatePriority() {
104 | return updatePriority;
105 | }
106 |
107 | public int getClientVersionStalenessDays() {
108 | return clientVersionStalenessDays;
109 | }
110 |
111 | /**
112 | * @return if the update can be flexible
113 | */
114 | public boolean canInstallFlexibleUpdate() {
115 | return canInstallFlexibleUpdate;
116 | }
117 |
118 | /**
119 | * @return if the update can be immediate
120 | */
121 | public boolean canInstallImmediateUpdate() {
122 | return canInstallImmediateUpdate;
123 | }
124 |
125 | @Nullable
126 | public Exception getException() {
127 | return exception;
128 | }
129 |
130 | @Override
131 | public boolean equals(Object o) {
132 | if (this == o) return true;
133 | if (o == null || getClass() != o.getClass()) return false;
134 | AppUpdateInfoResult that = (AppUpdateInfoResult) o;
135 | return isSuccessful == that.isSuccessful &&
136 | versionCode == that.versionCode &&
137 | updatePriority == that.updatePriority &&
138 | canInstallFlexibleUpdate == that.canInstallFlexibleUpdate &&
139 | canInstallImmediateUpdate == that.canInstallImmediateUpdate &&
140 | clientVersionStalenessDays == that.clientVersionStalenessDays &&
141 | updateAvailability == that.updateAvailability &&
142 | exception.equals(that.exception);
143 | }
144 |
145 | @Override
146 | public int hashCode() {
147 | return Objects.hash(isSuccessful, versionCode, updateAvailability,
148 | updatePriority, canInstallFlexibleUpdate, canInstallImmediateUpdate,
149 | clientVersionStalenessDays, exception);
150 | }
151 |
152 | @Override
153 | public String toString() {
154 | return "AppUpdateInfoResult{" +
155 | "isSuccessful=" + isSuccessful +
156 | ", versionCode=" + versionCode +
157 | ", updateAvailability=" + updateAvailability +
158 | ", updatePriority=" + updatePriority +
159 | ", canInstallFlexibleUpdate=" + canInstallFlexibleUpdate +
160 | ", canInstallImmediateUpdate=" + canInstallImmediateUpdate +
161 | ", clientVersionStalenessDays=" + clientVersionStalenessDays +
162 | ", exception=" + exception +
163 | '}';
164 | }
165 |
166 | /**
167 | * Enum that represents the availability of the update.
168 | */
169 | public enum Availability {
170 | UNKNOWN,
171 | UPDATE_NOT_AVAILABLE,
172 | UPDATE_AVAILABLE,
173 | UPDATE_IN_PROGRESS,
174 | UPDATE_DOWNLOADED;
175 |
176 | static Availability from(@UpdateAvailability int availability, @InstallStatus int installStatus) {
177 | switch (availability) {
178 | case UpdateAvailability.UPDATE_NOT_AVAILABLE:
179 | return UPDATE_NOT_AVAILABLE;
180 | case UpdateAvailability.UPDATE_AVAILABLE:
181 | return UPDATE_AVAILABLE;
182 | case UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS:
183 | if (installStatus == DOWNLOADED) {
184 | return UPDATE_DOWNLOADED;
185 | } else {
186 | return UPDATE_IN_PROGRESS;
187 | }
188 | case UpdateAvailability.UNKNOWN:
189 | default:
190 | return UNKNOWN;
191 | }
192 | }
193 | }
194 | }
195 |
--------------------------------------------------------------------------------
/lib/src/main/java/com/hyperdevs/appupdateshelper/AppUpdateInstallState.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper;
20 |
21 | import com.google.android.play.core.install.InstallState;
22 | import com.google.android.play.core.install.model.InstallErrorCode;
23 | import com.google.android.play.core.install.model.InstallStatus;
24 |
25 | import java.util.Objects;
26 |
27 | import androidx.annotation.NonNull;
28 |
29 | /**
30 | * Class that contains information about the app update installation state.
31 | */
32 | public class AppUpdateInstallState {
33 | static final long BYTES_UNKNOWN = 0;
34 | static final long PROGRESS_UNKNOWN = 0;
35 |
36 | @NonNull
37 | private final Status status;
38 | @NonNull
39 | private final ErrorCode errorCode;
40 | private final long bytesDownloaded;
41 | private final long totalBytesToDownload;
42 | private final float downloadProgress;
43 |
44 | AppUpdateInstallState(@NonNull Status status,
45 | @NonNull ErrorCode errorCode,
46 | long bytesDownloaded,
47 | long totalBytesToDownload) {
48 | this.status = status;
49 | this.errorCode = errorCode;
50 | this.bytesDownloaded = bytesDownloaded;
51 | this.totalBytesToDownload = totalBytesToDownload;
52 | if (status == Status.DOWNLOADED) {
53 | this.downloadProgress = 100f;
54 | } else if (totalBytesToDownload <= BYTES_UNKNOWN) {
55 | this.downloadProgress = PROGRESS_UNKNOWN;
56 | } else {
57 | this.downloadProgress = bytesDownloaded * 100f / totalBytesToDownload;
58 | }
59 | }
60 |
61 | AppUpdateInstallState(@NonNull InstallState state) {
62 | this(Status.from(state),
63 | ErrorCode.from(state),
64 | state.bytesDownloaded(),
65 | state.totalBytesToDownload());
66 | }
67 |
68 | @NonNull
69 | public Status getStatus() {
70 | return status;
71 | }
72 |
73 | @NonNull
74 | public ErrorCode getErrorCode() {
75 | return errorCode;
76 | }
77 |
78 | public long getBytesDownloaded() {
79 | return bytesDownloaded;
80 | }
81 |
82 | public long getTotalBytesToDownload() {
83 | return totalBytesToDownload;
84 | }
85 |
86 | public float getDownloadProgress() {
87 | return downloadProgress;
88 | }
89 |
90 | @Override
91 | public boolean equals(Object o) {
92 | if (this == o) return true;
93 | if (o == null || getClass() != o.getClass()) return false;
94 | AppUpdateInstallState that = (AppUpdateInstallState) o;
95 | return bytesDownloaded == that.bytesDownloaded &&
96 | totalBytesToDownload == that.totalBytesToDownload &&
97 | Float.compare(that.downloadProgress, downloadProgress) == 0 &&
98 | status == that.status &&
99 | errorCode == that.errorCode;
100 | }
101 |
102 | @Override
103 | public int hashCode() {
104 | return Objects.hash(status, errorCode, bytesDownloaded, totalBytesToDownload, downloadProgress);
105 | }
106 |
107 | @Override
108 | public String toString() {
109 | return "AppUpdateInstallState{" +
110 | "status=" + status +
111 | ", errorCode=" + errorCode +
112 | ", bytesDownloaded=" + bytesDownloaded +
113 | ", totalBytesToDownload=" + totalBytesToDownload +
114 | ", downloadProgress=" + downloadProgress +
115 | '}';
116 | }
117 |
118 | /**
119 | * Specific state of the app update installation.
120 | *
121 | * IMPORTANT: there's no SUCCESS state because the app is reloaded when the install process
122 | * finishes, so there's no need to emit that specific state.
123 | *
124 | * The enums represent the following states:
125 | *
126 | * - UNKNOWN: the update state is not known
127 | * - DENIED: the update has been denied by the user. It will only happen in immediate installs.
128 | * - REQUIRES_UI_INTENT: needs an UI Intent
129 | * - UPDATE_ACCEPTED: the user pressed the "update" button in the in-app update prompt.
130 | * - PENDING: the update is pending
131 | * - DOWNLOADING: the update is currently downloading
132 | * - DOWNLOADED: the update is downloaded, the user can be prompted to install it in this case
133 | * - INSTALLING: the update is currently being installed
134 | * - INSTALLED: the update has been installed
135 | * - FAILED: the update failed
136 | * - CANCELED: the update has been canceled, but it can be resumed in another moment.
137 | */
138 | public enum Status {
139 | UNKNOWN,
140 | DENIED,
141 | REQUIRES_UI_INTENT,
142 | UPDATE_ACCEPTED,
143 | PENDING,
144 | DOWNLOADING,
145 | DOWNLOADED,
146 | INSTALLING,
147 | INSTALLED,
148 | FAILED,
149 | CANCELED;
150 |
151 | static Status from(@NonNull InstallState state) {
152 | switch (state.installStatus()) {
153 | case InstallStatus.REQUIRES_UI_INTENT:
154 | return Status.REQUIRES_UI_INTENT;
155 | case InstallStatus.PENDING:
156 | return Status.PENDING;
157 | case InstallStatus.DOWNLOADING:
158 | return Status.DOWNLOADING;
159 | case InstallStatus.DOWNLOADED:
160 | return Status.DOWNLOADED;
161 | case InstallStatus.INSTALLING:
162 | return Status.INSTALLING;
163 | case InstallStatus.INSTALLED:
164 | return Status.INSTALLED;
165 | case InstallStatus.FAILED:
166 | return Status.FAILED;
167 | case InstallStatus.CANCELED:
168 | return Status.CANCELED;
169 | case InstallStatus.UNKNOWN:
170 | default:
171 | return Status.UNKNOWN;
172 | }
173 | }
174 | }
175 |
176 | /**
177 | * Specific enum related to an app install error code. It will always be present in {@link AppUpdateInstallState}
178 | * (even in non-error cases, then the value of this field will be NO_ERROR)
179 | *
180 | * The enums represent the following states:
181 | *
182 | * - NO_ERROR: No error occurred; all types of update flow are allowed.
183 | * - ERROR_UNKNOWN: An unknown error occurred.
184 | * - ERROR_API_NOT_AVAILABLE: The API is not available on this device (such as when the device is not supported).
185 | * - ERROR_INVALID_REQUEST: The request that was sent by the app is malformed.
186 | * - ERROR_INSTALL_UNAVAILABLE: The install is unavailable to this user or device.
187 | * - ERROR_INSTALL_NOT_ALLOWED: The download/install is not allowed, due to the current device state (e.g. low battery, low disk space…)
188 | * - ERROR_DOWNLOAD_NOT_PRESENT: The install/update has not been (fully) downloaded yet.
189 | * - ERROR_APP_NOT_OWNED: The user hasn't acquired the app via Play
190 | * - ERROR_PLAY_STORE_NOT_FOUND: The Play Store app is either not installed or not the official version.
191 | * - ERROR_INTERNAL_ERROR: An internal error happened in the Play Store.
192 | */
193 | public enum ErrorCode {
194 | NO_ERROR,
195 | ERROR_UNKNOWN,
196 | ERROR_API_NOT_AVAILABLE,
197 | ERROR_INVALID_REQUEST,
198 | ERROR_INSTALL_UNAVAILABLE,
199 | ERROR_INSTALL_NOT_ALLOWED,
200 | ERROR_DOWNLOAD_NOT_PRESENT,
201 | ERROR_APP_NOT_OWNED,
202 | ERROR_PLAY_STORE_NOT_FOUND,
203 | ERROR_INTERNAL_ERROR;
204 |
205 | static ErrorCode from(InstallState state) {
206 | switch (state.installErrorCode()) {
207 | case InstallErrorCode.NO_ERROR:
208 | return ErrorCode.NO_ERROR;
209 | case InstallErrorCode.ERROR_API_NOT_AVAILABLE:
210 | return ErrorCode.ERROR_API_NOT_AVAILABLE;
211 | case InstallErrorCode.ERROR_INVALID_REQUEST:
212 | return ErrorCode.ERROR_INVALID_REQUEST;
213 | case InstallErrorCode.ERROR_INSTALL_UNAVAILABLE:
214 | return ErrorCode.ERROR_INSTALL_UNAVAILABLE;
215 | case InstallErrorCode.ERROR_INSTALL_NOT_ALLOWED:
216 | return ErrorCode.ERROR_INSTALL_NOT_ALLOWED;
217 | case InstallErrorCode.ERROR_DOWNLOAD_NOT_PRESENT:
218 | return ErrorCode.ERROR_DOWNLOAD_NOT_PRESENT;
219 | case InstallErrorCode.ERROR_APP_NOT_OWNED:
220 | return ErrorCode.ERROR_APP_NOT_OWNED;
221 | case InstallErrorCode.ERROR_PLAY_STORE_NOT_FOUND:
222 | return ErrorCode.ERROR_PLAY_STORE_NOT_FOUND;
223 | case InstallErrorCode.ERROR_INTERNAL_ERROR:
224 | return ErrorCode.ERROR_INTERNAL_ERROR;
225 | case InstallErrorCode.ERROR_UNKNOWN:
226 | //noinspection deprecation
227 | case InstallErrorCode.NO_ERROR_PARTIALLY_ALLOWED:
228 | default:
229 | return ErrorCode.ERROR_UNKNOWN;
230 | }
231 | }
232 |
233 | @InstallErrorCode
234 | int getValue() {
235 | switch (this) {
236 | case NO_ERROR:
237 | return InstallErrorCode.NO_ERROR;
238 | case ERROR_API_NOT_AVAILABLE:
239 | return InstallErrorCode.ERROR_API_NOT_AVAILABLE;
240 | case ERROR_INVALID_REQUEST:
241 | return InstallErrorCode.ERROR_INVALID_REQUEST;
242 | case ERROR_INSTALL_UNAVAILABLE:
243 | return InstallErrorCode.ERROR_INSTALL_UNAVAILABLE;
244 | case ERROR_INSTALL_NOT_ALLOWED:
245 | return InstallErrorCode.ERROR_INSTALL_NOT_ALLOWED;
246 | case ERROR_DOWNLOAD_NOT_PRESENT:
247 | return InstallErrorCode.ERROR_DOWNLOAD_NOT_PRESENT;
248 | case ERROR_APP_NOT_OWNED:
249 | return InstallErrorCode.ERROR_APP_NOT_OWNED;
250 | case ERROR_PLAY_STORE_NOT_FOUND:
251 | return InstallErrorCode.ERROR_PLAY_STORE_NOT_FOUND;
252 | case ERROR_INTERNAL_ERROR:
253 | return InstallErrorCode.ERROR_INTERNAL_ERROR;
254 | case ERROR_UNKNOWN:
255 | default:
256 | return InstallErrorCode.ERROR_UNKNOWN;
257 | }
258 | }
259 | }
260 | }
261 |
--------------------------------------------------------------------------------
/lib/src/main/java/com/hyperdevs/appupdateshelper/AppUpdatesHelper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper;
20 |
21 | import android.app.Activity;
22 | import android.content.Context;
23 | import android.content.Intent;
24 | import android.content.IntentSender;
25 | import android.os.Bundle;
26 | import android.util.Log;
27 | import android.view.View;
28 |
29 | import com.google.android.gms.tasks.OnCompleteListener;
30 | import com.google.android.gms.tasks.Task;
31 | import com.google.android.play.core.appupdate.AppUpdateInfo;
32 | import com.google.android.play.core.appupdate.AppUpdateManager;
33 | import com.google.android.play.core.appupdate.AppUpdateManagerFactory;
34 | import com.google.android.play.core.install.InstallState;
35 | import com.google.android.play.core.install.InstallStateUpdatedListener;
36 | import com.google.android.play.core.install.model.AppUpdateType;
37 |
38 | import androidx.annotation.NonNull;
39 | import androidx.fragment.app.Fragment;
40 |
41 | import static android.app.Activity.RESULT_CANCELED;
42 | import static com.google.android.play.core.install.model.ActivityResult.RESULT_IN_APP_UPDATE_FAILED;
43 |
44 | /**
45 | * Helper class used to simplify the use of the In-App Updates library from Google.
46 | *
47 | * Its use is as follows:
48 | * - Register it using {@link #startListening(InstallStateListener)}, for example in {@link Activity#onCreate(Bundle)} or in {@link Fragment#onViewCreated(View, Bundle)}.
49 | * - Unregister it using {@link #stopListening()}, for example in {@link Activity#onDestroy()} or in {@link Fragment#onDestroyView()}.
50 | * - Call {@link #onUpdateStatusResult(int, int)} in your Activity's
51 | * {@link Activity#onActivityResult(int, int, Intent)} or your Fragment's {@link Fragment#onActivityResult(int, int, Intent)} so the helper can properly report status
52 | * updates.
53 | * - When you want to check if there are any updates, call {@link #getAppUpdateInfo(GetUpdateInfoListener)}.
54 | * - When you want to perform an update, call {@link #startImmediateUpdate(Activity)}/{@link #startImmediateUpdate(Fragment)}
55 | * or {@link #startFlexibleUpdate(Activity)}/{@link #startFlexibleUpdate(Fragment)} after successfully receiving an update via
56 | * {@link #getAppUpdateInfo(GetUpdateInfoListener)}.
57 | */
58 | @SuppressWarnings("JavadocReference")
59 | public class AppUpdatesHelper {
60 | static final int IMMEDIATE_UPDATE_REQUEST_CODE = 13371;
61 | static final int FLEXIBLE_UPDATE_REQUEST_CODE = 13372;
62 |
63 | private static final String TAG = "AppUpdatesHelper";
64 |
65 | private final AppUpdateManager manager;
66 | private InstallStateListener installStateListener;
67 | private boolean isListening = false;
68 | private AppUpdateInfo appUpdateInfo = null;
69 | private InstallStateUpdatedListener installStateUpdatedListener;
70 |
71 | /**
72 | * Creates a helper instance with a given context.
73 | *
74 | * @param context Context to use to build the helper.
75 | */
76 | public AppUpdatesHelper(@NonNull Context context) {
77 | this(AppUpdateManagerFactory.create(context));
78 | }
79 |
80 | /**
81 | * Creates a helper instance with a given app update manager.
82 | *
83 | * @param appUpdateManager app update manager to use.
84 | */
85 | AppUpdatesHelper(@NonNull AppUpdateManager appUpdateManager) {
86 | this.manager = appUpdateManager;
87 | }
88 |
89 | /**
90 | * Starts listening for app updates and install changes.
91 | */
92 | public void startListening(@NonNull final InstallStateListener installStateListener) {
93 | if (!isListening) {
94 | this.isListening = true;
95 | this.installStateListener = installStateListener;
96 | this.installStateUpdatedListener = new InstallStateUpdatedListener() {
97 | @Override
98 | public void onStateUpdate(InstallState installState) {
99 | AppUpdateInstallState state = new AppUpdateInstallState(installState);
100 | Log.d(TAG, "Update status result: " + state.toString());
101 |
102 | installStateListener.onInstallStateUpdate(state);
103 | }
104 | };
105 | this.manager.registerListener(installStateUpdatedListener);
106 | }
107 | }
108 |
109 | /**
110 | * Stops listening for app updates and install changes.
111 | */
112 | public void stopListening() {
113 | isListening = false;
114 | manager.unregisterListener(installStateUpdatedListener);
115 | }
116 |
117 | /**
118 | * Starts an app update check.
119 | *
120 | * The method must only be called after calling {@link #startListening(InstallStateListener)}.
121 | *
122 | * @param getUpdateInfoListener Callback that will emit an {@link AppUpdateInfoResult} object after finishing
123 | * querying for possible updates.
124 | */
125 | public void getAppUpdateInfo(@NonNull final GetUpdateInfoListener getUpdateInfoListener) {
126 | if (!isListening)
127 | throw new IllegalStateException("You must call startListening() before requesting update info");
128 |
129 | final Task appUpdateInfoTask = manager.getAppUpdateInfo();
130 |
131 | appUpdateInfoTask.addOnCompleteListener(new OnCompleteListener() {
132 | @Override
133 | public void onComplete(Task task) {
134 | Exception exception = null;
135 | if (task.isSuccessful()) {
136 | appUpdateInfo = task.getResult();
137 | } else {
138 | exception = task.getException();
139 | }
140 |
141 | AppUpdateInfoResult result = new AppUpdateInfoResult(appUpdateInfo, exception);
142 | Log.d(TAG, "Update info: " + result.toString());
143 |
144 | getUpdateInfoListener.onGetUpdateInfoComplete(result);
145 | }
146 | });
147 | }
148 |
149 | /**
150 | * Starts an immediate update.
151 | * It will receive callbacks in {@link InstallStateListener}.
152 | *
153 | * The method must only be called after calling {@link #startListening(InstallStateListener)}.
154 | *
155 | * @param activity The {@link Activity} to link to the update.
156 | */
157 | public void startImmediateUpdate(@NonNull Activity activity) {
158 | if (!isListening)
159 | throw new IllegalStateException("You must call startListening() " +
160 | "before requesting an immediate update");
161 | if (appUpdateInfo == null)
162 | throw new IllegalStateException("You must call getAppUpdateInfo() " +
163 | "with a successful response before requesting an immediate update");
164 |
165 | try {
166 | manager.startUpdateFlowForResult(
167 | appUpdateInfo,
168 | AppUpdateType.IMMEDIATE,
169 | activity,
170 | IMMEDIATE_UPDATE_REQUEST_CODE);
171 | } catch (IntentSender.SendIntentException e) {
172 | e.printStackTrace();
173 | }
174 | }
175 |
176 | /**
177 | * Starts an immediate update.
178 | * It will receive callbacks in {@link InstallStateListener}.
179 | *
180 | * The method must only be called after calling {@link #startListening(InstallStateListener)}.
181 | *
182 | * @param activity The {@link Fragment} to link to the update.
183 | */
184 | public void startImmediateUpdate(@NonNull Fragment fragment) {
185 | if (!isListening)
186 | throw new IllegalStateException("You must call startListening() " +
187 | "before requesting an immediate update");
188 | if (appUpdateInfo == null)
189 | throw new IllegalStateException("You must call getAppUpdateInfo() " +
190 | "with a successful response before requesting an immediate update");
191 |
192 | try {
193 | manager.startUpdateFlowForResult(
194 | appUpdateInfo,
195 | AppUpdateType.IMMEDIATE,
196 | fragment::startIntentSenderForResult,
197 | IMMEDIATE_UPDATE_REQUEST_CODE);
198 | } catch (IntentSender.SendIntentException e) {
199 | e.printStackTrace();
200 | }
201 | }
202 |
203 | /**
204 | * Starts a flexible update.
205 | * It will receive callbacks in {@link InstallStateListener}.
206 | *
207 | * The method must only be called after calling {@link #startListening(InstallStateListener)}
208 | * and {@link #getAppUpdateInfo(GetUpdateInfoListener)}.
209 | *
210 | * @param activity The {@link Activity} to link to the update.
211 | */
212 | public void startFlexibleUpdate(@NonNull Activity activity) {
213 | if (!isListening)
214 | throw new IllegalStateException("You must call startListening() " +
215 | "before requesting a flexible update");
216 | if (appUpdateInfo == null)
217 | throw new IllegalStateException("You must call getAppUpdateInfo() " +
218 | "with a successful response before requesting a flexible update");
219 |
220 | try {
221 | manager.startUpdateFlowForResult(
222 | appUpdateInfo,
223 | AppUpdateType.FLEXIBLE,
224 | activity,
225 | FLEXIBLE_UPDATE_REQUEST_CODE);
226 | } catch (IntentSender.SendIntentException e) {
227 | e.printStackTrace();
228 | }
229 | }
230 |
231 | /**
232 | * Starts a flexible update.
233 | * It will receive callbacks in {@link InstallStateListener}.
234 | *
235 | * The method must only be called after calling {@link #startListening(InstallStateListener)}
236 | * and {@link #getAppUpdateInfo(GetUpdateInfoListener)}.
237 | *
238 | * @param activity The {@link Fragment} to link to the update.
239 | */
240 | public void startFlexibleUpdate(@NonNull Fragment fragment) {
241 | if (!isListening)
242 | throw new IllegalStateException("You must call startListening() " +
243 | "before requesting a flexible update");
244 | if (appUpdateInfo == null)
245 | throw new IllegalStateException("You must call getAppUpdateInfo() " +
246 | "with a successful response before requesting a flexible update");
247 |
248 | try {
249 | manager.startUpdateFlowForResult(
250 | appUpdateInfo,
251 | AppUpdateType.FLEXIBLE,
252 | fragment::startIntentSenderForResult,
253 | FLEXIBLE_UPDATE_REQUEST_CODE);
254 | } catch (IntentSender.SendIntentException e) {
255 | e.printStackTrace();
256 | }
257 | }
258 |
259 | /**
260 | * Called to process {@link Activity#onActivityResult(int, int, Intent)} results for the
261 | * in-app updates installStateListener.
262 | *
263 | * @param requestCode {@link Activity#onActivityResult(int, int, Intent)}'s request code
264 | * @param resultCode {@link Activity#onActivityResult(int, int, Intent)}'s result code
265 | */
266 | public void onUpdateStatusResult(int requestCode, int resultCode) {
267 | if (requestCode == IMMEDIATE_UPDATE_REQUEST_CODE || requestCode == FLEXIBLE_UPDATE_REQUEST_CODE) {
268 | AppUpdateInstallState state;
269 | switch (resultCode) {
270 | case RESULT_CANCELED:
271 | if (requestCode == IMMEDIATE_UPDATE_REQUEST_CODE)
272 | state = new AppUpdateInstallState(
273 | AppUpdateInstallState.Status.DENIED,
274 | AppUpdateInstallState.ErrorCode.ERROR_INSTALL_NOT_ALLOWED,
275 | AppUpdateInstallState.BYTES_UNKNOWN,
276 | AppUpdateInstallState.BYTES_UNKNOWN
277 | );
278 | else
279 | state = new AppUpdateInstallState(
280 | AppUpdateInstallState.Status.CANCELED,
281 | AppUpdateInstallState.ErrorCode.ERROR_INSTALL_NOT_ALLOWED,
282 | AppUpdateInstallState.BYTES_UNKNOWN,
283 | AppUpdateInstallState.BYTES_UNKNOWN);
284 | break;
285 | case RESULT_IN_APP_UPDATE_FAILED:
286 | // We don't know why the update failed, so return an unknown error
287 | state = new AppUpdateInstallState(
288 | AppUpdateInstallState.Status.FAILED,
289 | AppUpdateInstallState.ErrorCode.ERROR_UNKNOWN,
290 | AppUpdateInstallState.BYTES_UNKNOWN,
291 | AppUpdateInstallState.BYTES_UNKNOWN
292 | );
293 | break;
294 | default:
295 | // If everything goes well, do stuff
296 | state = new AppUpdateInstallState(
297 | AppUpdateInstallState.Status.UPDATE_ACCEPTED,
298 | AppUpdateInstallState.ErrorCode.NO_ERROR,
299 | AppUpdateInstallState.BYTES_UNKNOWN,
300 | AppUpdateInstallState.BYTES_UNKNOWN
301 | );
302 | break;
303 | }
304 |
305 | Log.d(TAG, "Update status result: " + state.toString());
306 |
307 | if (installStateListener != null) {
308 | installStateListener.onInstallStateUpdate(state);
309 | }
310 | }
311 | }
312 |
313 | /**
314 | * Completes an unfinished installation (for example, when finishing downloading a flexible
315 | * installation).
316 | *
317 | * The method must only be called after calling {@link #startListening(InstallStateListener)}
318 | * and {@link #getAppUpdateInfo(GetUpdateInfoListener)}.
319 | */
320 | public void completeUpdate() {
321 | if (!isListening)
322 | throw new IllegalStateException("You must call startListening() " +
323 | "before completing an update");
324 | if (appUpdateInfo == null)
325 | throw new IllegalStateException("You must call getAppUpdateInfo() " +
326 | "before completing an update");
327 |
328 | manager.completeUpdate();
329 | }
330 | }
331 |
--------------------------------------------------------------------------------
/lib/src/main/java/com/hyperdevs/appupdateshelper/ContextUtils.java:
--------------------------------------------------------------------------------
1 | package com.hyperdevs.appupdateshelper;
2 |
3 | import android.content.Context;
4 | import android.os.Build;
5 |
6 | public class ContextUtils {
7 | /**
8 | * Constant to use in [registerReceiver] to declare that a registered receiver is not exported.
9 | *
10 | * This is needed as the constant does not exist in Android < 34
11 | */
12 | public static int getReceiverNotExported() {
13 | int value;
14 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
15 | value = Context.RECEIVER_NOT_EXPORTED;
16 | } else {
17 | value = 0;
18 | }
19 | return value;
20 | }
21 |
22 | /**
23 | * Constant to use in [registerReceiver] to declare that a registered receiver is exported.
24 | *
25 | * This is needed as the constant does not exist in Android < 34
26 | */
27 | public static int getReceiverExported() {
28 | int value;
29 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
30 | value = Context.RECEIVER_EXPORTED;
31 | } else {
32 | value = 0;
33 | }
34 | return value;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/lib/src/main/java/com/hyperdevs/appupdateshelper/FakeAppUpdatesHelper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper;
20 |
21 | import android.content.Context;
22 |
23 | import com.google.android.play.core.appupdate.AppUpdateManager;
24 | import com.google.android.play.core.appupdate.testing.FakeAppUpdateManager;
25 |
26 | import androidx.annotation.NonNull;
27 | import androidx.annotation.Nullable;
28 |
29 | import static android.app.Activity.RESULT_CANCELED;
30 | import static android.app.Activity.RESULT_OK;
31 |
32 | /**
33 | * A fake implementation of the {@link AppUpdatesHelper}, backed by a {@link FakeAppUpdateManager}.
34 | *
35 | * This implementation is completely self-contained in the library and does not interact with the Play Store. For this reason no UI is
36 | * being shown and no update is really performed.
37 | *
38 | * The developer can simulate the most common user actions, download progress and failure scenarios.
39 | *
40 | * It is designed to be used for unit-tests and early development iterations. It is not meant for full stack integration tests:
41 | * the latter can be performed by uploading your app to Play and sideload an older version (modified so it can trigger an in-app update)
42 | * onto your test device.
43 | */
44 | @SuppressWarnings("JavadocReference")
45 | public class FakeAppUpdatesHelper extends AppUpdatesHelper {
46 | private final FakeAppUpdateManager fakeAppUpdateManager;
47 |
48 | public FakeAppUpdatesHelper(@NonNull Context context) {
49 | this(new FakeAppUpdateManager(context));
50 | }
51 |
52 | private FakeAppUpdatesHelper(@NonNull AppUpdateManager appUpdateManager) {
53 | super(appUpdateManager);
54 | fakeAppUpdateManager = (FakeAppUpdateManager) appUpdateManager;
55 | }
56 |
57 | /**
58 | * Declares that an update is available and provides its version code.
59 | *
60 | * @param availableVersionCode the available update's version code
61 | */
62 | public void setUpdateAvailable(int availableVersionCode) {
63 | fakeAppUpdateManager.setUpdateAvailable(availableVersionCode);
64 | }
65 |
66 | /**
67 | * Declares that no updates are available.
68 | */
69 | public void setUpdateNotAvailable() {
70 | fakeAppUpdateManager.setUpdateNotAvailable();
71 | }
72 |
73 | /**
74 | * Simulates user click on the positive button in the update confirmation dialog. The download is enqueued in
75 | * {@link AppUpdateInstallState.Status.PENDING PENDING} status.
76 | *
77 | * Works only if {@link #isConfirmationDialogVisible()} or {@link #isImmediateFlowVisible()} is true.
78 | *
79 | * In the real implementation a {@link android.app.Activity.RESULT_OK} would also be received by the calling activity's
80 | * {@link android.app.Activity#onActivityResult}.
81 | */
82 | public void userAcceptsUpdate() {
83 | // Since the fake updater does not trigger onActivityResult, we have to manually trigger the ACCEPTED callback.
84 | int requestCode = getRequestCode();
85 |
86 | fakeAppUpdateManager.userAcceptsUpdate();
87 | onUpdateStatusResult(requestCode, RESULT_OK);
88 | }
89 |
90 | /**
91 | * Returns which type of update is currently in progress or null if no update is in progress.
92 | */
93 | @Nullable
94 | public Integer getTypeForUpdateInProgress() {
95 | return fakeAppUpdateManager.getTypeForUpdateInProgress();
96 | }
97 |
98 | /**
99 | * Simulates user canceling the download via the Play UI.
100 | *
101 | * Works only if the download of an update is pending or downloading.
102 | */
103 | public void userCancelsDownload() {
104 | fakeAppUpdateManager.userCancelsDownload();
105 | }
106 |
107 | /**
108 | * Simulates user click on the negative button in the currently active update flow.
109 | *
110 | * Works only if {@link #isConfirmationDialogVisible()} or {@link #isImmediateFlowVisible()} is true.
111 | *
112 | * In the real implementation a {@link android.app.Activity.RESULT_CANCELED} would also be received by the calling activity's
113 | * {@link android.app.Activity#onActivityResult}.
114 | */
115 | public void userRejectsUpdate() {
116 | // Since the fake updater does not trigger onActivityResult, we first have to check which
117 | // view is being shown (immediate or flexible) and then trigger the onUpdateStatusResult
118 | // callback manually
119 | int requestCode = getRequestCode();
120 |
121 | fakeAppUpdateManager.userRejectsUpdate();
122 | onUpdateStatusResult(requestCode, RESULT_CANCELED);
123 | }
124 |
125 | /**
126 | * Simulates the download completing.
127 | *
128 | * Works only after {@link #userAcceptsUpdate()}.
129 | */
130 | public void downloadStarts() {
131 | fakeAppUpdateManager.downloadStarts();
132 | }
133 |
134 | /**
135 | * Simulates the download starting.
136 | *
137 | * Works only after {@link #downloadStarts()}.
138 | */
139 | public void downloadCompletes() {
140 | fakeAppUpdateManager.downloadCompletes();
141 | }
142 |
143 | /**
144 | * Simulates a download failure.
145 | *
146 | * Works only if the download of an update is pending or downloading.
147 | */
148 | public void downloadFails() {
149 | fakeAppUpdateManager.downloadFails();
150 | }
151 |
152 | /**
153 | * Simulates the download completing.
154 | *
155 | * Works only after {@link #completeUpdate()} has been triggered by the application.
156 | */
157 | public void installCompletes() {
158 | fakeAppUpdateManager.installCompletes();
159 | }
160 |
161 | /**
162 | * Simulates an install failure.
163 | *
164 | * Works only if the update is already installing (after a call to {@link #completeUpdate()}).
165 | */
166 | public void installFails() {
167 | fakeAppUpdateManager.installFails();
168 | }
169 |
170 | /**
171 | * Sets an error code which will be returned by the next API calls.
172 | *
173 | * The error code is being honored by {@link #getAppUpdateInfo()} and {@link #completeUpdate()}; the error code is not being honored
174 | * if a more severe workflow error happens, e.g. if {@link #completeUpdate()} is called when the update is not downloaded yet.
175 | *
176 | * The error code is persistent: to return to the default behaviour, you can reset the value by calling the same method with
177 | * {@link AppUpdateInstallState.ErrorCode.NO_ERROR}.
178 | *
179 | * @param installErrorCode the install error code
180 | */
181 | public void setInstallErrorCode(AppUpdateInstallState.ErrorCode installErrorCode) {
182 | fakeAppUpdateManager.setInstallErrorCode(installErrorCode.getValue());
183 | }
184 |
185 | /**
186 | * Returns whether the user confirmation screen of the immediate update is visible to the user.
187 | */
188 | public boolean isConfirmationDialogVisible() {
189 | return fakeAppUpdateManager.isConfirmationDialogVisible();
190 | }
191 |
192 | /**
193 | * Returns whether the user confirmation screen of the immediate update is visible to the user.
194 | */
195 | public boolean isImmediateFlowVisible() {
196 | return fakeAppUpdateManager.isImmediateFlowVisible();
197 | }
198 |
199 | /**
200 | * Returns whether the splash screen is visible to the user. This happens during update completion:
201 | * in the real implementation your app is reloaded with the new version.
202 | */
203 | public boolean isInstallSplashScreenVisible() {
204 | return fakeAppUpdateManager.isInstallSplashScreenVisible();
205 | }
206 |
207 | private int getRequestCode() {
208 | if (isImmediateFlowVisible()) {
209 | return IMMEDIATE_UPDATE_REQUEST_CODE;
210 | }
211 | if (isConfirmationDialogVisible()) {
212 | return FLEXIBLE_UPDATE_REQUEST_CODE;
213 | }
214 | return -1;
215 | }
216 |
217 | }
218 |
--------------------------------------------------------------------------------
/lib/src/main/java/com/hyperdevs/appupdateshelper/GetUpdateInfoListener.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper;
20 |
21 | import androidx.annotation.NonNull;
22 |
23 | /**
24 | * Callback listener to obtain information about a finished update info request.
25 | */
26 | public interface GetUpdateInfoListener {
27 | /**
28 | * Triggered when an app info request has finished.
29 | *
30 | * @param result The result of the app info request whether is an error or not
31 | */
32 | void onGetUpdateInfoComplete(@NonNull AppUpdateInfoResult result);
33 | }
34 |
--------------------------------------------------------------------------------
/lib/src/main/java/com/hyperdevs/appupdateshelper/InstallStateListener.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper;
20 |
21 | import androidx.annotation.NonNull;
22 |
23 | /**
24 | * Listener that emits changes when an app update installation event happens.
25 | */
26 | public interface InstallStateListener {
27 | /**
28 | * Triggered on an app update installation event is emitted.
29 | *
30 | * @param state App update installation event
31 | */
32 | void onInstallStateUpdate(@NonNull AppUpdateInstallState state);
33 | }
34 |
--------------------------------------------------------------------------------
/lib/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 |
20 | AppUpdatesHelper
21 |
22 |
--------------------------------------------------------------------------------
/lib/src/test/java/com/hyperdevs/appupdateshelper/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | package com.hyperdevs.appupdateshelper;
20 |
21 | import org.junit.Test;
22 |
23 | import static org.junit.Assert.*;
24 |
25 | /**
26 | * Example local unit test, which will execute on the development machine (host).
27 | *
28 | * @see Testing documentation
29 | */
30 | public class ExampleUnitTest {
31 | @Test
32 | public void addition_isCorrect() {
33 | assertEquals(4, 2 + 2);
34 | }
35 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2021 HyperDevs
3 | *
4 | * Copyright (C) 2019 BQ
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 | * http://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 | include ':app', ':lib'
20 |
--------------------------------------------------------------------------------