├── .editorconfig
├── .gitignore
├── LICENSE
├── README.md
├── build.gradle
├── dependencies.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library
├── .gitignore
├── build.gradle
├── consumer-rules.pro
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── kernel
│ └── bundlesaver
│ ├── ActivityLifecycleCallbacksAdapter.kt
│ ├── ActivitySavedStateLogger.kt
│ ├── BundleManager.kt
│ ├── BundleSaverDelegate.kt
│ ├── Formatter.kt
│ ├── FragmentSavedStateLogger.kt
│ ├── Logger.kt
│ ├── SizeTree.kt
│ ├── disk
│ ├── DiskHandler.kt
│ └── FileDiskHandler.kt
│ ├── exceptions
│ └── BundleSizeExceededException.kt
│ ├── utils
│ ├── Converter.kt
│ └── Size.kt
│ └── wrapper
│ └── BitmapWrapper.kt
├── sample
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── kernel
│ │ └── bundlesaver
│ │ └── sample
│ │ ├── App.kt
│ │ └── MainActivity.kt
│ └── res
│ ├── layout
│ └── activity_main.xml
│ └── values
│ └── strings.xml
└── settings.gradle
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*.{kt,kts,java,yml,json,proto}]
4 | trim_trailing_whitespace = true
5 | insert_final_newline = false
6 | ij_kotlin_allow_trailing_comma = false
7 | ij_kotlin_allow_trailing_comma_on_call_site = false
8 |
9 | [*.{kt,kts,java}]
10 | indent_size = 4
11 | max_line_length = 120
12 |
13 | [*.{yml,json,proto}]
14 | indent_size = 2
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 |
22 | # Log/OS Files
23 | *.log
24 |
25 | # Android Studio generated files and folders
26 | captures/
27 | .externalNativeBuild/
28 | .cxx/
29 | *.apk
30 | output.json
31 |
32 | # IntelliJ
33 | .idea/
34 | misc.xml
35 | deploymentTargetDropDown.xml
36 | render.experimental.xml
37 |
38 | # Keystore files
39 | *.jks
40 | *.keystore
41 | secrets.properties
42 | key/dev_gpp.json
43 |
44 | # Android Profiling
45 | *.hprof
46 |
47 | # Kotlin 2.0 files
48 | .kotlin
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Bundle Saver
2 | A library that fixes TransactionTooLargeException during state saving and restoring in Runtime.
3 |
4 | ## Just Say No to TransactionTooLargeException
5 | How many times, while sitting in the evening with a cup of tea and browsing through Crashlytics, have you encountered such an Exception?
6 |
7 | ````java
8 | Fatal Exception: java.lang.RuntimeException
9 | android.os.TransactionTooLargeException: data parcel size 535656 bytes Bundle stats: androidx.lifecycle.BundlableSavedStateRegistry.key [size=534156]
10 | ````
11 |
12 | ### What's happening? How did this occur?
13 | Any developer knows about bundles and their size limitations, but the problem can arise in large applications with deeply nested screens and complex states. When a Binder transaction exceeds 1(or 2) MB, a TransactionTooLargeException will occur. But there is a solution! Introducing, BundleSaver!
14 |
15 | ### Features
16 | - ***Avoid TransactionTooLargeException***: Automatically handles large bundles by saving excess data to disk.
17 | - ***Easy Integration***: Simple initialization and usage with minimal boilerplate code.
18 | - ***Concurrency Support***: Utilizes a cached thread pool for efficient background operations.
19 | - ***Logging***: Built-in logging to monitor bundle sizes and ensure compliance with size limits.
20 | - ***Memory and Disk Management***: Clears data from memory and disk as needed, ensuring optimal performance.
21 |
22 | ## Getting Started
23 |
24 | ### Installation
25 |
26 | Add it in your root build.gradle at the end of repositories:
27 |
28 | ````java
29 | dependencyResolutionManagement {
30 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
31 | repositories {
32 | ...
33 | maven { url 'https://jitpack.io' }
34 | }
35 | }
36 | ````
37 |
38 | Add the BundleSaver dependency to your build.gradle file in App module:
39 | ````java
40 | dependencies {
41 | implementation "com.github.kernel0x:bundlesaver:1.0.0"
42 | }
43 | ````
44 |
45 | ### Usage
46 |
47 | Initialize an instance of BundleManager (preferably in the Application's onCreate() method)
48 | ````java
49 | class App : Application() {
50 |
51 | override fun onCreate() {
52 | super.onCreate()
53 | BundleManager.initialize(this)
54 | }
55 | }
56 | ````
57 |
58 | Next, you should add the following to each of your Activities (***Important! The order must be exactly like this!***).
59 | ````java
60 | class MainActivity : Activity() {
61 |
62 | override fun onCreate(savedInstanceState: Bundle?) {
63 | BundleManager.restoreInstanceState(this, savedInstanceState)
64 | super.onCreate(savedInstanceState)
65 | }
66 |
67 | override fun onSaveInstanceState(outState: Bundle) {
68 | super.onSaveInstanceState(outState)
69 | BundleManager.saveInstanceState(this, outState)
70 | }
71 | }
72 | ````
73 |
74 | That's it!
75 |
76 | #### Optional
77 | Clearing Data and Logging.
78 |
79 | ## Releases
80 |
81 | Checkout the [Releases](https://github.com/kernel0x/bundlesaver/releases) tab for all release info.
82 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | apply from: 'dependencies.gradle'
2 |
3 | buildscript {
4 | ext.kotlin_version = '1.6.21'
5 | repositories {
6 | mavenCentral()
7 | google()
8 | }
9 | dependencies {
10 | classpath 'com.android.tools.build:gradle:4.0.2'
11 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | google()
18 | mavenCentral()
19 | maven { url 'https://jitpack.io' }
20 | }
21 | }
22 |
23 | tasks.register('clean', Delete) {
24 | delete rootProject.buildDir
25 | }
--------------------------------------------------------------------------------
/dependencies.gradle:
--------------------------------------------------------------------------------
1 | ext.versions = [
2 | minSdk : 24,
3 | compileSdk : 34,
4 | libraryVersion : '1.0.0',
5 | libraryVersionCode: 1,
6 |
7 | androidxFragment : '1.5.1',
8 | kotlin : '1.6.21',
9 | ]
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 |
8 | # Specifies the JVM arguments used for the daemon process.
9 | # The setting is particularly useful for tweaking memory settings.
10 | # Ensure important default jvmargs aren't overwritten. See https://github.com/gradle/gradle/issues/19750
11 | org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g
12 |
13 | # When configured, Gradle will run in incubating parallel mode.
14 | # This option should only be used with decoupled projects. More details, visit
15 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
16 | org.gradle.parallel=true
17 |
18 | # Not encouraged by Gradle and can produce weird results. Wait for isolated projects instead.
19 | org.gradle.configureondemand=false
20 |
21 | # Enable caching between builds.
22 | org.gradle.caching=true
23 |
24 | # Enable configuration caching between builds.
25 | org.gradle.configuration-cache=true
26 | # This option is set because of https://github.com/google/play-services-plugins/issues/246
27 | # to generate the Configuration Cache regardless of incompatible tasks.
28 | # See https://github.com/android/nowinandroid/issues/1022 before using it.
29 | org.gradle.configuration-cache.problems=warn
30 |
31 | # AndroidX package structure to make it clearer which packages are bundled with the
32 | # Android operating system, and which are packaged with your app"s APK
33 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
34 | android.useAndroidX=true
35 | android.enableJetifier=false
36 | # Kotlin code style for this project: "official" or "obsolete":
37 | kotlin.code.style=official
38 |
39 | org.gradle.unsafe.configuration-cache=true
40 | org.gradle.unsafe.configuration-cache-problems=warn
41 |
42 | # Disable build features that are enabled by default,
43 | # https://developer.android.com/build/releases/gradle-plugin#default-changes
44 | android.defaults.buildfeatures.resvalues=false
45 | android.defaults.buildfeatures.shaders=false
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kernel0x/bundlesaver/8a20183fbdb6f731b7fcc0d10308bd3dffb53299/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Nov 15 08:44:45 MSK 2023
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ]; do
30 | ls=$(ls -ld "$PRG")
31 | link=$(expr "$ls" : '.*-> \(.*\)$')
32 | if expr "$link" : '/.*' >/dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=$(dirname "$PRG")"/$link"
36 | fi
37 | done
38 | SAVED="$(pwd)"
39 | cd "$(dirname \"$PRG\")/" >/dev/null
40 | APP_HOME="$(pwd -P)"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=$(basename "$0")
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn() {
53 | echo "$*"
54 | }
55 |
56 | die() {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "$(uname)" in
69 | CYGWIN*)
70 | cygwin=true
71 | ;;
72 | Darwin*)
73 | darwin=true
74 | ;;
75 | MINGW*)
76 | msys=true
77 | ;;
78 | NONSTOP*)
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 | # Determine the Java command to use to start the JVM.
86 | if [ -n "$JAVA_HOME" ]; then
87 | if [ -x "$JAVA_HOME/jre/sh/java" ]; then
88 | # IBM's JDK on AIX uses strange locations for the executables
89 | JAVACMD="$JAVA_HOME/jre/sh/java"
90 | else
91 | JAVACMD="$JAVA_HOME/bin/java"
92 | fi
93 | if [ ! -x "$JAVACMD" ]; then
94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
95 |
96 | Please set the JAVA_HOME variable in your environment to match the
97 | location of your Java installation."
98 | fi
99 | else
100 | JAVACMD="java"
101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
102 |
103 | Please set the JAVA_HOME variable in your environment to match the
104 | location of your Java installation."
105 | fi
106 |
107 | # Increase the maximum file descriptors if we can.
108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ]; then
109 | MAX_FD_LIMIT=$(ulimit -H -n)
110 | if [ $? -eq 0 ]; then
111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ]; then
112 | MAX_FD="$MAX_FD_LIMIT"
113 | fi
114 | ulimit -n $MAX_FD
115 | if [ $? -ne 0 ]; then
116 | warn "Could not set maximum file descriptor limit: $MAX_FD"
117 | fi
118 | else
119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
120 | fi
121 | fi
122 |
123 | # For Darwin, add options to specify how the application appears in the dock
124 | if $darwin; then
125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
126 | fi
127 |
128 | # For Cygwin or MSYS, switch paths to Windows format before running java
129 | if [ "$cygwin" = "true" -o "$msys" = "true" ]; then
130 | APP_HOME=$(cygpath --path --mixed "$APP_HOME")
131 | CLASSPATH=$(cygpath --path --mixed "$CLASSPATH")
132 | JAVACMD=$(cygpath --unix "$JAVACMD")
133 |
134 | # We build the pattern for arguments to be converted via cygpath
135 | ROOTDIRSRAW=$(find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null)
136 | SEP=""
137 | for dir in $ROOTDIRSRAW; do
138 | ROOTDIRS="$ROOTDIRS$SEP$dir"
139 | SEP="|"
140 | done
141 | OURCYGPATTERN="(^($ROOTDIRS))"
142 | # Add a user-defined pattern to the cygpath arguments
143 | if [ "$GRADLE_CYGPATTERN" != "" ]; then
144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
145 | fi
146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
147 | i=0
148 | for arg in "$@"; do
149 | CHECK=$(echo "$arg" | egrep -c "$OURCYGPATTERN" -)
150 | CHECK2=$(echo "$arg" | egrep -c "^-") ### Determine if an option
151 |
152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ]; then ### Added a condition
153 | eval $(echo args$i)=$(cygpath --path --ignore --mixed "$arg")
154 | else
155 | eval $(echo args$i)="\"$arg\""
156 | fi
157 | i=$(expr $i + 1)
158 | done
159 | case $i in
160 | 0) set -- ;;
161 | 1) set -- "$args0" ;;
162 | 2) set -- "$args0" "$args1" ;;
163 | 3) set -- "$args0" "$args1" "$args2" ;;
164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
170 | esac
171 | fi
172 |
173 | # Escape application args
174 | save() {
175 | for i; do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/"; done
176 | echo " "
177 | }
178 | APP_ARGS=$(save "$@")
179 |
180 | # Collect all arguments for the java command, following the shell quoting and substitution rules
181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
182 |
183 | exec "$JAVACMD" "$@"
184 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
34 |
35 | @rem Find java.exe
36 | if defined JAVA_HOME goto findJavaFromJavaHome
37 |
38 | set JAVA_EXE=java.exe
39 | %JAVA_EXE% -version >NUL 2>&1
40 | if "%ERRORLEVEL%" == "0" goto init
41 |
42 | echo.
43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
44 | echo.
45 | echo Please set the JAVA_HOME variable in your environment to match the
46 | echo location of your Java installation.
47 |
48 | goto fail
49 |
50 | :findJavaFromJavaHome
51 | set JAVA_HOME=%JAVA_HOME:"=%
52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
53 |
54 | if exist "%JAVA_EXE%" goto init
55 |
56 | echo.
57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
58 | echo.
59 | echo Please set the JAVA_HOME variable in your environment to match the
60 | echo location of your Java installation.
61 |
62 | goto fail
63 |
64 | :init
65 | @rem Get command-line arguments, handling Windows variants
66 |
67 | if not "%OS%" == "Windows_NT" goto win9xME_args
68 |
69 | :win9xME_args
70 | @rem Slurp the command line arguments.
71 | set CMD_LINE_ARGS=
72 | set _SKIP=2
73 |
74 | :win9xME_args_slurp
75 | if "x%~1" == "x" goto execute
76 |
77 | set CMD_LINE_ARGS=%*
78 |
79 | :execute
80 | @rem Setup the command line
81 |
82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
83 |
84 | @rem Execute Gradle
85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
86 |
87 | :end
88 | @rem End local scope for the variables with windows NT shell
89 | if "%ERRORLEVEL%"=="0" goto mainEnd
90 |
91 | :fail
92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
93 | rem the _cmd.exe /c_ return code!
94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
95 | exit /b 1
96 |
97 | :mainEnd
98 | if "%OS%"=="Windows_NT" endlocal
99 |
100 | :omega
101 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
2 |
3 | apply plugin: "com.android.library"
4 | apply plugin: "kotlin-android"
5 |
6 | android {
7 | compileSdkVersion versions.compileSdk
8 | defaultConfig {
9 | minSdkVersion versions.minSdk
10 | targetSdkVersion versions.targetSdk
11 | versionCode versions.libraryVersionCode
12 | versionName versions.libraryVersion
13 | consumerProguardFiles "consumer-rules.pro"
14 | }
15 |
16 | compileOptions {
17 | sourceCompatibility JavaVersion.VERSION_1_8
18 | targetCompatibility JavaVersion.VERSION_1_8
19 | }
20 | }
21 |
22 | dependencies {
23 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$versions.kotlin"
24 | implementation "androidx.fragment:fragment:$versions.androidxFragment"
25 | }
26 |
27 | tasks.withType(KotlinCompile).configureEach {
28 | kotlinOptions {
29 | jvmTarget = "1.8"
30 | freeCompilerArgs = ["-Xjvm-default=enable"]
31 | }
32 | }
--------------------------------------------------------------------------------
/library/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kernel0x/bundlesaver/8a20183fbdb6f731b7fcc0d10308bd3dffb53299/library/consumer-rules.pro
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kernel0x/bundlesaver/8a20183fbdb6f731b7fcc0d10308bd3dffb53299/library/proguard-rules.pro
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library/src/main/java/com/kernel/bundlesaver/ActivityLifecycleCallbacksAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver
2 |
3 | import android.app.Activity
4 | import android.app.Application.ActivityLifecycleCallbacks
5 | import android.os.Bundle
6 |
7 | internal abstract class ActivityLifecycleCallbacksAdapter : ActivityLifecycleCallbacks {
8 |
9 | override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
10 | // no-op
11 | }
12 |
13 | override fun onActivityDestroyed(activity: Activity) {
14 | // no-op
15 | }
16 |
17 | override fun onActivityPaused(activity: Activity) {
18 | // no-op
19 | }
20 |
21 | override fun onActivityResumed(activity: Activity) {
22 | // no-op
23 | }
24 |
25 | override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
26 | // no-op
27 | }
28 |
29 | override fun onActivityStarted(activity: Activity) {
30 | // no-op
31 | }
32 |
33 | override fun onActivityStopped(activity: Activity) {
34 | // no-op
35 | }
36 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/kernel/bundlesaver/ActivitySavedStateLogger.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver
2 |
3 | import android.app.Activity
4 | import android.app.Application
5 | import android.os.Bundle
6 | import androidx.fragment.app.FragmentActivity
7 | import com.kernel.bundlesaver.exceptions.BundleSizeExceededException
8 | import com.kernel.bundlesaver.utils.sizeAsParcel
9 |
10 | /**
11 | * [Application.ActivityLifecycleCallbacks] implementation that logs information
12 | * about the saved state of Activities.
13 | */
14 | internal class ActivitySavedStateLogger(
15 | private val formatter: Formatter,
16 | private val logger: Logger,
17 | private val limitSizeBundle: Int,
18 | logFragments: Boolean
19 | ) : ActivityLifecycleCallbacksAdapter() {
20 |
21 | private val fragmentLogger = if (logFragments) FragmentSavedStateLogger(formatter, logger) else null
22 | private val savedStates = HashMap()
23 | internal var isLogging = false
24 |
25 | override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
26 | if (activity is FragmentActivity && fragmentLogger != null) {
27 | activity.supportFragmentManager.registerFragmentLifecycleCallbacks(fragmentLogger, true)
28 | }
29 | }
30 |
31 | override fun onActivityDestroyed(activity: Activity) {
32 | logAndRemoveSavedState(activity)
33 | }
34 |
35 | override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
36 | if (isLogging) {
37 | savedStates[activity] = outState
38 | }
39 | }
40 |
41 | override fun onActivityStopped(activity: Activity) {
42 | logAndRemoveSavedState(activity)
43 | }
44 |
45 | private fun logAndRemoveSavedState(activity: Activity) {
46 | val savedState = savedStates.remove(key = activity)
47 | if (savedState != null) {
48 | try {
49 | val message = formatter.format(activity = activity, bundle = savedState)
50 | logger.log(message = message)
51 | val size = sizeAsParcel(bundle = savedState)
52 | if (size > limitSizeBundle) {
53 | logger.logException(
54 | exception = BundleSizeExceededException(
55 | formatter.format(
56 | size = size,
57 | limit = limitSizeBundle
58 | )
59 | )
60 | )
61 | }
62 | } catch (exception: RuntimeException) {
63 | logger.logException(exception = exception)
64 | }
65 | }
66 | }
67 |
68 | fun startLogging() {
69 | isLogging = true
70 | fragmentLogger?.startLogging()
71 | }
72 |
73 | fun stopLogging() {
74 | isLogging = false
75 | savedStates.clear()
76 | fragmentLogger?.stopLogging()
77 | }
78 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/kernel/bundlesaver/BundleManager.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver
2 |
3 | import android.app.Application
4 | import android.content.Context
5 | import android.os.Bundle
6 | import android.util.Log
7 | import com.kernel.bundlesaver.disk.FileDiskHandler
8 | import java.util.concurrent.Executors
9 |
10 | /**
11 | * Constant representing the default size limit for Bundle.
12 | */
13 | const val DEFAULT_BUNDLE_SIZE_LIMIT_BYTES = 524288 // 512 КБ
14 |
15 | /**
16 | * A object for avoiding [android.os.TransactionTooLargeException] in Runtime
17 | */
18 | object BundleManager {
19 |
20 | private val executorService = Executors.newCachedThreadPool()
21 |
22 | private var activityLogger: ActivitySavedStateLogger? = null
23 |
24 | @Volatile
25 | private var delegate: BundleSaverDelegate? = null
26 |
27 | @JvmStatic
28 | val isLogging: Boolean
29 | get() = activityLogger?.isLogging ?: false
30 |
31 | /**
32 | * Initializes the framework used to save and restore data and route it to a location free from
33 | * [android.os.TransactionTooLargeException].
34 | */
35 | @JvmStatic
36 | fun initialize(
37 | application: Application,
38 | isLogging: Boolean = true,
39 | logger: Logger? = null,
40 | priority: Int = Log.DEBUG,
41 | tag: String = "BundleSaver",
42 | limitSizeBundle: Int = DEFAULT_BUNDLE_SIZE_LIMIT_BYTES
43 | ) {
44 | delegate = BundleSaverDelegate(application, executorService)
45 | if (isLogging) {
46 | startLogging(
47 | application = application,
48 | formatter = DefaultFormatter(),
49 | logger = logger ?: DefaultLogger(priority, tag),
50 | limitSizeBundle = limitSizeBundle
51 | )
52 | }
53 | }
54 |
55 | /**
56 | * Restores the state of the given target object based on tracking information stored in the
57 | * given [Bundle]. The actual saved data will be retrieved from a location in memory or
58 | * stored on disk.
59 | *
60 | * It is required to call [initialize] before calling this method.
61 | */
62 | @JvmStatic
63 | fun restoreInstanceState(target: Any, state: Bundle?) {
64 | checkInitialization()
65 | delegate?.restoreInstanceState(target, state)
66 | }
67 |
68 | /**
69 | * Saves the state of the given target object to a location in memory and disk and stores
70 | * tracking information in given [Bundle].
71 | *
72 | * It is required to call [initialize] before calling this method.
73 | */
74 | @JvmStatic
75 | fun saveInstanceState(target: Any, state: Bundle) {
76 | checkInitialization()
77 | delegate?.saveInstanceState(target, state)
78 | }
79 |
80 | /**
81 | * Clears any data associated with the given target object that may be stored to disk. This
82 | * will not affect data stored for restoration after configuration changes. Due to how these
83 | * changes are monitored.
84 | *
85 | * It is required to call [initialize] before calling this method.
86 | */
87 | @JvmStatic
88 | fun clear(target: Any) {
89 | checkInitialization()
90 | delegate?.clear(target)
91 | }
92 |
93 | /**
94 | * Clears all data from disk and memory. Does not require a call to [initialize].
95 | */
96 | @JvmStatic
97 | fun clearAll(context: Context) {
98 | delegate?.clearAll() ?: run {
99 | executorService.execute {
100 | FileDiskHandler(context, executorService).clearAll()
101 | }
102 | }
103 | }
104 |
105 | /**
106 | * Start logging size bundle
107 | */
108 | @JvmStatic
109 | fun startLogging(application: Application, formatter: Formatter, logger: Logger, limitSizeBundle: Int) {
110 | if (activityLogger == null) {
111 | activityLogger = ActivitySavedStateLogger(
112 | formatter = formatter,
113 | logger = logger,
114 | limitSizeBundle = limitSizeBundle,
115 | logFragments = true
116 | )
117 | }
118 |
119 | val activityLogger = activityLogger ?: return
120 |
121 | if (activityLogger.isLogging) {
122 | return
123 | }
124 |
125 | activityLogger.startLogging()
126 | application.registerActivityLifecycleCallbacks(activityLogger)
127 | }
128 |
129 | /**
130 | * Stop all logging
131 | */
132 | @JvmStatic
133 | fun stopLogging(application: Application) {
134 | val activityLogger = activityLogger ?: return
135 |
136 | if (!activityLogger.isLogging) {
137 | return
138 | }
139 |
140 | activityLogger.stopLogging()
141 | application.unregisterActivityLifecycleCallbacks(activityLogger)
142 | }
143 |
144 | private fun checkInitialization() {
145 | delegate ?: throw IllegalStateException(
146 | "You must first call initialize before calling any other methods"
147 | )
148 | }
149 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/kernel/bundlesaver/BundleSaverDelegate.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver
2 |
3 | import android.app.Activity
4 | import android.app.ActivityManager
5 | import android.app.Application
6 | import android.content.Context
7 | import android.os.Bundle
8 | import android.util.Log
9 | import androidx.annotation.Nullable
10 | import com.kernel.bundlesaver.disk.DiskHandler
11 | import com.kernel.bundlesaver.disk.FileDiskHandler
12 | import com.kernel.bundlesaver.utils.Converter
13 | import com.kernel.bundlesaver.wrapper.unwrapOptimizedObjects
14 | import com.kernel.bundlesaver.wrapper.wrapOptimizedObjects
15 | import java.util.UUID
16 | import java.util.WeakHashMap
17 | import java.util.concurrent.ConcurrentHashMap
18 | import java.util.concurrent.CopyOnWriteArrayList
19 | import java.util.concurrent.CountDownLatch
20 | import java.util.concurrent.ExecutorService
21 | import java.util.concurrent.TimeUnit
22 |
23 | private const val TAG = "BundleSaverDelegate"
24 | private const val BACKGROUND_WAIT_TIMEOUT_MS = 5000L
25 | private const val KEY_UUID = "uuid_%s"
26 |
27 | internal class BundleSaverDelegate(
28 | context: Context,
29 | private val executorService: ExecutorService
30 | ) {
31 |
32 | private val diskHandler: DiskHandler = FileDiskHandler(context, executorService)
33 | private val pendingWriteTasks = CopyOnWriteArrayList()
34 | private val uuidBundleMap = ConcurrentHashMap()
35 | private val objectUuidMap = WeakHashMap()
36 | private var activityCount = 0
37 | private var isClearAllowed = false
38 | private var isConfigChange = false
39 | private var isFirstCreateCall = true
40 | private var pendingWriteTasksLatch: CountDownLatch? = null
41 |
42 | init {
43 | registerForLifecycleEvents(context)
44 | context.getSharedPreferences(TAG, Context.MODE_PRIVATE).edit().clear().apply()
45 | }
46 |
47 | fun clear(target: Any) {
48 | if (!isClearAllowed) return
49 | val uuid = objectUuidMap.remove(target) ?: return
50 | clearDataForUuid(uuid)
51 | }
52 |
53 | fun clearAll() {
54 | uuidBundleMap.clear()
55 | objectUuidMap.clear()
56 | doInBackground { diskHandler.clearAll() }
57 | }
58 |
59 | private fun clearDataForUuid(uuid: String) {
60 | uuidBundleMap.remove(uuid)
61 | clearDataFromDisk(uuid)
62 | }
63 |
64 | private fun clearDataFromDisk(uuid: String) {
65 | doInBackground { diskHandler.clear(uuid) }
66 | }
67 |
68 | private fun doInBackground(runnable: Runnable) {
69 | executorService.execute(runnable)
70 | }
71 |
72 | private fun getKeyForUuid(target: Any): String = String.format(KEY_UUID, target.javaClass.name)
73 |
74 | private fun getOrGenerateUuid(target: Any): String = objectUuidMap.getOrPut(target) { UUID.randomUUID().toString() }
75 |
76 | @Nullable
77 | private fun getSavedBundleAndUnwrap(uuid: String): Bundle? {
78 | val bundle = uuidBundleMap[uuid] ?: readFromDisk(uuid) ?: return null
79 | unwrapOptimizedObjects(bundle)
80 | clearDataForUuid(uuid)
81 | return bundle
82 | }
83 |
84 | @Nullable
85 | private fun getSavedUuid(target: Any, state: Bundle): String? {
86 | return objectUuidMap[target] ?: state.getString(getKeyForUuid(target), null)?.also {
87 | objectUuidMap[target] = it
88 | }
89 | }
90 |
91 | private fun isAppInForeground(): Boolean = activityCount > 0 || isConfigChange
92 |
93 | private fun isFreshStart(activity: Activity, savedInstanceState: Bundle?): Boolean {
94 | if (!isFirstCreateCall) return false
95 | isFirstCreateCall = false
96 | if (savedInstanceState != null) return false
97 | val activityManager = activity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
98 | val appTasks = activityManager.appTasks
99 | return appTasks.size == 1 && appTasks[0].taskInfo.numActivities == 1
100 | }
101 |
102 | private fun queueDiskWritingIfNecessary(uuid: String, bundle: Bundle) {
103 | val runnable = object : Runnable {
104 | override fun run() {
105 | writeToDisk(uuid, bundle)
106 | if (!uuidBundleMap.containsKey(uuid)) {
107 | clearDataFromDisk(uuid)
108 | }
109 | pendingWriteTasks.remove(this) // Используем this для удаления текущего Runnable
110 | if (pendingWriteTasks.isEmpty() && pendingWriteTasksLatch != null) {
111 | pendingWriteTasksLatch?.countDown()
112 | }
113 | }
114 | }
115 | if (pendingWriteTasksLatch == null || pendingWriteTasksLatch?.count == 0L) {
116 | pendingWriteTasksLatch = CountDownLatch(1)
117 | }
118 | pendingWriteTasks.add(runnable)
119 | doInBackground(runnable)
120 | if (isAppInForeground()) return
121 | try {
122 | pendingWriteTasksLatch?.await(BACKGROUND_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS)
123 | } catch (e: InterruptedException) {
124 | // Interrupted for an unknown reason, simply proceed.
125 | }
126 | pendingWriteTasksLatch = null
127 | }
128 |
129 | @Nullable
130 | private fun readFromDisk(uuid: String): Bundle? {
131 | val bytes = diskHandler.getBytes(uuid) ?: return null
132 | val bundle = Converter.fromBytes(bytes) ?: run {
133 | Log.e("Bridge", "Unable to properly convert disk-persisted data to a Bundle. Some state loss may occur.")
134 | return null
135 | }
136 | return bundle
137 | }
138 |
139 | private fun registerForLifecycleEvents(context: Context) {
140 | (context.applicationContext as Application).registerActivityLifecycleCallbacks(
141 | object : ActivityLifecycleCallbacksAdapter() {
142 | override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
143 | isClearAllowed = true
144 | isConfigChange = false
145 | if (!isFreshStart(activity, savedInstanceState)) return
146 | clearAll()
147 | }
148 |
149 | override fun onActivityDestroyed(activity: Activity) {
150 | isClearAllowed = activity.isFinishing
151 | }
152 |
153 | override fun onActivityPaused(activity: Activity) {
154 | isConfigChange = activity.isChangingConfigurations
155 | }
156 |
157 | override fun onActivityStarted(activity: Activity) {
158 | activityCount++
159 | }
160 |
161 | override fun onActivityStopped(activity: Activity) {
162 | activityCount--
163 | }
164 | }
165 | )
166 | }
167 |
168 | fun restoreInstanceState(target: Any, state: Bundle?) {
169 | state ?: return
170 | getSavedUuid(target, state)?.let { uuid ->
171 | getSavedBundleAndUnwrap(uuid)?.also { state.putAll(it) }
172 | }
173 | }
174 |
175 | fun saveInstanceState(target: Any, state: Bundle) {
176 | val key = getKeyForUuid(target)
177 | val uuid = getOrGenerateUuid(target)
178 | state.putString(key, uuid)
179 | saveToMemoryAndDiskIfNecessary(uuid, state)
180 | state.clear()
181 | state.putString(key, uuid)
182 | }
183 |
184 | private fun saveToMemoryAndDiskIfNecessary(uuid: String, bundle: Bundle) {
185 | val state = Bundle(bundle)
186 | wrapOptimizedObjects(state)
187 | uuidBundleMap[uuid] = state
188 | queueDiskWritingIfNecessary(uuid, state)
189 | }
190 |
191 | private fun writeToDisk(uuid: String, bundle: Bundle) {
192 | val bytes = Converter.toBytes(bundle)
193 | diskHandler.putBytes(uuid, bytes)
194 | }
195 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/kernel/bundlesaver/Formatter.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver
2 |
3 | import android.app.Activity
4 | import android.os.Bundle
5 | import androidx.fragment.app.Fragment
6 | import androidx.fragment.app.FragmentManager
7 | import com.kernel.bundlesaver.utils.bundleBreakdown
8 | import com.kernel.bundlesaver.utils.kb
9 |
10 | /**
11 | * Interface that provides flexibility in how BundleSaver's output is formatted.
12 | * The default implementation [DefaultFormatter] should be suitable for most use cases.
13 | */
14 | interface Formatter {
15 | fun format(activity: Activity, bundle: Bundle): String
16 | fun format(fragmentManager: FragmentManager, fragment: Fragment, bundle: Bundle): String
17 | fun format(size: Int, limit: Int): String
18 | }
19 |
20 | /**
21 | * The default implementation of the [Formatter] interface.
22 | */
23 | class DefaultFormatter : Formatter {
24 |
25 | override fun format(activity: Activity, bundle: Bundle): String {
26 | return "${activity.javaClass.simpleName}.onSaveInstanceState wrote: ${bundleBreakdown(bundle)}"
27 | }
28 |
29 | override fun format(fragmentManager: FragmentManager, fragment: Fragment, bundle: Bundle): String {
30 | var message = "${fragment.javaClass.simpleName}.onSaveInstanceState wrote: ${bundleBreakdown(bundle)}"
31 | val fragmentArguments = fragment.arguments
32 | if (fragmentArguments != null) {
33 | message += "\n* fragment arguments = ${bundleBreakdown(fragmentArguments)}"
34 | }
35 | return message
36 | }
37 |
38 | override fun format(size: Int, limit: Int): String {
39 | return "Bundle size exceeded the limit of ${kb(limit)} KB. Current size: ${kb(size)}"
40 | }
41 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/kernel/bundlesaver/FragmentSavedStateLogger.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver
2 |
3 | import android.os.Bundle
4 | import androidx.fragment.app.Fragment
5 | import androidx.fragment.app.FragmentManager
6 |
7 | /**
8 | * [FragmentManager.FragmentLifecycleCallbacks] implementation that logs information about the
9 | * saved state of Fragments.
10 | */
11 | internal class FragmentSavedStateLogger(
12 | private val formatter: Formatter,
13 | private val logger: Logger
14 | ) : FragmentManager.FragmentLifecycleCallbacks() {
15 |
16 | private val savedStates = HashMap()
17 | private var isLogging = true
18 |
19 | override fun onFragmentSaveInstanceState(fragmentManager: FragmentManager, fragment: Fragment, outState: Bundle) {
20 | if (isLogging) {
21 | savedStates[fragment] = outState
22 | }
23 | }
24 |
25 | override fun onFragmentStopped(fragmentManager: FragmentManager, fragment: Fragment) {
26 | logAndRemoveSavedState(fragment, fragmentManager)
27 | }
28 |
29 | override fun onFragmentDestroyed(fragmentManager: FragmentManager, fragment: Fragment) {
30 | logAndRemoveSavedState(fragment, fragmentManager)
31 | }
32 |
33 | private fun logAndRemoveSavedState(fragment: Fragment, fragmentManager: FragmentManager) {
34 | val savedState = savedStates.remove(fragment)
35 | if (savedState != null) {
36 | try {
37 | val message = formatter.format(
38 | fragmentManager = fragmentManager,
39 | fragment = fragment,
40 | bundle = savedState
41 | )
42 | logger.log(message = message)
43 | } catch (exception: RuntimeException) {
44 | logger.logException(exception = exception)
45 | }
46 | }
47 | }
48 |
49 | internal fun startLogging() {
50 | isLogging = true
51 | }
52 |
53 | internal fun stopLogging() {
54 | isLogging = false
55 | }
56 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/kernel/bundlesaver/Logger.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver
2 |
3 | import android.util.Log
4 |
5 | /**
6 | * Interface that provides flexibility in how BundleSaver's output is logged.
7 | * The default implementation [DefaultLogger] should be suitable for most use cases.
8 | */
9 | interface Logger {
10 | fun log(message: String)
11 | fun logException(exception: Exception)
12 | }
13 |
14 | /**
15 | * The default implementation of the [Logger] interface, which logs messages to Logcat.
16 | */
17 | class DefaultLogger(private val priority: Int = Log.DEBUG, private val tag: String = "BundleSaver") : Logger {
18 |
19 | override fun log(message: String) {
20 | Log.println(priority, tag, message)
21 | }
22 |
23 | override fun logException(exception: Exception) {
24 | Log.w(tag, exception.message, exception)
25 | }
26 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/kernel/bundlesaver/SizeTree.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver
2 |
3 | /**
4 | * Data class representing a hierarchical structure of items with associated sizes.
5 | * Each node in the tree has a unique key, a total size, and a list of subtrees.
6 | */
7 | internal data class SizeTree(
8 | val key: String,
9 | val totalSize: Int,
10 | val subTrees: List = emptyList()
11 | )
--------------------------------------------------------------------------------
/library/src/main/java/com/kernel/bundlesaver/disk/DiskHandler.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver.disk
2 |
3 | /**
4 | * A simple interface for managing the storage and retrieval of data to and from disk. All calls
5 | * should be assumed to be blocking.
6 | */
7 | internal interface DiskHandler {
8 | /**
9 | * Clears any saved data associated with the given `key`.
10 | *
11 | * @param key The key for the saved data to clear.
12 | */
13 | fun clear(key: String)
14 |
15 | /**
16 | * Clears all saved data currently stored by the handler.
17 | */
18 | fun clearAll()
19 |
20 | /**
21 | * Retrieves the saved data associated with the given `key` as a byte array (or
22 | * `null` if there is no data available).
23 | *
24 | * @param key The key associated with the saved data to be retrieved.
25 | * @return The saved data as a byte array (or `null` if there is no data available).
26 | */
27 | fun getBytes(key: String): ByteArray?
28 |
29 | /**
30 | * Stores the given `bytes` to disk and associates them with the given `key` for
31 | * retrieval later.
32 | *
33 | * @param key The key to associate with the saved data.
34 | * @param bytes The data to be saved.
35 | */
36 | fun putBytes(key: String, bytes: ByteArray)
37 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/kernel/bundlesaver/disk/FileDiskHandler.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver.disk
2 |
3 | import android.content.Context
4 | import androidx.annotation.Nullable
5 | import java.io.File
6 | import java.io.FileInputStream
7 | import java.io.FileOutputStream
8 | import java.util.concurrent.ConcurrentHashMap
9 | import java.util.concurrent.ExecutorService
10 | import java.util.concurrent.Future
11 | import java.util.concurrent.TimeUnit
12 |
13 | private const val DIRECTORY_NAME = "bundle_saver"
14 | private const val BACKGROUND_WAIT_TIMEOUT_MS = 1000L
15 |
16 | /**
17 | * A simple implementation of [DiskHandler] that saves the requested data to individual files.
18 | * Similar to [android.content.SharedPreferences], this implementation will begin loading the
19 | * saved data into memory as soon as it is constructed and block on the first call until all data
20 | * is loaded (or some cutoff is reached).
21 | */
22 | internal class FileDiskHandler(context: Context, executorService: ExecutorService) : DiskHandler {
23 |
24 | private val directory: File = context.getDir(DIRECTORY_NAME, Context.MODE_PRIVATE)
25 | private val pendingLoadFuture: Future<*> = executorService.submit { loadAllFiles() }
26 | private val keyByteMap = ConcurrentHashMap()
27 |
28 | /**
29 | * Determines whether the [waitForFilesToLoad] call has completed in some way.
30 | */
31 | @Volatile
32 | private var isLoadedOrTimedOut = false
33 |
34 | override fun clearAll() {
35 | cancelFileLoading()
36 | keyByteMap.clear()
37 | deleteFilesByKey(null)
38 | }
39 |
40 | override fun clear(key: String) {
41 | cancelFileLoading()
42 | keyByteMap.remove(key)
43 | deleteFilesByKey(key)
44 | }
45 |
46 | override fun getBytes(key: String): ByteArray? {
47 | waitForFilesToLoad()
48 | return getBytesInternal(key)
49 | }
50 |
51 | override fun putBytes(key: String, bytes: ByteArray) {
52 | // Place the data in memory first
53 | keyByteMap[key] = bytes
54 |
55 | // Write the data to disk
56 | val file = File(directory, key)
57 | FileOutputStream(file).use { outStream ->
58 | outStream.write(bytes)
59 | }
60 | }
61 |
62 | /**
63 | * Cancels any pending file loading that happens at startup.
64 | */
65 | private fun cancelFileLoading() {
66 | pendingLoadFuture.cancel(true)
67 | }
68 |
69 | /**
70 | * Deletes all files associated with the given [key]. If the key is null, then
71 | * all stored files will be deleted.
72 | *
73 | * @param key The key associated with the data to delete (or null if all data should be
74 | * deleted).
75 | */
76 | private fun deleteFilesByKey(key: String?) {
77 | directory.listFiles()?.forEach { file ->
78 | if (key == null || getFileNameForKey(key) == file.name) {
79 | file.delete()
80 | }
81 | }
82 | }
83 |
84 | @Nullable
85 | private fun getBytesFromDisk(key: String): ByteArray? {
86 | val file = getFileByKey(key) ?: return null
87 |
88 | return FileInputStream(file).use { inputStream ->
89 | val bytes = ByteArray(file.length().toInt())
90 | inputStream.read(bytes)
91 | bytes
92 | }
93 | }
94 |
95 | @Nullable
96 | private fun getBytesInternal(key: String): ByteArray? {
97 | // Check for data loaded into memory from the initial load
98 | val cachedBytes = keyByteMap[key]
99 | if (cachedBytes != null) {
100 | return cachedBytes
101 | }
102 |
103 | // Get bytes from disk and place into memory if necessary
104 | val bytes = getBytesFromDisk(key)
105 | if (bytes != null) {
106 | keyByteMap[key] = bytes
107 | }
108 |
109 | return bytes
110 | }
111 |
112 | private fun getFileNameForKey(key: String): String {
113 | // For now the key and filename are equivalent
114 | return key
115 | }
116 |
117 | @Nullable
118 | private fun getFileByKey(key: String): File? {
119 | return directory.listFiles()?.find { file ->
120 | getFileNameForKey(key) == file.name
121 | }
122 | }
123 |
124 | private fun getKeyForFileName(fileName: String): String {
125 | // For now the key and filename are equivalent
126 | return fileName
127 | }
128 |
129 | private fun loadAllFiles() {
130 | directory.listFiles()?.forEach { file ->
131 | // Populate the cached map
132 | val key = getKeyForFileName(file.name)
133 | getBytesInternal(key)
134 | }
135 | }
136 |
137 | private fun waitForFilesToLoad() {
138 | if (isLoadedOrTimedOut) {
139 | // No need to wait.
140 | return
141 | }
142 | try {
143 | pendingLoadFuture.get(BACKGROUND_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS)
144 | } catch (e: Exception) {
145 | // We've made a best effort to load the data in the background. We can simply proceed
146 | // here.
147 | }
148 | isLoadedOrTimedOut = true
149 | }
150 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/kernel/bundlesaver/exceptions/BundleSizeExceededException.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver.exceptions
2 |
3 | /**
4 | * Custom exception thrown when the size of a Bundle exceeds the specified limit.
5 | */
6 | class BundleSizeExceededException(message: String) : Exception(message)
--------------------------------------------------------------------------------
/library/src/main/java/com/kernel/bundlesaver/utils/Converter.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver.utils
2 |
3 | import android.os.Bundle
4 | import android.os.Parcel
5 |
6 | /**
7 | * Helper class for converting [Bundle] instances to and from bytes.
8 | */
9 | internal object Converter {
10 |
11 | /**
12 | * Converts the given [Bundle] to raw bytes.
13 | *
14 | * Note that if the [Bundle] contains some highly specialized classes
15 | * [android.os.IBinder], this process will fail.
16 | */
17 | fun toBytes(bundle: Bundle): ByteArray {
18 | val parcel = Parcel.obtain()
19 | parcel.writeBundle(bundle)
20 | val bytes = parcel.marshall()
21 | parcel.recycle()
22 | return bytes
23 | }
24 |
25 | /**
26 | * Converts the given bytes to a [Bundle].
27 | *
28 | * Note that if the bytes do not represent a [Bundle] that was previously converted with
29 | * [toBytes], this process will likely fail and will return `null`.
30 | */
31 | fun fromBytes(bytes: ByteArray): Bundle? {
32 | val parcel = Parcel.obtain()
33 | parcel.unmarshall(bytes, 0, bytes.size)
34 | parcel.setDataPosition(0)
35 | val bundle: Bundle? = try {
36 | parcel.readBundle(Converter::class.java.classLoader)
37 | } catch (e: IllegalArgumentException) {
38 | null
39 | } catch (e: IllegalStateException) {
40 | null
41 | }
42 | parcel.recycle()
43 | return bundle
44 | }
45 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/kernel/bundlesaver/utils/Size.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver.utils
2 |
3 | import android.os.Bundle
4 | import android.os.Parcel
5 | import com.kernel.bundlesaver.SizeTree
6 | import java.util.Locale
7 |
8 | /**
9 | * Measure the sizes of all the values in a typed [Bundle] when written to a
10 | * [Parcel]. Returns a map from keys to the sizes, in bytes, of the associated values in
11 | * the Bundle.
12 | */
13 | internal fun sizeTreeFromBundle(bundle: Bundle): SizeTree {
14 | val results = ArrayList(bundle.size())
15 | // We measure the totalSize of each value by measuring the total totalSize of the bundle before and
16 | // after removing that value and calculating the difference. We make a copy of the original
17 | // bundle so we can put all the original values back at the end. It's not possible to
18 | // carry out the measurements on the copy because of the way Android parcelables work
19 | // under the hood where certain objects are actually stored as references.
20 | val copy = Bundle(bundle)
21 | try {
22 | var bundleSize = sizeAsParcel(bundle)
23 | // Iterate over copy's keys because we're removing those of the original bundle
24 | for (key in copy.keySet()) {
25 | bundle.remove(key)
26 | val newBundleSize = sizeAsParcel(bundle)
27 | val valueSize = bundleSize - newBundleSize
28 | results.add(SizeTree(key, valueSize, emptyList()))
29 | bundleSize = newBundleSize
30 | }
31 | } finally {
32 | // Put everything back into original bundle
33 | bundle.putAll(copy)
34 | }
35 | return SizeTree("Bundle" + System.identityHashCode(bundle), sizeAsParcel(bundle), results)
36 | }
37 |
38 | /**
39 | * Measure the size of a typed [Bundle] when written to a [Parcel].
40 | */
41 | internal fun sizeAsParcel(bundle: Bundle): Int {
42 | try {
43 | val parcel = Parcel.obtain()
44 | try {
45 | parcel.writeBundle(bundle)
46 | return parcel.dataSize()
47 | } finally {
48 | parcel.recycle()
49 | }
50 | } catch (exception: OutOfMemoryError) {
51 | return -1
52 | }
53 | }
54 |
55 | /**
56 | * Converts the given number of bytes to kilobytes.
57 | */
58 | internal fun kb(bytes: Int): Float {
59 | return bytes.toFloat() / 1000f
60 | }
61 |
62 | /**
63 | * Return a formatted String containing a breakdown of the contents of a [Bundle].
64 | *
65 | * @param bundle to format
66 | * @return a nicely formatted string (multi-line)
67 | */
68 | fun bundleBreakdown(bundle: Bundle): String {
69 | val (key, totalSize, subTrees) = sizeTreeFromBundle(bundle)
70 | var result = String.format(
71 | Locale.UK,
72 | "%s contains %d keys and measures %,.1f KB when serialized as a Parcel",
73 | key,
74 | subTrees.size,
75 | kb(totalSize)
76 | )
77 | for ((key1, totalSize1) in subTrees) {
78 | result += String.format(
79 | Locale.UK,
80 | "\n* %s = %,.1f KB",
81 | key1, kb(totalSize1)
82 | )
83 | }
84 | return result
85 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/kernel/bundlesaver/wrapper/BitmapWrapper.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver.wrapper
2 |
3 | import android.graphics.Bitmap
4 | import android.os.Bundle
5 | import android.os.Parcel
6 | import android.os.Parcelable
7 | import java.nio.ByteBuffer
8 |
9 | /**
10 | * A wrapper class for a [Bitmap] that allows it to be placed into a [android.os.Bundle]
11 | * and written to disk.
12 | */
13 | internal class BitmapWrapper(internal val bitmap: Bitmap) : Parcelable {
14 |
15 | //region Parcelable
16 | constructor(parcel: Parcel) : this(
17 | bitmap = Bitmap.createBitmap(
18 | parcel.readInt(),
19 | parcel.readInt(),
20 | Bitmap.Config.values()[parcel.readInt()]
21 | ).apply {
22 | parcel.createByteArray()?.also {
23 | copyPixelsFromBuffer(ByteBuffer.wrap(it))
24 | }
25 | }
26 | )
27 |
28 | override fun writeToParcel(dest: Parcel, flags: Int) {
29 | val size = bitmap.allocationByteCount
30 | val byteBuffer = ByteBuffer.allocate(size)
31 | bitmap.copyPixelsToBuffer(byteBuffer)
32 |
33 | with(dest) {
34 | writeInt(bitmap.width)
35 | writeInt(bitmap.height)
36 | writeInt(bitmap.config.ordinal)
37 | writeByteArray(byteBuffer.array())
38 | }
39 | }
40 |
41 | override fun describeContents(): Int = 0
42 |
43 | companion object CREATOR : Parcelable.Creator {
44 | override fun createFromParcel(parcel: Parcel): BitmapWrapper = BitmapWrapper(parcel)
45 |
46 | override fun newArray(size: Int): Array = arrayOfNulls(size)
47 | }
48 | //endregion Parcelable
49 | }
50 |
51 | /**
52 | * Manages the wrapping and unwrapping of certain [android.os.Parcelable] objects that use
53 | * native code to optimize their [android.os.Parcelable] implementations. If these objects are placed into a [Bundle]
54 | * unwrapped, they may cause a crash if the [Bundle] is written to a [android.os.Parcel] that then calls
55 | * [Parcel.marshall].
56 | */
57 | internal fun unwrapOptimizedObjects(bundle: Bundle) {
58 | val keys = bundle.keySet()
59 | for (key in keys) {
60 | val value = bundle.get(key)
61 | if (value is BitmapWrapper) {
62 | bundle.putParcelable(key, value.bitmap)
63 | }
64 | }
65 | }
66 |
67 | internal fun wrapOptimizedObjects(bundle: Bundle) {
68 | val keys = bundle.keySet()
69 | for (key in keys) {
70 | val value = bundle.get(key)
71 | if (value is Bitmap) {
72 | bundle.putParcelable(key, BitmapWrapper(value))
73 | }
74 | }
75 | }
--------------------------------------------------------------------------------
/sample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 | apply plugin: "kotlin-android"
3 |
4 | android {
5 | compileSdkVersion versions.compileSdk
6 | defaultConfig {
7 | minSdkVersion versions.minSdk
8 | targetSdkVersion versions.targetSdk
9 | applicationId "com.kernel.bundlesaver.sample"
10 | versionCode 1
11 | versionName "1.0"
12 | }
13 |
14 | buildTypes {
15 | debug {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | release {
20 | minifyEnabled true
21 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 |
25 | compileOptions {
26 | sourceCompatibility JavaVersion.VERSION_1_8
27 | targetCompatibility JavaVersion.VERSION_1_8
28 | }
29 | }
30 |
31 | dependencies {
32 | debugImplementation project(':library')
33 | //implementation "com.github.kernel0x:bundlesaver:1.0.0"
34 | implementation "androidx.fragment:fragment:$versions.androidxFragment"
35 | }
--------------------------------------------------------------------------------
/sample/proguard-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kernel0x/bundlesaver/8a20183fbdb6f731b7fcc0d10308bd3dffb53299/sample/proguard-rules.pro
--------------------------------------------------------------------------------
/sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
9 |
10 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/kernel/bundlesaver/sample/App.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver.sample
2 |
3 | import android.app.Application
4 | import com.kernel.bundlesaver.BundleManager
5 |
6 | class App : Application() {
7 |
8 | override fun onCreate() {
9 | super.onCreate()
10 | BundleManager.initialize(this)
11 | }
12 | }
--------------------------------------------------------------------------------
/sample/src/main/java/com/kernel/bundlesaver/sample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.kernel.bundlesaver.sample
2 |
3 | import android.app.Activity
4 | import android.os.Bundle
5 | import com.kernel.bundlesaver.BundleManager
6 |
7 | class MainActivity : Activity() {
8 |
9 | override fun onCreate(savedInstanceState: Bundle?) {
10 | BundleManager.restoreInstanceState(this, savedInstanceState)
11 | super.onCreate(savedInstanceState)
12 | }
13 |
14 | override fun onSaveInstanceState(outState: Bundle) {
15 | val largeObject = ByteArray(10 * 1024 * 1024) // 10 МБ
16 | outState.putByteArray("test", largeObject)
17 | super.onSaveInstanceState(outState)
18 | BundleManager.saveInstanceState(this, outState)
19 | }
20 | }
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Bundle Saver Sample
3 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ":sample"
2 | include ':library'
--------------------------------------------------------------------------------