├── .gitignore
├── LICENSE
├── README-Chinese.md
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── zxy
│ │ └── recovery
│ │ └── test
│ │ ├── App.java
│ │ ├── BaseActivity.java
│ │ ├── MainActivity.java
│ │ ├── MyCrashHandler.java
│ │ ├── TestActivity.java
│ │ └── TestActivity2.java
│ └── res
│ ├── layout
│ ├── activity_main.xml
│ ├── activity_test.xml
│ └── activity_test2.xml
│ ├── mipmap-hdpi
│ └── ic_launcher.png
│ ├── mipmap-mdpi
│ └── ic_launcher.png
│ ├── mipmap-xhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxxhdpi
│ └── ic_launcher.png
│ ├── values-v21
│ └── styles.xml
│ ├── values-w820dp
│ └── dimens.xml
│ └── values
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── recovery-no-op
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── zxy
│ │ └── recovery
│ │ ├── callback
│ │ └── RecoveryCallback.java
│ │ └── core
│ │ └── Recovery.java
│ └── res
│ └── values
│ └── strings.xml
├── recovery.jpg
├── recovery
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── zxy
│ │ └── recovery
│ │ ├── callback
│ │ ├── RecoveryActivityLifecycleCallback.java
│ │ └── RecoveryCallback.java
│ │ ├── core
│ │ ├── ActivityManagerDelegate.java
│ │ ├── ActivityStackCompat.java
│ │ ├── ApplicationLoader.java
│ │ ├── CrashData.java
│ │ ├── Recovery.java
│ │ ├── RecoveryActivity.java
│ │ ├── RecoveryComponentHook.java
│ │ ├── RecoveryHandler.java
│ │ ├── RecoveryService.java
│ │ └── RecoveryStore.java
│ │ ├── exception
│ │ ├── RecoveryException.java
│ │ └── ReflectException.java
│ │ └── tools
│ │ ├── DefaultHandlerUtil.java
│ │ ├── RecoveryLog.java
│ │ ├── RecoverySharedPrefsUtil.java
│ │ ├── RecoverySilentSharedPrefsUtil.java
│ │ ├── RecoveryUtil.java
│ │ ├── Reflect.java
│ │ └── SharedPreferencesCompat.java
│ └── res
│ ├── drawable-xhdpi
│ └── ic_recovery_page.png
│ ├── drawable
│ └── recovery_default_btn_selector.xml
│ ├── layout
│ ├── recovery_activity_recover.xml
│ └── recovery_layout_debug.xml
│ ├── menu
│ ├── recovery_menu.xml
│ └── recovery_menu_sub.xml
│ ├── values-en
│ └── strings.xml
│ ├── values-v19
│ └── styles.xml
│ ├── values-v21
│ └── styles.xml
│ └── values
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### Android template
3 | # Built application files
4 | *.apk
5 | *.ap_
6 |
7 | # Files for the ART/Dalvik VM
8 | *.dex
9 |
10 | # Java class files
11 | *.class
12 |
13 | # Generated files
14 | bin/
15 | gen/
16 | out/
17 |
18 | # Gradle files
19 | .gradle/
20 | build/
21 |
22 | # Local configuration file (sdk path, etc)
23 | local.properties
24 |
25 | # Proguard folder generated by Eclipse
26 | proguard/
27 |
28 | # Log Files
29 | *.log
30 |
31 | # Android Studio Navigation editor temp files
32 | .navigation/
33 |
34 | # Android Studio captures folder
35 | captures/
36 |
37 | # Intellij
38 | *.iml
39 | .idea/
40 |
41 | # Keystore files
42 | *.jks
43 |
44 |
--------------------------------------------------------------------------------
/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-Chinese.md:
--------------------------------------------------------------------------------
1 | # **Recovery**
2 | A crash recovery framework!
3 |
4 | ----
5 |
6 | [  ](https://bintray.com/sunzxyong/maven/Recovery/_latestVersion)  [](https://github.com/Sunzxyong/Recovery/blob/master/LICENSE)
7 |
8 | [英文文档](https://github.com/Sunzxyong/Recovery/blob/master/README.md)
9 |
10 | # **Introduce**
11 |
12 | [博客介绍](http://zhengxiaoyong.com/2016/09/05/Android%E8%BF%90%E8%A1%8C%E6%97%B6Crash%E8%87%AA%E5%8A%A8%E6%81%A2%E5%A4%8D%E6%A1%86%E6%9E%B6-Recovery)
13 |
14 | “Recovery”帮助你自动处理程序在运行时的Crash,它含有以下几点功能
15 |
16 | * 自动恢复Activity Stack和数据
17 | * 支持只恢复栈顶Activity
18 | * Crash信息的显示与保存
19 | * 应用重启或者清空缓存
20 | * 一分钟内两次恢复失败不再恢复而进行重启应用
21 |
22 | # **Art**
23 | 
24 |
25 | # **Usage**
26 | ## **Reference**
27 | **Gradle**
28 |
29 | ```
30 | implementation 'com.zxy.android:recovery:1.0.0'
31 | ```
32 |
33 | 或者
34 |
35 | ```gradle
36 | debugImplementation 'com.zxy.android:recovery:1.0.0'
37 | releaseImplementation 'com.zxy.android:recovery-no-op:1.0.0'
38 | ```
39 |
40 |
41 | **Maven**
42 |
43 | ```
44 |
45 | com.zxy.android
46 | recovery
47 | 1.0.0
48 | pom
49 |
50 | ```
51 | ## **Init**
52 | 你可以使用类似如下初始化代码在你自定义的Application中进行初始化:
53 |
54 | ```java
55 | Recovery.getInstance()
56 | .debug(true)
57 | .recoverInBackground(false)
58 | .recoverStack(true)
59 | .mainPage(MainActivity.class)
60 | .recoverEnabled(true)
61 | .callback(new MyCrashCallback())
62 | .silent(false, Recovery.SilentMode.RECOVER_ACTIVITY_STACK)
63 | .skip(TestActivity.class)
64 | .init(this);
65 | ```
66 |
67 | 如果你不想在应用发生Crash时显示RecoveryActivity,你可以使用静默恢复来进行无界面的恢复你的应用,那么请使用类似如下初始化代码在你自定义的Application中进行初始化:
68 |
69 | ```java
70 | Recovery.getInstance()
71 | .debug(true)
72 | .recoverInBackground(false)
73 | .recoverStack(true)
74 | .mainPage(MainActivity.class)
75 | .recoverEnabled(true)
76 | .callback(new MyCrashCallback())
77 | .silent(false, Recovery.SilentMode.RECOVER_ACTIVITY_STACK)
78 | .skip(TestActivity.class)
79 | .init(this);
80 | ```
81 |
82 | 如果你仅仅需要在开发时显示RecoveryActivity界面来获取debug数据,而在线上版本不显示,那么可以设置`recoverEnabled(false);`
83 |
84 | ## **Arguments**
85 |
86 | | Argument | Type | Function |
87 | | :-: | :-: | :-: |
88 | | debug | boolean | 是否开启debug模式 |
89 | | recoverInBackgroud | boolean | 当应用在后台时发生Crash,是否需要进行恢复 |
90 | | recoverStack | boolean | 是否恢复整个Activity Stack,否则将恢复栈顶Activity |
91 | | mainPage | Class extends Activity> | 回退的界面 |
92 | | callback | RecoveryCallback | 发生Crash时的回调 |
93 | | silent | boolean,SilentMode | 是否使用静默恢复,如果设置为true的情况下,那么在发生Crash时将不显示RecoveryActivity界面来进行恢复,而是自动的恢复Activity的堆栈和数据,也就是无界面恢复 |
94 |
95 | **SilentMode**
96 | > 1. RESTART - 重启应用
97 | > 2. RECOVER_ACTIVITY_STACK - 恢复Activity堆栈
98 | > 3. RECOVER_TOP_ACTIVITY - 恢复栈顶Activity
99 | > 4. RESTART_AND_CLEAR - 重启应用并清空缓存数据
100 |
101 | ## **Callback**
102 |
103 | ```
104 | public interface RecoveryCallback {
105 |
106 | void stackTrace(String stackTrace);
107 |
108 | void cause(String cause);
109 |
110 | void exception(String throwExceptionType, String throwClassName, String throwMethodName, int throwLineNumber);
111 |
112 | void throwable(Throwable throwable);
113 | }
114 | ```
115 |
116 | ## **Custom Theme**
117 |
118 | 自定义RecoveryActivity的主题,需重写以下styles属性:
119 |
120 | ```
121 | #2E2E36
122 | #2E2E36
123 | #BDBDBD
124 | #3C4350
125 | #FFFFFF
126 | #C6C6C6
127 | ```
128 | ## **Crash File Path**
129 | > {SDCard Dir}/Android/data/{packageName}/files/recovery_crash/
130 |
131 | ## **Update history**
132 | * `VERSION-0.0.5`——**支持静默恢复**
133 | * `VERSION-0.0.6`——**加强静默恢复模式的保护**
134 | * `VERSION-0.0.7`——**添加混淆配置**
135 | * `VERSION-0.0.8`——**增加可配置不需要恢复的Activity,方法:skip()**
136 | * `VERSION-0.0.9`——**更新UI和解决一些问题**
137 | * `VERSION-0.1.0`——**异常传递的优化,可在任意位置初始化Recovery框架,发布正式版本**
138 | * `VERSION-0.1.3`——**增加no-op包**
139 | * `VERSION-0.1.4`——**更新默认主题.**
140 | * `VERSION-0.1.5`——**fix 8.0+ hook bug**
141 | * `VERSION-0.1.6`——**update**
142 | * `VERSION-1.0.0`——**修复8.0上兼容性问题**
143 |
144 | ## **About**
145 | * **Blog**:[https://zhengxiaoyong.com](https://zhengxiaoyong.com)
146 | * **Wechat**:
147 |
148 | 
149 |
150 | # **LICENSE**
151 |
152 | ```
153 | Copyright 2016 zhengxiaoyong
154 |
155 | Licensed under the Apache License, Version 2.0 (the "License");
156 | you may not use this file except in compliance with the License.
157 | You may obtain a copy of the License at
158 |
159 | http://www.apache.org/licenses/LICENSE-2.0
160 |
161 | Unless required by applicable law or agreed to in writing, software
162 | distributed under the License is distributed on an "AS IS" BASIS,
163 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
164 | See the License for the specific language governing permissions and
165 | limitations under the License.
166 | ```
167 |
168 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # **Recovery**
2 | A crash recovery framework!
3 |
4 | ----
5 |
6 | [  ](https://bintray.com/sunzxyong/maven/Recovery/_latestVersion)  [](https://github.com/Sunzxyong/Recovery/blob/master/LICENSE)
7 |
8 | [中文文档](https://github.com/Sunzxyong/Recovery/blob/master/README-Chinese.md)
9 |
10 | # **Introduction**
11 |
12 | [Blog entry with introduction](http://zhengxiaoyong.com/2016/09/05/Android%E8%BF%90%E8%A1%8C%E6%97%B6Crash%E8%87%AA%E5%8A%A8%E6%81%A2%E5%A4%8D%E6%A1%86%E6%9E%B6-Recovery)
13 |
14 | “Recovery” can help you to automatically handle application crash in runtime. It provides you with following functionality:
15 |
16 | * Automatic recovery activity with stack and data;
17 | * Ability to recover to the top activity;
18 | * A way to view and save crash info;
19 | * Ability to restart and clear the cache;
20 | * Allows you to do a restart instead of recovering if failed twice in one minute.
21 |
22 | # **Art**
23 | 
24 |
25 | # **Usage**
26 | ## **Installation**
27 | **Using Gradle**
28 |
29 | ```gradle
30 | implementation 'com.zxy.android:recovery:1.0.0'
31 | ```
32 |
33 | or
34 |
35 | ```gradle
36 | debugImplementation 'com.zxy.android:recovery:1.0.0'
37 | releaseImplementation 'com.zxy.android:recovery-no-op:1.0.0'
38 | ```
39 |
40 |
41 | **Using Maven**
42 |
43 | ```xml
44 |
45 | com.zxy.android
46 | recovery
47 | 1.0.0
48 | pom
49 |
50 | ```
51 |
52 | ## **Initialization**
53 | You can use this code sample to initialize Recovery in your application:
54 |
55 | ```java
56 | Recovery.getInstance()
57 | .debug(true)
58 | .recoverInBackground(false)
59 | .recoverStack(true)
60 | .mainPage(MainActivity.class)
61 | .recoverEnabled(true)
62 | .callback(new MyCrashCallback())
63 | .silent(false, Recovery.SilentMode.RECOVER_ACTIVITY_STACK)
64 | .skip(TestActivity.class)
65 | .init(this);
66 | ```
67 |
68 | If you don't want to show the RecoveryActivity when the application crash in runtime,you can use silence recover to restore your application.
69 |
70 | You can use this code sample to initialize Recovery in your application:
71 |
72 | ```java
73 | Recovery.getInstance()
74 | .debug(true)
75 | .recoverInBackground(false)
76 | .recoverStack(true)
77 | .mainPage(MainActivity.class)
78 | .recoverEnabled(true)
79 | .callback(new MyCrashCallback())
80 | .silent(true, Recovery.SilentMode.RECOVER_ACTIVITY_STACK)
81 | .skip(TestActivity.class)
82 | .init(this);
83 | ```
84 |
85 | If you only need to display 'RecoveryActivity' page in development to obtain the debug data, and in the online version does not display, you can set up `recoverEnabled(false);`
86 |
87 | ## **Arguments**
88 |
89 | | Argument | Type | Function |
90 | | :-: | :-: | :-: |
91 | | debug | boolean | Whether to open the debug mode |
92 | | recoverInBackgroud | boolean | When the App in the background, whether to restore the stack |
93 | | recoverStack | boolean | Whether to restore the activity stack, or to restore the top activity |
94 | | mainPage | Class extends Activity> | Initial page activity |
95 | | callback | RecoveryCallback | Crash info callback |
96 | | silent | boolean,SilentMode | Whether to use silence recover,if true it will not display RecoveryActivity and restore the activity stack automatically |
97 |
98 | **SilentMode**
99 | > 1. RESTART - Restart App
100 | > 2. RECOVER_ACTIVITY_STACK - Restore the activity stack
101 | > 3. RECOVER_TOP_ACTIVITY - Restore the top activity
102 | > 4. RESTART_AND_CLEAR - Restart App and clear data
103 |
104 | ## **Callback**
105 |
106 | ```java
107 | public interface RecoveryCallback {
108 |
109 | void stackTrace(String stackTrace);
110 |
111 | void cause(String cause);
112 |
113 | void exception(
114 | String throwExceptionType,
115 | String throwClassName,
116 | String throwMethodName,
117 | int throwLineNumber
118 | );
119 |
120 | void throwable(Throwable throwable);
121 | }
122 | ```
123 |
124 | ## **Custom Theme**
125 |
126 | You can customize UI by setting these properties in your styles file:
127 |
128 | ```xml
129 | #2E2E36
130 | #2E2E36
131 | #BDBDBD
132 | #3C4350
133 | #FFFFFF
134 | #C6C6C6
135 | ```
136 |
137 | ## **Crash File Path**
138 | > {SDCard Dir}/Android/data/{packageName}/files/recovery_crash/
139 |
140 | ----
141 | ## **Update history**
142 | * `VERSION-0.0.5`——**Support silent recovery**
143 | * `VERSION-0.0.6`——**Strengthen the protection of silent restore mode**
144 | * `VERSION-0.0.7`——**Add confusion configuration**
145 | * `VERSION-0.0.8`——**Add the skip Activity features,method:skip()**
146 | * `VERSION-0.0.9`——**Update the UI and solve some problems**
147 | * `VERSION-0.1.0`——**Optimization of crash exception delivery, initial Recovery framework can be in any position, release the official version-0.1.0**
148 | * `VERSION-0.1.3`——**Add 'no-op' support**
149 | * `VERSION-0.1.4`——**update default theme**
150 | * `VERSION-0.1.5`——**fix 8.0+ hook bug**
151 | * `VERSION-0.1.6`——**update**
152 | * `VERSION-1.0.0`——**Fix 8.0 compatibility issue**
153 |
154 | ## **About**
155 | * **Blog**:[https://zhengxiaoyong.com](https://zhengxiaoyong.com)
156 | * **Wechat**:
157 |
158 | 
159 | # **LICENSE**
160 |
161 | ```
162 | Copyright 2016 zhengxiaoyong
163 |
164 | Licensed under the Apache License, Version 2.0 (the "License");
165 | you may not use this file except in compliance with the License.
166 | You may obtain a copy of the License at
167 |
168 | http://www.apache.org/licenses/LICENSE-2.0
169 |
170 | Unless required by applicable law or agreed to in writing, software
171 | distributed under the License is distributed on an "AS IS" BASIS,
172 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
173 | See the License for the specific language governing permissions and
174 | limitations under the License.
175 | ```
176 |
177 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 26
5 |
6 | resourcePrefix ""
7 | defaultConfig {
8 | applicationId "com.zxy.recovery.test"
9 | minSdkVersion 14
10 | targetSdkVersion 26
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | lintOptions {
21 | abortOnError false
22 | }
23 |
24 | }
25 |
26 | dependencies {
27 | implementation fileTree(include: ['*.jar'], dir: 'libs')
28 |
29 | // debugCompile 'com.zxy.android:recovery:0.1.5'
30 | // releaseCompile 'com.zxy.android:recovery-no-op:0.1.5'
31 | implementation 'com.android.support:appcompat-v7:25.2.0'
32 | implementation 'com.android.support:design:25.2.0'
33 | debugImplementation project(':recovery')
34 | releaseImplementation project(':recovery-no-op')
35 | }
36 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/Sunzxyong/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
13 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zxy/recovery/test/App.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.test;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 | import android.util.Log;
6 |
7 | import com.zxy.recovery.callback.RecoveryCallback;
8 | import com.zxy.recovery.core.Recovery;
9 |
10 | /**
11 | * Created by zhengxiaoyong on 16/8/26.
12 | */
13 | public class App extends Application {
14 | @Override
15 | protected void attachBaseContext(Context base) {
16 | super.attachBaseContext(base);
17 | }
18 |
19 | @Override
20 | public void onCreate() {
21 | super.onCreate();
22 |
23 | Log.e("zxy", "Recovery: init");
24 | Recovery.getInstance()
25 | .debug(true)
26 | .recoverInBackground(false)
27 | .recoverStack(true)
28 | .mainPage(MainActivity.class)
29 | .recoverEnabled(true)
30 | .callback(new MyCrashCallback())
31 | .silent(false, Recovery.SilentMode.RECOVER_ACTIVITY_STACK)
32 | .skip(TestActivity.class)
33 | .init(this);
34 |
35 | MyCrashHandler.register();
36 |
37 | }
38 |
39 | static final class MyCrashCallback implements RecoveryCallback {
40 | @Override
41 | public void stackTrace(String exceptionMessage) {
42 | Log.e("zxy", "exceptionMessage:" + exceptionMessage);
43 | }
44 |
45 | @Override
46 | public void cause(String cause) {
47 | Log.e("zxy", "cause:" + cause);
48 | }
49 |
50 | @Override
51 | public void exception(String exceptionType, String throwClassName, String throwMethodName, int throwLineNumber) {
52 | Log.e("zxy", "exceptionClassName:" + exceptionType);
53 | Log.e("zxy", "throwClassName:" + throwClassName);
54 | Log.e("zxy", "throwMethodName:" + throwMethodName);
55 | Log.e("zxy", "throwLineNumber:" + throwLineNumber);
56 | }
57 |
58 | @Override
59 | public void throwable(Throwable throwable) {
60 |
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zxy/recovery/test/BaseActivity.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.test;
2 |
3 | import android.os.Bundle;
4 | import android.support.annotation.Nullable;
5 | import android.support.v7.app.AppCompatActivity;
6 |
7 | /**
8 | * Created by zhengxiaoyong on 16/8/30.
9 | */
10 | public class BaseActivity extends AppCompatActivity {
11 | @Override
12 | protected void onCreate(@Nullable Bundle savedInstanceState) {
13 | super.onCreate(savedInstanceState);
14 | }
15 |
16 | @Override
17 | protected void onStart() {
18 | super.onStart();
19 | // getWindow().getDecorView().post(new Runnable() {
20 | // @Override
21 | // public void run() {
22 | // int count = ActivityStackCompat.getActivityCount(Recovery.getInstance().getContext());
23 | // Log.e("zxy", "realCount: " + count);
24 | // String baseActivity = ActivityStackCompat.getBaseActivityName(Recovery.getInstance().getContext());
25 | // Log.e("zxy", "realBaseActivityName: " + baseActivity);
26 | // }
27 | // });
28 |
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zxy/recovery/test/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.test;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 | import android.view.View;
7 |
8 | public class MainActivity extends BaseActivity {
9 |
10 | @Override
11 | protected void onCreate(Bundle savedInstanceState) {
12 | super.onCreate(savedInstanceState);
13 | setContentView(R.layout.activity_main);
14 | }
15 |
16 | public void onClick(View view) {
17 | if (view.getId() == R.id.btn) {
18 | Activity activity = null;
19 | activity.finish();
20 | } else if (view.getId() == R.id.btn2) {
21 | Intent intent = new Intent(MainActivity.this, TestActivity.class);
22 | startActivity(intent);
23 | }
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zxy/recovery/test/MyCrashHandler.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.test;
2 |
3 | import android.util.Log;
4 |
5 | /**
6 | * Created by zhengxiaoyong on 2017/1/16.
7 | */
8 | public class MyCrashHandler implements Thread.UncaughtExceptionHandler {
9 |
10 | private Thread.UncaughtExceptionHandler mUncaughtExceptionHandler;
11 |
12 | public MyCrashHandler() {
13 | mUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
14 | }
15 |
16 | @Override
17 | public void uncaughtException(Thread t, Throwable e) {
18 | Log.e("zxy", "myCrashHandler...");
19 | mUncaughtExceptionHandler.uncaughtException(t, e);
20 | }
21 |
22 |
23 | public static void register() {
24 | Thread.setDefaultUncaughtExceptionHandler(new MyCrashHandler());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zxy/recovery/test/TestActivity.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.test;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 | import android.view.View;
7 | import android.view.Window;
8 |
9 | public class TestActivity extends BaseActivity {
10 |
11 | @Override
12 | protected void onCreate(Bundle savedInstanceState) {
13 | super.onCreate(savedInstanceState);
14 | requestWindowFeature(Window.FEATURE_NO_TITLE);
15 | setContentView(R.layout.activity_test);
16 | // new Thread(new Runnable() {
17 | // int i = 0;
18 | //
19 | // @Override
20 | // public void run() {
21 | // while (true) {
22 | // if (i == 3) {
23 | // Activity activity = null;
24 | // activity.finish();
25 | // }
26 | // try {
27 | // Thread.sleep(1000);
28 | // } catch (InterruptedException e) {
29 | // e.printStackTrace();
30 | // }
31 | // i++;
32 | // }
33 | // }
34 | // }).start();
35 | }
36 |
37 | @Override
38 | protected void onResume() {
39 | super.onResume();
40 | }
41 |
42 | public void onClick(View view) {
43 | if (view.getId() == R.id.btn) {
44 | Activity activity = null;
45 | activity.finish();
46 | } else if (view.getId() == R.id.btn2) {
47 | Intent intent = new Intent(TestActivity.this, TestActivity2.class);
48 | startActivity(intent);
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zxy/recovery/test/TestActivity2.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.test;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 | import android.view.View;
7 |
8 | public class TestActivity2 extends BaseActivity {
9 |
10 | @Override
11 | protected void onCreate(Bundle savedInstanceState) {
12 | super.onCreate(savedInstanceState);
13 | setContentView(R.layout.activity_test2);
14 | }
15 |
16 | public void onClick(View view) {
17 | if (view.getId() == R.id.btn) {
18 | Activity activity = null;
19 | activity.finish();
20 | } else if (view.getId() == R.id.btn2) {
21 | startActivity(new Intent(this, MainActivity.class));
22 | }
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
18 |
19 |
24 |
25 |
31 |
32 |
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_test.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
19 |
20 |
25 |
26 |
32 |
33 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_test2.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
22 |
23 |
28 |
29 |
35 |
36 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sunzxyong/Recovery/bca6d12b91e37aaf8b85a9e8eccd2518047f434c/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sunzxyong/Recovery/bca6d12b91e37aaf8b85a9e8eccd2518047f434c/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sunzxyong/Recovery/bca6d12b91e37aaf8b85a9e8eccd2518047f434c/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sunzxyong/Recovery/bca6d12b91e37aaf8b85a9e8eccd2518047f434c/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sunzxyong/Recovery/bca6d12b91e37aaf8b85a9e8eccd2518047f434c/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-v21/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 | 16dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | RecoveryTest
3 | Main2Activity
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | google()
7 | mavenCentral()
8 | }
9 | dependencies {
10 | classpath 'com.android.tools.build:gradle:3.0.1'
11 | classpath 'com.novoda:bintray-release:0.6.1'
12 | // NOTE: Do not place your application dependencies here; they belong
13 | // in the individual module build.gradle files
14 | }
15 | }
16 |
17 | allprojects {
18 | repositories {
19 | jcenter()
20 | google()
21 | mavenCentral()
22 | }
23 | }
24 |
25 | task clean(type: Delete) {
26 | delete rootProject.buildDir
27 | }
28 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 | RECOVERY_VERSION=1.0.0
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sunzxyong/Recovery/bca6d12b91e37aaf8b85a9e8eccd2518047f434c/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Aug 25 16:50:33 CST 2016
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-4.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/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 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
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 Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/recovery-no-op/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/recovery-no-op/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.novoda.bintray-release'
3 |
4 | android {
5 | compileSdkVersion 26
6 |
7 | defaultConfig {
8 | minSdkVersion 14
9 | targetSdkVersion 26
10 | versionCode 1
11 | versionName "1.0"
12 |
13 | }
14 |
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 |
22 | lintOptions {
23 | abortOnError false
24 | }
25 |
26 | }
27 |
28 | dependencies {
29 | implementation fileTree(dir: 'libs', include: ['*.jar'])
30 | }
31 |
32 | Properties properties = new Properties()
33 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
34 |
35 | publish {
36 | userOrg = 'sunzxyong'
37 | uploadName = 'Recovery-no-op'
38 | groupId = 'com.zxy.android'
39 | artifactId = 'recovery-no-op'
40 | publishVersion = RECOVERY_VERSION
41 | repoName = 'maven'
42 | dryRun = 'false'
43 | desc = 'A crash recover framework'
44 | website = 'https://github.com/Sunzxyong/Recovery'
45 | issueTracker = 'https://github.com/Sunzxyong/Recovery/issues'
46 | repository = 'https://github.com/Sunzxyong/Recovery.git'
47 | bintrayUser = properties.getProperty("bintray.user")
48 | bintrayKey = properties.getProperty("bintray.apikey")
49 | }
--------------------------------------------------------------------------------
/recovery-no-op/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/Sunzxyong/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/recovery-no-op/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/recovery-no-op/src/main/java/com/zxy/recovery/callback/RecoveryCallback.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.callback;
2 |
3 | /**
4 | * Created by zhengxiaoyong on 16/8/29.
5 | */
6 | public interface RecoveryCallback {
7 |
8 | void stackTrace(String stackTrace);
9 |
10 | void cause(String cause);
11 |
12 | void exception(String throwExceptionType, String throwClassName, String throwMethodName, int throwLineNumber);
13 |
14 | void throwable(Throwable throwable);
15 | }
16 |
--------------------------------------------------------------------------------
/recovery-no-op/src/main/java/com/zxy/recovery/core/Recovery.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.core;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 |
6 | import com.zxy.recovery.callback.RecoveryCallback;
7 |
8 | /**
9 | * Created by zhengxiaoyong on 16/8/26.
10 | */
11 | public class Recovery {
12 |
13 | private volatile static Recovery sInstance;
14 |
15 | private static final Object LOCK = new Object();
16 |
17 | private Recovery() {
18 | }
19 |
20 | public static Recovery getInstance() {
21 | if (sInstance == null) {
22 | synchronized (LOCK) {
23 | if (sInstance == null) {
24 | sInstance = new Recovery();
25 | }
26 | }
27 | }
28 | return sInstance;
29 | }
30 |
31 | public void init(Context context) {
32 |
33 | }
34 |
35 | public Recovery debug(boolean isDebug) {
36 | return this;
37 | }
38 |
39 | public Recovery recoverStack(boolean isRecoverStack) {
40 | return this;
41 | }
42 |
43 | public Recovery recoverInBackground(boolean isRecoverInBackground) {
44 | return this;
45 | }
46 |
47 | public Recovery mainPage(Class extends Activity> clazz) {
48 | return this;
49 | }
50 |
51 | public Recovery callback(RecoveryCallback callback) {
52 | return this;
53 | }
54 |
55 | public Recovery silent(boolean enabled, SilentMode mode) {
56 | return this;
57 | }
58 |
59 | @SafeVarargs
60 | public final Recovery skip(Class extends Activity>... activities) {
61 | return this;
62 | }
63 |
64 | public Recovery recoverEnabled(boolean enabled) {
65 | return this;
66 | }
67 |
68 | public enum SilentMode {
69 | RESTART(1),
70 | RECOVER_ACTIVITY_STACK(2),
71 | RECOVER_TOP_ACTIVITY(3),
72 | RESTART_AND_CLEAR(4);
73 |
74 | int value;
75 |
76 | SilentMode(int value) {
77 | this.value = value;
78 | }
79 |
80 | public int getValue() {
81 | return value;
82 | }
83 |
84 | public static SilentMode getMode(int value) {
85 | switch (value) {
86 | case 1:
87 | return RESTART;
88 | case 2:
89 | return RECOVER_ACTIVITY_STACK;
90 | case 3:
91 | return RECOVER_TOP_ACTIVITY;
92 | case 4:
93 | return RESTART_AND_CLEAR;
94 | default:
95 | return RECOVER_ACTIVITY_STACK;
96 | }
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/recovery-no-op/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/recovery.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sunzxyong/Recovery/bca6d12b91e37aaf8b85a9e8eccd2518047f434c/recovery.jpg
--------------------------------------------------------------------------------
/recovery/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/recovery/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.novoda.bintray-release'
3 |
4 | android {
5 | compileSdkVersion 26
6 | resourcePrefix "recovery_"
7 | defaultConfig {
8 | minSdkVersion 14
9 | targetSdkVersion 26
10 | versionCode 1
11 | versionName "1.0"
12 |
13 | consumerProguardFiles 'proguard-rules.pro'
14 | }
15 |
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 |
23 | lintOptions {
24 | abortOnError false
25 | }
26 | }
27 |
28 | dependencies {
29 | implementation fileTree(include: ['*.jar'], dir: 'libs')
30 | implementation 'com.android.support:appcompat-v7:25.2.0'
31 | }
32 |
33 | Properties properties = new Properties()
34 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
35 |
36 | publish {
37 | userOrg = 'sunzxyong'
38 | uploadName = 'Recovery'
39 | groupId = 'com.zxy.android'
40 | artifactId = 'recovery'
41 | publishVersion = RECOVERY_VERSION
42 | repoName = 'maven'
43 | dryRun = 'false'
44 | desc = 'A crash recover framework'
45 | website = 'https://github.com/Sunzxyong/Recovery'
46 | issueTracker = 'https://github.com/Sunzxyong/Recovery/issues'
47 | repository = 'https://github.com/Sunzxyong/Recovery.git'
48 | bintrayUser = properties.getProperty("bintray.user")
49 | bintrayKey = properties.getProperty("bintray.apikey")
50 | }
51 | //./gradlew clean build bintrayUpload -PdryRun=false
52 |
--------------------------------------------------------------------------------
/recovery/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/Sunzxyong/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | -ignorewarnings
20 | -keepattributes Signature
21 | -keepattributes *Annotation*
22 | -keep @android.support.annotation.Keep class *
23 | -keepclassmembers class * {
24 | @android.support.annotation.Keep *;
25 | }
26 | -keepclasseswithmembers class * implements java.io.Serializable {*;}
27 | -keep class com.zxy.recovery.core.Recovery {*;}
--------------------------------------------------------------------------------
/recovery/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
17 |
18 |
19 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/callback/RecoveryActivityLifecycleCallback.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.callback;
2 |
3 | import android.app.Activity;
4 | import android.app.Application;
5 | import android.content.Intent;
6 | import android.os.Bundle;
7 | import android.view.View;
8 | import android.view.Window;
9 |
10 | import com.zxy.recovery.core.Recovery;
11 | import com.zxy.recovery.core.RecoveryActivity;
12 | import com.zxy.recovery.core.RecoveryStore;
13 | import com.zxy.recovery.tools.Reflect;
14 |
15 | /**
16 | * Created by zhengxiaoyong on 16/8/28.
17 | */
18 | public class RecoveryActivityLifecycleCallback implements Application.ActivityLifecycleCallbacks {
19 |
20 | @Override
21 | public void onActivityCreated(final Activity activity, Bundle savedInstanceState) {
22 | }
23 |
24 | @Override
25 | public void onActivityStarted(final Activity activity) {
26 | boolean isLegal = RecoveryStore.getInstance().verifyActivity(activity);
27 | if (!isLegal)
28 | return;
29 |
30 | if (activity.getIntent().getBooleanExtra(RecoveryActivity.RECOVERY_MODE_ACTIVE, false)) {
31 | Reflect.on(Recovery.class).method("registerRecoveryProxy").invoke(Recovery.getInstance());
32 | }
33 |
34 | if (RecoveryStore.getInstance().contains(activity))
35 | return;
36 |
37 | Window window = activity.getWindow();
38 | if (window != null) {
39 | View decorView = window.getDecorView();
40 | if (decorView == null)
41 | return;
42 | decorView.post(new Runnable() {
43 | @Override
44 | public void run() {
45 | RecoveryStore.getInstance().putActivity(activity);
46 | Object o = activity.getIntent().clone();
47 | RecoveryStore.getInstance().setIntent((Intent) o);
48 | }
49 | });
50 | }
51 |
52 | }
53 |
54 | @Override
55 | public void onActivityResumed(Activity activity) {
56 | }
57 |
58 | @Override
59 | public void onActivityPaused(Activity activity) {
60 | }
61 |
62 | @Override
63 | public void onActivityStopped(Activity activity) {
64 | }
65 |
66 | @Override
67 | public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
68 |
69 | }
70 |
71 | @Override
72 | public void onActivityDestroyed(Activity activity) {
73 | RecoveryStore.getInstance().removeActivity(activity);
74 | }
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/callback/RecoveryCallback.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.callback;
2 |
3 | /**
4 | * Created by zhengxiaoyong on 16/8/29.
5 | */
6 | public interface RecoveryCallback {
7 |
8 | void stackTrace(String stackTrace);
9 |
10 | void cause(String cause);
11 |
12 | void exception(String throwExceptionType, String throwClassName, String throwMethodName, int throwLineNumber);
13 |
14 | void throwable(Throwable throwable);
15 | }
16 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/core/ActivityManagerDelegate.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.core;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.text.TextUtils;
6 |
7 | import com.zxy.recovery.tools.RecoveryLog;
8 | import com.zxy.recovery.tools.RecoveryUtil;
9 |
10 | import java.lang.reflect.InvocationHandler;
11 | import java.lang.reflect.Method;
12 |
13 | /**
14 | * Created by zhengxiaoyong on 16/8/30.
15 | */
16 | class ActivityManagerDelegate implements InvocationHandler {
17 |
18 | private Object mBaseActivityManagerProxy;
19 |
20 | ActivityManagerDelegate(Object o) {
21 | this.mBaseActivityManagerProxy = o;
22 | }
23 |
24 | @Override
25 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
26 | String methodName = method.getName();
27 | switch (methodName) {
28 | case "finishActivity":
29 | // case "finishActivityAffinity":
30 | Class extends Activity> clazz = Recovery.getInstance().getMainPageClass();
31 | if (clazz == null)
32 | break;
33 | int count = ActivityStackCompat.getActivityCount(Recovery.getInstance().getContext());
34 | String baseActivityName = ActivityStackCompat.getBaseActivityName(Recovery.getInstance().getContext());
35 | if (TextUtils.isEmpty(baseActivityName))
36 | break;
37 | RecoveryLog.e("currentActivityCount: " + count);
38 | RecoveryLog.e("baseActivityName: " + baseActivityName);
39 | if (count == 1 && !clazz.getName().equals(baseActivityName)) {
40 | Intent intent = new Intent(Recovery.getInstance().getContext(), clazz);
41 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
42 | if (RecoveryUtil.isIntentAvailable(Recovery.getInstance().getContext(), intent))
43 | Recovery.getInstance().getContext().startActivity(intent);
44 | }
45 | break;
46 | default:
47 | break;
48 |
49 | }
50 |
51 | return method.invoke(mBaseActivityManagerProxy, args);
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/core/ActivityStackCompat.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.core;
2 |
3 | import android.app.ActivityManager;
4 | import android.content.ComponentName;
5 | import android.content.Context;
6 | import android.os.Build;
7 |
8 | import java.util.List;
9 |
10 | /**
11 | * Created by zhengxiaoyong on 16/8/30.
12 | */
13 | class ActivityStackCompat {
14 |
15 | private static ActivityManager.AppTask getTopTaskAfterL(Context context) {
16 | ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
17 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
18 | return activityManager.getAppTasks().get(0);
19 | return null;
20 | }
21 |
22 | private static ActivityManager.RunningTaskInfo getTopTaskBeforeL(Context context) {
23 | ActivityManager activityManager = (ActivityManager) context
24 | .getSystemService(Context.ACTIVITY_SERVICE);
25 | List tasks = null;
26 | try {
27 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
28 | tasks = activityManager.getRunningTasks(1);
29 | } catch (Exception e) {
30 | return null;
31 | }
32 | if (tasks == null || tasks.size() == 0)
33 | return null;
34 | return tasks.get(0);
35 | }
36 |
37 | /**
38 | * @param context Context.
39 | * @return Number of activities in this task.
40 | */
41 | public static int getActivityCount(Context context) {
42 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
43 | ActivityManager.AppTask appTask = getTopTaskAfterL(context);
44 | if (appTask == null)
45 | return 0;
46 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
47 | return appTask.getTaskInfo().numActivities;
48 | } else {
49 | //or mActivities
50 | return RecoveryStore.getInstance().getRunningActivityCount();
51 | }
52 | } else {
53 | ActivityManager.RunningTaskInfo taskInfo = getTopTaskBeforeL(context);
54 | if (taskInfo == null)
55 | return 0;
56 | return taskInfo.numActivities;
57 | }
58 | }
59 |
60 | public static String getBaseActivityName(Context context) {
61 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
62 | ActivityManager.AppTask appTask = getTopTaskAfterL(context);
63 | if (appTask == null)
64 | return null;
65 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
66 | return appTask.getTaskInfo().baseActivity.getClassName();
67 | } else {
68 | ComponentName componentName = RecoveryStore.getInstance().getBaseActivity();
69 | return componentName == null ? null : componentName.getClassName();
70 | }
71 | } else {
72 | ActivityManager.RunningTaskInfo taskInfo = getTopTaskBeforeL(context);
73 | if (taskInfo == null)
74 | return null;
75 | return taskInfo.baseActivity.getClassName();
76 | }
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/core/ApplicationLoader.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.core;
2 |
3 | import android.app.Application;
4 |
5 | import java.lang.reflect.Method;
6 |
7 | /**
8 | * Created by zhengxiaoyong on 2017/5/23.
9 | */
10 | public class ApplicationLoader {
11 |
12 | private static Application sApplication;
13 |
14 | public static Application get() {
15 | return sApplication != null ? sApplication : getApplication();
16 | }
17 |
18 | private static Application getApplication() {
19 | Application application = null;
20 | Method method;
21 | try {
22 | method = Class.forName("android.app.AppGlobals").getDeclaredMethod("getInitialApplication");
23 | method.setAccessible(true);
24 | application = (Application) method.invoke(null);
25 | } catch (Exception e) {
26 | try {
27 | method = Class.forName("android.app.ActivityThread").getDeclaredMethod("currentApplication");
28 | method.setAccessible(true);
29 | application = (Application) method.invoke(null);
30 | } catch (Exception ex) {
31 | ex.printStackTrace();
32 | }
33 | }
34 | return application;
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/core/CrashData.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.core;
2 |
3 | import java.io.Serializable;
4 |
5 | /**
6 | * Created by zhengxiaoyong on 16/8/30.
7 | */
8 | public class CrashData implements Serializable {
9 |
10 | public long crashTime;
11 |
12 | public int crashCount;
13 |
14 | public boolean shouldRestart;
15 |
16 | private CrashData() {
17 | }
18 |
19 | public static CrashData newInstance() {
20 | return new CrashData();
21 | }
22 |
23 | public CrashData time(long time) {
24 | this.crashTime = time;
25 | return this;
26 | }
27 |
28 | public CrashData count(int count) {
29 | this.crashCount = count;
30 | return this;
31 | }
32 |
33 | public CrashData restart(boolean restart) {
34 | this.shouldRestart = restart;
35 | return this;
36 | }
37 |
38 | @Override
39 | public String toString() {
40 | return "CrashData{" +
41 | "crashCount=" + crashCount +
42 | ", crashTime=" + crashTime +
43 | ", shouldRestart=" + shouldRestart +
44 | '}';
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/core/Recovery.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.core;
2 |
3 | import android.app.Activity;
4 | import android.app.Application;
5 | import android.content.Context;
6 | import android.os.Build;
7 | import android.support.annotation.Keep;
8 |
9 | import com.zxy.recovery.callback.RecoveryActivityLifecycleCallback;
10 | import com.zxy.recovery.callback.RecoveryCallback;
11 | import com.zxy.recovery.exception.RecoveryException;
12 | import com.zxy.recovery.tools.RecoveryLog;
13 | import com.zxy.recovery.tools.RecoveryUtil;
14 |
15 | import java.util.ArrayList;
16 | import java.util.Arrays;
17 | import java.util.List;
18 |
19 | /**
20 | * Created by zhengxiaoyong on 16/8/26.
21 | */
22 | public class Recovery {
23 |
24 | private volatile static Recovery sInstance;
25 |
26 | private static final Object LOCK = new Object();
27 |
28 | private Context mContext;
29 |
30 | private boolean isDebug = false;
31 |
32 | /**
33 | * The default to restore the stack.
34 | */
35 | private boolean isRecoverStack = true;
36 |
37 | /**
38 | * The default is not restore the background process.
39 | */
40 | private boolean isRecoverInBackground = false;
41 |
42 | private Class extends Activity> mMainPageClass;
43 |
44 | private RecoveryCallback mCallback;
45 |
46 | private boolean isSilentEnabled = false;
47 |
48 | private SilentMode mSilentMode = SilentMode.RECOVER_ACTIVITY_STACK;
49 |
50 | private List> mSkipActivities = new ArrayList<>();
51 |
52 | /**
53 | * Whether to enter recovery mode.
54 | */
55 | private boolean isRecoverEnabled = true;
56 |
57 | private Recovery() {
58 | }
59 |
60 | public static Recovery getInstance() {
61 | if (sInstance == null) {
62 | synchronized (LOCK) {
63 | if (sInstance == null) {
64 | sInstance = new Recovery();
65 | }
66 | }
67 | }
68 | return sInstance;
69 | }
70 |
71 | public void init(Context context) {
72 | if (context == null)
73 | throw new RecoveryException("Context can not be null!");
74 | if (!(context instanceof Application))
75 | context = context.getApplicationContext();
76 | mContext = context;
77 | if (!RecoveryUtil.isMainProcess(context))
78 | return;
79 | registerRecoveryHandler();
80 | registerRecoveryLifecycleCallback();
81 | }
82 |
83 | public Recovery debug(boolean isDebug) {
84 | this.isDebug = isDebug;
85 | return this;
86 | }
87 |
88 | public Recovery recoverStack(boolean isRecoverStack) {
89 | this.isRecoverStack = isRecoverStack;
90 | return this;
91 | }
92 |
93 | public Recovery recoverInBackground(boolean isRecoverInBackground) {
94 | this.isRecoverInBackground = isRecoverInBackground;
95 | return this;
96 | }
97 |
98 | public Recovery mainPage(Class extends Activity> clazz) {
99 | this.mMainPageClass = clazz;
100 | return this;
101 | }
102 |
103 | public Recovery callback(RecoveryCallback callback) {
104 | this.mCallback = callback;
105 | return this;
106 | }
107 |
108 | public Recovery silent(boolean enabled, SilentMode mode) {
109 | this.isSilentEnabled = enabled;
110 | this.mSilentMode = mode == null ? SilentMode.RECOVER_ACTIVITY_STACK : mode;
111 | return this;
112 | }
113 |
114 | @SafeVarargs
115 | public final Recovery skip(Class extends Activity>... activities) {
116 | if (activities == null)
117 | return this;
118 | mSkipActivities.addAll(Arrays.asList(activities));
119 | return this;
120 | }
121 |
122 | public Recovery recoverEnabled(boolean enabled) {
123 | this.isRecoverEnabled = enabled;
124 | return this;
125 | }
126 |
127 | private void registerRecoveryHandler() {
128 | RecoveryHandler.newInstance(Thread.getDefaultUncaughtExceptionHandler()).setCallback(mCallback).register();
129 | }
130 |
131 | private void registerRecoveryLifecycleCallback() {
132 | ((Application) getContext()).registerActivityLifecycleCallbacks(new RecoveryActivityLifecycleCallback());
133 | }
134 |
135 | @Keep
136 | private void registerRecoveryProxy() {
137 | //OS version in the 5.0 ~ 6.0 don`t register agent
138 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
139 | return;
140 | if (mMainPageClass == null)
141 | return;
142 | if (!RecoveryUtil.isMainProcess(RecoveryUtil.checkNotNull(getContext(), "The context is not initialized")))
143 | return;
144 | new Thread(new Runnable() {
145 | @Override
146 | public void run() {
147 | while (true) {
148 | boolean isSuccess = RecoveryComponentHook.hookActivityManagerProxy();
149 | RecoveryLog.e("hook is success:" + isSuccess);
150 | if (isSuccess)
151 | break;
152 | }
153 | }
154 | }).start();
155 | }
156 |
157 | public Context getContext() {
158 | if (mContext == null)
159 | mContext = ApplicationLoader.get();
160 | return RecoveryUtil.checkNotNull(mContext, "The context is not initialized");
161 | }
162 |
163 | public boolean isDebug() {
164 | return isDebug;
165 | }
166 |
167 | boolean isRecoverInBackground() {
168 | return isRecoverInBackground;
169 | }
170 |
171 | boolean isRecoverStack() {
172 | return isRecoverStack;
173 | }
174 |
175 | boolean isRecoverEnabled() {
176 | return isRecoverEnabled;
177 | }
178 |
179 | Class extends Activity> getMainPageClass() {
180 | return mMainPageClass;
181 | }
182 |
183 | boolean isSilentEnabled() {
184 | return isSilentEnabled;
185 | }
186 |
187 | SilentMode getSilentMode() {
188 | return mSilentMode;
189 | }
190 |
191 | public List> getSkipActivities() {
192 | return mSkipActivities;
193 | }
194 |
195 | public enum SilentMode {
196 | RESTART(1),
197 | RECOVER_ACTIVITY_STACK(2),
198 | RECOVER_TOP_ACTIVITY(3),
199 | RESTART_AND_CLEAR(4);
200 |
201 | int value;
202 |
203 | SilentMode(int value) {
204 | this.value = value;
205 | }
206 |
207 | public int getValue() {
208 | return value;
209 | }
210 |
211 | public static SilentMode getMode(int value) {
212 | switch (value) {
213 | case 1:
214 | return RESTART;
215 | case 2:
216 | return RECOVER_ACTIVITY_STACK;
217 | case 3:
218 | return RECOVER_TOP_ACTIVITY;
219 | case 4:
220 | return RESTART_AND_CLEAR;
221 | default:
222 | return RECOVER_ACTIVITY_STACK;
223 | }
224 | }
225 | }
226 | }
227 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/core/RecoveryActivity.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.core;
2 |
3 | import android.content.DialogInterface;
4 | import android.content.Intent;
5 | import android.os.Build;
6 | import android.os.Bundle;
7 | import android.support.v7.app.AlertDialog;
8 | import android.support.v7.app.AppCompatActivity;
9 | import android.support.v7.widget.Toolbar;
10 | import android.view.KeyEvent;
11 | import android.view.Menu;
12 | import android.view.MenuItem;
13 | import android.view.View;
14 | import android.widget.Button;
15 | import android.widget.ImageButton;
16 | import android.widget.ScrollView;
17 | import android.widget.TextView;
18 | import android.widget.Toast;
19 |
20 | import com.zxy.recovery.R;
21 | import com.zxy.recovery.tools.RecoverySharedPrefsUtil;
22 | import com.zxy.recovery.tools.RecoveryUtil;
23 | import com.zxy.recovery.tools.Reflect;
24 |
25 | import java.io.File;
26 | import java.io.FileWriter;
27 | import java.io.IOException;
28 | import java.util.ArrayList;
29 | import java.util.Date;
30 |
31 | /**
32 | * Created by zhengxiaoyong on 16/8/26.
33 | */
34 | public final class RecoveryActivity extends AppCompatActivity {
35 |
36 | public static final String RECOVERY_MODE_ACTIVE = "recovery_mode_active";
37 |
38 | private static final String DEFAULT_CRASH_FILE_DIR_NAME = "recovery_crash";
39 |
40 | private boolean isDebugMode = false;
41 |
42 | private boolean isDebugModeActive = false;
43 |
44 | private RecoveryStore.ExceptionData mExceptionData;
45 |
46 | private Toolbar mToolbar;
47 |
48 | private String mStackTrace;
49 |
50 | private String mCause;
51 |
52 | private Button mRecoverBtn;
53 |
54 | private Button mRestartBtn;
55 |
56 | private Button mRestartClearBtn;
57 |
58 | private View mMainLayout;
59 |
60 | private View mDebugLayout;
61 |
62 | private TextView mExceptionTypeTv;
63 |
64 | private TextView mClassNameTv;
65 |
66 | private TextView mMethodNameTv;
67 |
68 | private TextView mLineNumberTv;
69 |
70 | private TextView mStackTraceTv;
71 |
72 | private TextView mCauseTv;
73 |
74 | private TextView mCrashTipsTv;
75 |
76 | private ScrollView mScrollView;
77 |
78 | @Override
79 | protected void onCreate(Bundle savedInstanceState) {
80 | super.onCreate(savedInstanceState);
81 | setContentView(R.layout.recovery_activity_recover);
82 | setupToolbar();
83 | initView();
84 | initData();
85 | setupEvent();
86 | }
87 |
88 | private void setupToolbar() {
89 | mToolbar = (Toolbar) findViewById(R.id.toolbar);
90 | setSupportActionBar(mToolbar);
91 | if (getSupportActionBar() != null)
92 | getSupportActionBar().setDisplayShowTitleEnabled(false);
93 | mToolbar.setTitle(RecoveryUtil.getAppName(this));
94 | mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
95 | @Override
96 | public void onClick(View v) {
97 | isDebugModeActive = false;
98 | showMainView();
99 | setDisplayHomeAsUpEnabled(false);
100 | }
101 | });
102 | }
103 |
104 | @Override
105 | public boolean onCreateOptionsMenu(Menu menu) {
106 | if (!isDebugMode)
107 | return false;
108 | if (isDebugModeActive) {
109 | getMenuInflater().inflate(R.menu.recovery_menu_sub, menu);
110 | return true;
111 | }
112 | getMenuInflater().inflate(R.menu.recovery_menu, menu);
113 | return true;
114 | }
115 |
116 | @Override
117 | public boolean onOptionsItemSelected(MenuItem item) {
118 | int id = item.getItemId();
119 | if (id == R.id.action_debug) {
120 | isDebugModeActive = true;
121 | showDebugView();
122 | setDisplayHomeAsUpEnabled(true);
123 | } else if (id == R.id.action_save) {
124 | boolean isSuccess = saveCrashData();
125 | Toast.makeText(this, isSuccess ? "Save success!" : "Save failed!", Toast.LENGTH_SHORT).show();
126 | }
127 | return super.onOptionsItemSelected(item);
128 | }
129 |
130 | private void initView() {
131 | mMainLayout = findViewById(R.id.recovery_main_layout);
132 | mDebugLayout = findViewById(R.id.recovery_debug_layout);
133 | mRecoverBtn = (Button) findViewById(R.id.btn_recover);
134 | mRestartBtn = (Button) findViewById(R.id.btn_restart);
135 | mRestartClearBtn = (Button) findViewById(R.id.btn_restart_clear);
136 | mExceptionTypeTv = (TextView) findViewById(R.id.tv_type);
137 | mClassNameTv = (TextView) findViewById(R.id.tv_class_name);
138 | mMethodNameTv = (TextView) findViewById(R.id.tv_method_name);
139 | mLineNumberTv = (TextView) findViewById(R.id.tv_line_number);
140 | mStackTraceTv = (TextView) findViewById(R.id.tv_stack_trace);
141 | mCauseTv = (TextView) findViewById(R.id.tv_cause);
142 | mCrashTipsTv = (TextView) findViewById(R.id.tv_crash_tips);
143 | mScrollView = (ScrollView) findViewById(R.id.scrollView);
144 |
145 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
146 | mScrollView.setPadding(0, RecoveryUtil.dp2px(getApplication(), 16), 0, 0);
147 | }
148 | }
149 |
150 | private void initData() {
151 | isDebugMode = isDebugMode();
152 | if (isDebugMode)
153 | invalidateOptionsMenu();
154 | mExceptionData = getExceptionData();
155 | mCause = getCause();
156 | mStackTrace = getStackTrace();
157 | }
158 |
159 | private void setupEvent() {
160 | mRecoverBtn.setOnClickListener(new View.OnClickListener() {
161 | @Override
162 | public void onClick(View v) {
163 | boolean restart = RecoverySharedPrefsUtil.shouldRestartApp();
164 | if (restart) {
165 | RecoverySharedPrefsUtil.clear();
166 | restart();
167 | return;
168 | }
169 | if (isRecoverStack()) {
170 | recoverActivityStack();
171 | } else {
172 | recoverTopActivity();
173 | }
174 | }
175 | });
176 |
177 | mRestartBtn.setOnClickListener(new View.OnClickListener() {
178 | @Override
179 | public void onClick(View v) {
180 | boolean restart = RecoverySharedPrefsUtil.shouldRestartApp();
181 | if (restart)
182 | RecoverySharedPrefsUtil.clear();
183 | restart();
184 | }
185 | });
186 |
187 | mRestartClearBtn.setOnClickListener(new View.OnClickListener() {
188 | @Override
189 | public void onClick(View v) {
190 | AlertDialog dialog = new AlertDialog.Builder(RecoveryActivity.this)
191 | .setTitle(getResources().getString(R.string.recovery_dialog_tips))
192 | .setMessage(getResources().getString(R.string.recovery_dialog_tips_msg))
193 | .setPositiveButton(getResources().getString(R.string.recovery_dialog_sure), new DialogInterface.OnClickListener() {
194 | @Override
195 | public void onClick(DialogInterface dialog, int which) {
196 | if (dialog != null)
197 | dialog.dismiss();
198 | RecoveryUtil.clearApplicationData();
199 | restart();
200 | }
201 | }).setNegativeButton(getResources().getString(R.string.recovery_dialog_cancel), new DialogInterface.OnClickListener() {
202 | @Override
203 | public void onClick(DialogInterface dialog, int which) {
204 | if (dialog != null)
205 | dialog.dismiss();
206 | }
207 | }).create();
208 | dialog.setCanceledOnTouchOutside(false);
209 | dialog.show();
210 | }
211 | });
212 |
213 | mCrashTipsTv.setText(String.format(getResources().getString(R.string.recovery_crash_tips_msg), RecoveryUtil.getAppName(this)));
214 |
215 | if (mExceptionData != null) {
216 | String type = mExceptionData.type == null ? "" : mExceptionData.type;
217 | String name = mExceptionData.className == null ? "" : mExceptionData.className;
218 |
219 | mExceptionTypeTv.setText(String.format(getResources().getString(R.string.recovery_exception_type), type.substring(type.lastIndexOf('.') + 1)));
220 |
221 | mClassNameTv.setText(String.format(getResources().getString(R.string.recovery_class_name), name.substring(name.lastIndexOf('.') + 1)));
222 |
223 | mMethodNameTv.setText(String.format(getResources().getString(R.string.recovery_method_name), mExceptionData.methodName));
224 |
225 | mLineNumberTv.setText(String.format(getResources().getString(R.string.recovery_line_number), mExceptionData.lineNumber));
226 | }
227 | mCauseTv.setText(String.valueOf(mCause));
228 | mStackTraceTv.setText(String.valueOf(mStackTrace));
229 | }
230 |
231 | private boolean isDebugMode() {
232 | return getIntent().getBooleanExtra(RecoveryStore.IS_DEBUG, false);
233 | }
234 |
235 | private RecoveryStore.ExceptionData getExceptionData() {
236 | return getIntent().getParcelableExtra(RecoveryStore.EXCEPTION_DATA);
237 | }
238 |
239 | private String getCause() {
240 | return getIntent().getStringExtra(RecoveryStore.EXCEPTION_CAUSE);
241 | }
242 |
243 | private String getStackTrace() {
244 | return getIntent().getStringExtra(RecoveryStore.STACK_TRACE);
245 | }
246 |
247 | private void restart() {
248 | Intent launchIntent = getApplication().getPackageManager().getLaunchIntentForPackage(this.getPackageName());
249 | if (launchIntent != null) {
250 | launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
251 | startActivity(launchIntent);
252 | overridePendingTransition(0, 0);
253 | }
254 | finish();
255 | }
256 |
257 | private void recoverTopActivity() {
258 | Intent intent = getRecoveryIntent();
259 | if (intent != null && RecoveryUtil.isIntentAvailable(this, intent)) {
260 | intent.setExtrasClassLoader(getClassLoader());
261 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
262 | intent.putExtra(RECOVERY_MODE_ACTIVE, true);
263 | startActivity(intent);
264 | overridePendingTransition(0, 0);
265 | finish();
266 | return;
267 | }
268 | restart();
269 | }
270 |
271 | private boolean isRecoverStack() {
272 | boolean hasRecoverStack = getIntent().hasExtra(RecoveryStore.RECOVERY_STACK);
273 | return !hasRecoverStack || getIntent().getBooleanExtra(RecoveryStore.RECOVERY_STACK, true);
274 | }
275 |
276 | private void recoverActivityStack() {
277 | ArrayList intents = getRecoveryIntents();
278 | if (intents != null && !intents.isEmpty()) {
279 | ArrayList availableIntents = new ArrayList<>();
280 | for (Intent tmp : intents) {
281 | if (tmp != null && RecoveryUtil.isIntentAvailable(this, tmp)) {
282 | tmp.setExtrasClassLoader(getClassLoader());
283 | availableIntents.add(tmp);
284 | }
285 | }
286 | if (!availableIntents.isEmpty()) {
287 | availableIntents.get(0).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
288 | availableIntents.get(availableIntents.size() - 1).putExtra(RECOVERY_MODE_ACTIVE, true);
289 | startActivities(availableIntents.toArray(new Intent[availableIntents.size()]));
290 | overridePendingTransition(0, 0);
291 | finish();
292 | return;
293 | }
294 | }
295 | restart();
296 | }
297 |
298 | private Intent getRecoveryIntent() {
299 | boolean hasRecoverIntent = getIntent().hasExtra(RecoveryStore.RECOVERY_INTENT);
300 | if (!hasRecoverIntent)
301 | return null;
302 | return getIntent().getParcelableExtra(RecoveryStore.RECOVERY_INTENT);
303 | }
304 |
305 | private ArrayList getRecoveryIntents() {
306 | boolean hasRecoveryIntents = getIntent().hasExtra(RecoveryStore.RECOVERY_INTENTS);
307 | if (!hasRecoveryIntents)
308 | return null;
309 | return getIntent().getParcelableArrayListExtra(RecoveryStore.RECOVERY_INTENTS);
310 | }
311 |
312 | private boolean saveCrashData() {
313 | String date = RecoveryUtil.getDateFormat().format(new Date(System.currentTimeMillis()));
314 | File dir = new File(getExternalFilesDir(null) + File.separator + DEFAULT_CRASH_FILE_DIR_NAME);
315 | if (!dir.exists())
316 | dir.mkdirs();
317 | File file = new File(dir, String.valueOf(date) + ".txt");
318 | FileWriter writer = null;
319 | try {
320 | writer = new FileWriter(file);
321 | writer.write("\nException:\n" + (mExceptionData == null ? null : mExceptionData.toString()) + "\n\n");
322 | writer.write("Cause:\n" + mCause + "\n\n");
323 | writer.write("StackTrace:\n" + mStackTrace + "\n\n");
324 | writer.flush();
325 | } catch (IOException e) {
326 | e.printStackTrace();
327 | return false;
328 | } finally {
329 | if (writer != null)
330 | try {
331 | writer.close();
332 | } catch (IOException e) {
333 | e.printStackTrace();
334 | }
335 | }
336 | return true;
337 | }
338 |
339 | private void killProcess() {
340 | android.os.Process.killProcess(android.os.Process.myPid());
341 | System.exit(10);
342 | }
343 |
344 | private void setDisplayHomeAsUpEnabled(boolean enabled) {
345 | if (getSupportActionBar() != null)
346 | getSupportActionBar().setDisplayHomeAsUpEnabled(enabled);
347 | final ImageButton navButton = (ImageButton) Reflect.on(Toolbar.class).field("mNavButtonView").get(mToolbar);
348 | if (navButton != null) {
349 | if (enabled) {
350 | navButton.setVisibility(View.VISIBLE);
351 | } else {
352 | navButton.setVisibility(View.GONE);
353 | }
354 | }
355 | invalidateOptionsMenu();
356 | }
357 |
358 | private void showDebugView() {
359 | mMainLayout.setVisibility(View.GONE);
360 | mDebugLayout.setVisibility(View.VISIBLE);
361 | }
362 |
363 | private void showMainView() {
364 | mMainLayout.setVisibility(View.VISIBLE);
365 | mDebugLayout.setVisibility(View.GONE);
366 | }
367 |
368 | @Override
369 | public boolean onKeyDown(int keyCode, KeyEvent event) {
370 | if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && isDebugModeActive) {
371 | isDebugModeActive = false;
372 | showMainView();
373 | setDisplayHomeAsUpEnabled(false);
374 | return true;
375 | }
376 | return super.onKeyDown(keyCode, event);
377 | }
378 |
379 | @Override
380 | protected void onStop() {
381 | super.onStop();
382 | finish();
383 | }
384 |
385 | @Override
386 | public void finish() {
387 | super.finish();
388 | killProcess();
389 | }
390 |
391 | }
392 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/core/RecoveryComponentHook.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.core;
2 |
3 | import android.os.Build;
4 |
5 | import com.zxy.recovery.tools.RecoveryLog;
6 | import com.zxy.recovery.tools.Reflect;
7 |
8 | import java.lang.reflect.Proxy;
9 |
10 | /**
11 | * Created by zhengxiaoyong on 16/8/30.
12 | */
13 | final class RecoveryComponentHook {
14 |
15 | static boolean hookActivityManagerProxy() {
16 | Object gDefault;
17 | try {
18 | if (Build.VERSION.SDK_INT >= 26) {
19 | //IActivityManagerSingleton
20 | gDefault = Reflect.on(android.app.ActivityManager.class).field("IActivityManagerSingleton").get(null);
21 | } else {
22 | //Singleton
23 | gDefault = Reflect.on("android.app.ActivityManagerNative").field("gDefault").get(null);
24 | }
25 | if (gDefault == null)
26 | return false;
27 | Object currentActivityManagerProxy = Reflect.on("android.util.Singleton").field("mInstance").get(gDefault);
28 | if (currentActivityManagerProxy == null)
29 | return false;
30 | Object proxy;
31 | if (Build.VERSION.SDK_INT >= 26) {
32 | ActivityManagerDelegate delegate = new ActivityManagerDelegate(currentActivityManagerProxy);
33 | if (currentActivityManagerProxy.getClass().isInstance(delegate))
34 | return true;
35 | Class> amClass = Class.forName("android.app.IActivityManager");
36 | proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{amClass}, delegate);
37 | } else {
38 | ActivityManagerDelegate delegate = new ActivityManagerDelegate(currentActivityManagerProxy);
39 | if (currentActivityManagerProxy.getClass().isInstance(delegate))
40 | return true;
41 | Class>[] interfaces = Class.forName("android.app.ActivityManagerNative").getInterfaces();
42 | proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, delegate);
43 | }
44 | Reflect.on("android.util.Singleton").field("mInstance").set(gDefault, proxy);
45 | } catch (Throwable e) {
46 | e.printStackTrace();
47 | RecoveryLog.e(e.toString());
48 | }
49 | return true;
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/core/RecoveryHandler.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.core;
2 |
3 | import android.content.Intent;
4 | import android.text.TextUtils;
5 |
6 | import com.zxy.recovery.callback.RecoveryCallback;
7 | import com.zxy.recovery.tools.DefaultHandlerUtil;
8 | import com.zxy.recovery.tools.RecoverySharedPrefsUtil;
9 | import com.zxy.recovery.tools.RecoverySilentSharedPrefsUtil;
10 | import com.zxy.recovery.tools.RecoveryUtil;
11 |
12 | import java.io.PrintWriter;
13 | import java.io.StringWriter;
14 |
15 | /**
16 | * Created by zhengxiaoyong on 16/8/26.
17 | */
18 | final class RecoveryHandler implements Thread.UncaughtExceptionHandler {
19 |
20 | private Thread.UncaughtExceptionHandler mDefaultUncaughtExceptionHandler;
21 |
22 | private RecoveryCallback mCallback;
23 |
24 | private RecoveryStore.ExceptionData mExceptionData;
25 |
26 | private String mStackTrace;
27 |
28 | private String mCause;
29 |
30 | private RecoveryHandler(Thread.UncaughtExceptionHandler defHandler) {
31 | mDefaultUncaughtExceptionHandler = defHandler;
32 | }
33 |
34 | static RecoveryHandler newInstance(Thread.UncaughtExceptionHandler defHandler) {
35 | return new RecoveryHandler(defHandler);
36 | }
37 |
38 | @Override
39 | public synchronized void uncaughtException(Thread t, Throwable e) {
40 |
41 | if (Recovery.getInstance().isRecoverEnabled()) {
42 | if (Recovery.getInstance().isSilentEnabled()) {
43 | RecoverySilentSharedPrefsUtil.recordCrashData();
44 | } else {
45 | RecoverySharedPrefsUtil.recordCrashData();
46 | }
47 | }
48 |
49 | StringWriter sw = new StringWriter();
50 | PrintWriter pw = new PrintWriter(sw);
51 | e.printStackTrace(pw);
52 | pw.flush();
53 |
54 | String stackTrace = sw.toString();
55 | String cause = e.getMessage();
56 | Throwable rootTr = e;
57 | while (e.getCause() != null) {
58 | e = e.getCause();
59 | if (e.getStackTrace() != null && e.getStackTrace().length > 0)
60 | rootTr = e;
61 | String msg = e.getMessage();
62 | if (!TextUtils.isEmpty(msg))
63 | cause = msg;
64 | }
65 |
66 | String exceptionType = rootTr.getClass().getName();
67 |
68 | String throwClassName;
69 | String throwMethodName;
70 | int throwLineNumber;
71 |
72 | if (rootTr.getStackTrace().length > 0) {
73 | StackTraceElement trace = rootTr.getStackTrace()[0];
74 | throwClassName = trace.getClassName();
75 | throwMethodName = trace.getMethodName();
76 | throwLineNumber = trace.getLineNumber();
77 | } else {
78 | throwClassName = "unknown";
79 | throwMethodName = "unknown";
80 | throwLineNumber = 0;
81 | }
82 |
83 | mExceptionData = RecoveryStore.ExceptionData.newInstance()
84 | .type(exceptionType)
85 | .className(throwClassName)
86 | .methodName(throwMethodName)
87 | .lineNumber(throwLineNumber);
88 |
89 | mStackTrace = stackTrace;
90 | mCause = cause;
91 |
92 | if (mCallback != null) {
93 | mCallback.stackTrace(stackTrace);
94 | mCallback.cause(cause);
95 | mCallback.exception(exceptionType, throwClassName, throwMethodName, throwLineNumber);
96 | mCallback.throwable(e);
97 | }
98 |
99 | if (!DefaultHandlerUtil.isSystemDefaultUncaughtExceptionHandler(mDefaultUncaughtExceptionHandler)) {
100 | if (mDefaultUncaughtExceptionHandler == null) {
101 | killProcess();
102 | return;
103 | }
104 | recover();
105 | mDefaultUncaughtExceptionHandler.uncaughtException(t, e);
106 | } else {
107 | recover();
108 | killProcess();
109 | }
110 |
111 | }
112 |
113 | RecoveryHandler setCallback(RecoveryCallback callback) {
114 | mCallback = callback;
115 | return this;
116 | }
117 |
118 | private void recover() {
119 | if (!Recovery.getInstance().isRecoverEnabled())
120 | return;
121 |
122 | if (RecoveryUtil.isAppInBackground(Recovery.getInstance().getContext())
123 | && !Recovery.getInstance().isRecoverInBackground()) {
124 | killProcess();
125 | return;
126 | }
127 |
128 | if (Recovery.getInstance().isSilentEnabled()) {
129 | startRecoverService();
130 | } else {
131 | startRecoverActivity();
132 | }
133 | }
134 |
135 | private void startRecoverActivity() {
136 | Intent intent = new Intent();
137 | intent.setClass(Recovery.getInstance().getContext(), RecoveryActivity.class);
138 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
139 | if (RecoveryStore.getInstance().getIntent() != null)
140 | intent.putExtra(RecoveryStore.RECOVERY_INTENT, RecoveryStore.getInstance().getIntent());
141 | if (!RecoveryStore.getInstance().getIntents().isEmpty())
142 | intent.putParcelableArrayListExtra(RecoveryStore.RECOVERY_INTENTS, RecoveryStore.getInstance().getIntents());
143 | intent.putExtra(RecoveryStore.RECOVERY_STACK, Recovery.getInstance().isRecoverStack());
144 | intent.putExtra(RecoveryStore.IS_DEBUG, Recovery.getInstance().isDebug());
145 | if (mExceptionData != null)
146 | intent.putExtra(RecoveryStore.EXCEPTION_DATA, mExceptionData);
147 | intent.putExtra(RecoveryStore.STACK_TRACE, String.valueOf(mStackTrace));
148 | intent.putExtra(RecoveryStore.EXCEPTION_CAUSE, String.valueOf(mCause));
149 | Recovery.getInstance().getContext().startActivity(intent);
150 | }
151 |
152 | private void startRecoverService() {
153 | Intent intent = new Intent();
154 | intent.setClass(Recovery.getInstance().getContext(), RecoveryService.class);
155 | if (RecoveryStore.getInstance().getIntent() != null)
156 | intent.putExtra(RecoveryStore.RECOVERY_INTENT, RecoveryStore.getInstance().getIntent());
157 | if (!RecoveryStore.getInstance().getIntents().isEmpty())
158 | intent.putParcelableArrayListExtra(RecoveryStore.RECOVERY_INTENTS, RecoveryStore.getInstance().getIntents());
159 | intent.putExtra(RecoveryService.RECOVERY_SILENT_MODE_VALUE, Recovery.getInstance().getSilentMode().getValue());
160 | RecoveryService.start(Recovery.getInstance().getContext(), intent);
161 | }
162 |
163 | void register() {
164 | Thread.setDefaultUncaughtExceptionHandler(this);
165 | }
166 |
167 | private void killProcess() {
168 | android.os.Process.killProcess(android.os.Process.myPid());
169 | System.exit(10);
170 | }
171 |
172 | }
173 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/core/RecoveryService.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.core;
2 |
3 | import android.app.Notification;
4 | import android.app.NotificationChannel;
5 | import android.app.NotificationManager;
6 | import android.app.Service;
7 | import android.content.Context;
8 | import android.content.Intent;
9 | import android.os.Build;
10 | import android.os.IBinder;
11 |
12 | import com.zxy.recovery.tools.RecoverySilentSharedPrefsUtil;
13 | import com.zxy.recovery.tools.RecoveryUtil;
14 |
15 | import java.util.ArrayList;
16 |
17 | import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
18 | import static com.zxy.recovery.core.RecoveryActivity.RECOVERY_MODE_ACTIVE;
19 |
20 | /**
21 | * Created by zhengxiaoyong on 16/8/29.
22 | */
23 | public class RecoveryService extends Service {
24 |
25 | static final String RECOVERY_SILENT_MODE_VALUE = "recovery_silent_mode_value";
26 |
27 | public RecoveryService() {
28 | }
29 |
30 | @Override
31 | public IBinder onBind(Intent intent) {
32 | return null;
33 | }
34 |
35 | @Override
36 | public int onStartCommand(Intent intent, int flags, int startId) {
37 | if (Build.VERSION.SDK_INT >= 26) {
38 | try {
39 | NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
40 | NotificationChannel channel = new NotificationChannel("channel_recovery_1", "Recovery", NotificationManager.IMPORTANCE_HIGH);
41 | notificationManager.createNotificationChannel(channel);
42 | Notification notification = new Notification.Builder(getApplication(), "channel_recovery_1").build();
43 | startForeground(1024, notification);
44 | } catch (Throwable t) {
45 | //ignore.
46 | }
47 | }
48 |
49 | if (RecoverySilentSharedPrefsUtil.shouldClearAppNotRestart()) {
50 | //If restore failed twice within 30 seconds, will only delete data and not restored.
51 | RecoverySilentSharedPrefsUtil.clear();
52 | stopSelf();
53 | killProcess();
54 | }
55 |
56 | Recovery.SilentMode mode = getRecoverySilentMode(intent);
57 |
58 | if (mode == Recovery.SilentMode.RESTART) {
59 | restart();
60 | } else if (mode == Recovery.SilentMode.RECOVER_ACTIVITY_STACK) {
61 | recoverActivityStack(intent);
62 | } else if (mode == Recovery.SilentMode.RECOVER_TOP_ACTIVITY) {
63 | recoverTopActivity(intent);
64 | } else if (mode == Recovery.SilentMode.RESTART_AND_CLEAR) {
65 | restartAndClear();
66 | } else {
67 | stopSelf();
68 | }
69 | return Service.START_NOT_STICKY;
70 | }
71 |
72 | private void restartAndClear() {
73 | RecoveryUtil.clearApplicationData();
74 | restart();
75 | }
76 |
77 | private void recoverActivityStack(Intent o) {
78 | ArrayList intents = getRecoveryIntents(o);
79 | if (intents != null && !intents.isEmpty()) {
80 | ArrayList availableIntents = new ArrayList<>();
81 | for (Intent tmp : intents) {
82 | if (tmp != null && RecoveryUtil.isIntentAvailable(this, tmp)) {
83 | tmp.setExtrasClassLoader(getClassLoader());
84 | availableIntents.add(tmp);
85 | }
86 | }
87 | if (!availableIntents.isEmpty()) {
88 | availableIntents.get(0).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
89 | availableIntents.get(availableIntents.size() - 1).putExtra(RECOVERY_MODE_ACTIVE, true);
90 | startActivities(availableIntents.toArray(new Intent[availableIntents.size()]));
91 | stopSelf();
92 | return;
93 | }
94 | }
95 | restart();
96 | }
97 |
98 | private void recoverTopActivity(Intent o) {
99 | Intent intent = getRecoveryIntent(o);
100 | if (intent != null && RecoveryUtil.isIntentAvailable(this, intent)) {
101 | intent.setExtrasClassLoader(getClassLoader());
102 | intent.addFlags(FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
103 | intent.putExtra(RECOVERY_MODE_ACTIVE, true);
104 | startActivity(intent);
105 | stopSelf();
106 | return;
107 | }
108 | restart();
109 | }
110 |
111 | private Intent getRecoveryIntent(Intent intent) {
112 | boolean hasRecoverIntent = intent.hasExtra(RecoveryStore.RECOVERY_INTENT);
113 | if (!hasRecoverIntent)
114 | return null;
115 | return intent.getParcelableExtra(RecoveryStore.RECOVERY_INTENT);
116 | }
117 |
118 | private ArrayList getRecoveryIntents(Intent intent) {
119 | boolean hasRecoveryIntents = intent.hasExtra(RecoveryStore.RECOVERY_INTENTS);
120 | if (!hasRecoveryIntents)
121 | return null;
122 | return intent.getParcelableArrayListExtra(RecoveryStore.RECOVERY_INTENTS);
123 | }
124 |
125 | private Recovery.SilentMode getRecoverySilentMode(Intent intent) {
126 | int value = intent.getIntExtra(RECOVERY_SILENT_MODE_VALUE, -1);
127 | return Recovery.SilentMode.getMode(value);
128 | }
129 |
130 | private void restart() {
131 | Intent launchIntent = getApplication().getPackageManager().getLaunchIntentForPackage(this.getPackageName());
132 | if (launchIntent != null) {
133 | launchIntent.addFlags(FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
134 | startActivity(launchIntent);
135 | }
136 | stopSelf();
137 | }
138 |
139 | private void killProcess() {
140 | android.os.Process.killProcess(android.os.Process.myPid());
141 | System.exit(10);
142 | }
143 |
144 | @Override
145 | public void onDestroy() {
146 | super.onDestroy();
147 | killProcess();
148 | }
149 |
150 | public static void start(Context context, Intent intent) {
151 | try {
152 | if (Build.VERSION.SDK_INT >= 26) {
153 | context.startForegroundService(intent);
154 | } else {
155 | context.startService(intent);
156 | }
157 | } catch (Throwable t) {
158 | //ignore.
159 | }
160 | }
161 | }
162 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/core/RecoveryStore.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.core;
2 |
3 | import android.app.Activity;
4 | import android.content.ComponentName;
5 | import android.content.Intent;
6 | import android.os.Parcel;
7 | import android.os.Parcelable;
8 |
9 | import java.lang.ref.WeakReference;
10 | import java.util.ArrayList;
11 | import java.util.List;
12 | import java.util.concurrent.CopyOnWriteArrayList;
13 | import java.util.concurrent.atomic.AtomicInteger;
14 |
15 | /**
16 | * Created by zhengxiaoyong on 16/8/28.
17 | */
18 | public final class RecoveryStore {
19 |
20 | static final String RECOVERY_INTENT = "recovery_intent";
21 |
22 | static final String RECOVERY_INTENTS = "recovery_intents";
23 |
24 | static final String RECOVERY_STACK = "recovery_stack";
25 |
26 | static final String IS_DEBUG = "recovery_is_debug";
27 |
28 | static final String STACK_TRACE = "recovery_stack_trace";
29 |
30 | static final String EXCEPTION_DATA = "recovery_exception_data";
31 |
32 | static final String EXCEPTION_CAUSE = "recovery_exception_cause";
33 |
34 | private volatile static RecoveryStore sInstance;
35 |
36 | private static final Object LOCK = new Object();
37 |
38 | private List> mRunningActivities;
39 |
40 | private Intent mIntent;
41 |
42 | private RecoveryStore() {
43 | mRunningActivities = new CopyOnWriteArrayList<>();
44 | }
45 |
46 | public static RecoveryStore getInstance() {
47 | if (sInstance == null) {
48 | synchronized (LOCK) {
49 | if (sInstance == null) {
50 | sInstance = new RecoveryStore();
51 | }
52 | }
53 | }
54 | return sInstance;
55 | }
56 |
57 | public Intent getIntent() {
58 | return mIntent;
59 | }
60 |
61 | public synchronized void setIntent(Intent intent) {
62 | mIntent = intent;
63 | }
64 |
65 | public boolean verifyActivity(Activity activity) {
66 | return activity != null && !Recovery.getInstance().getSkipActivities().contains(activity.getClass()) && !RecoveryActivity.class.isInstance(activity);
67 | }
68 |
69 | public List> getRunningActivities() {
70 | return mRunningActivities;
71 | }
72 |
73 | public void putActivity(Activity activity) {
74 | WeakReference weakReference = new WeakReference<>(activity);
75 | mRunningActivities.add(weakReference);
76 | }
77 |
78 | public boolean contains(Activity activity) {
79 | if (activity == null)
80 | return false;
81 | int size = mRunningActivities.size();
82 | for (int i = 0; i < size; i++) {
83 | WeakReference refer = mRunningActivities.get(i);
84 | if (refer == null)
85 | continue;
86 | Activity tmp = refer.get();
87 | if (tmp == null)
88 | continue;
89 | if (activity == tmp)
90 | return true;
91 | }
92 | return false;
93 | }
94 |
95 | public void removeActivity(Activity activity) {
96 | for (WeakReference activityWeakReference : mRunningActivities) {
97 | if (activityWeakReference == null)
98 | continue;
99 | Activity tmpActivity = activityWeakReference.get();
100 | if (tmpActivity == null)
101 | continue;
102 | if (tmpActivity == activity) {
103 | mRunningActivities.remove(activityWeakReference);
104 | break;
105 | }
106 | }
107 | }
108 |
109 | int getRunningActivityCount() {
110 | AtomicInteger count = new AtomicInteger(0);
111 | for (WeakReference activityWeakReference : mRunningActivities) {
112 | if (activityWeakReference == null)
113 | continue;
114 | Activity activity = activityWeakReference.get();
115 | if (activity == null)
116 | continue;
117 | count.set(count.incrementAndGet());
118 | }
119 | return count.get();
120 | }
121 |
122 | ComponentName getBaseActivity() {
123 | for (WeakReference activityWeakReference : mRunningActivities) {
124 | if (activityWeakReference == null)
125 | continue;
126 | Activity tmpActivity = activityWeakReference.get();
127 | if (tmpActivity == null)
128 | continue;
129 | return tmpActivity.getComponentName();
130 | }
131 | return null;
132 | }
133 |
134 | ArrayList getIntents() {
135 | ArrayList intentList = new ArrayList<>();
136 | for (WeakReference activityWeakReference : mRunningActivities) {
137 | if (activityWeakReference == null)
138 | continue;
139 | Activity tmpActivity = activityWeakReference.get();
140 | if (tmpActivity == null)
141 | continue;
142 | intentList.add((Intent) tmpActivity.getIntent().clone());
143 | }
144 | return intentList;
145 | }
146 |
147 | static final class ExceptionData implements Parcelable {
148 | String type;
149 | String className;
150 | String methodName;
151 | int lineNumber;
152 |
153 | @Override
154 | public int describeContents() {
155 | return 0;
156 | }
157 |
158 | @Override
159 | public void writeToParcel(Parcel dest, int flags) {
160 | dest.writeString(this.type);
161 | dest.writeString(this.className);
162 | dest.writeString(this.methodName);
163 | dest.writeInt(this.lineNumber);
164 | }
165 |
166 | ExceptionData() {
167 | }
168 |
169 | public static ExceptionData newInstance() {
170 | return new ExceptionData();
171 | }
172 |
173 | public ExceptionData type(String type) {
174 | this.type = type;
175 | return this;
176 | }
177 |
178 | public ExceptionData className(String className) {
179 | this.className = className;
180 | return this;
181 | }
182 |
183 | public ExceptionData methodName(String methodName) {
184 | this.methodName = methodName;
185 | return this;
186 | }
187 |
188 | public ExceptionData lineNumber(int lineNumber) {
189 | this.lineNumber = lineNumber;
190 | return this;
191 | }
192 |
193 | protected ExceptionData(Parcel in) {
194 | this.type = in.readString();
195 | this.className = in.readString();
196 | this.methodName = in.readString();
197 | this.lineNumber = in.readInt();
198 | }
199 |
200 | public static final Creator CREATOR = new Creator() {
201 | @Override
202 | public ExceptionData createFromParcel(Parcel source) {
203 | return new ExceptionData(source);
204 | }
205 |
206 | @Override
207 | public ExceptionData[] newArray(int size) {
208 | return new ExceptionData[size];
209 | }
210 | };
211 |
212 | @Override
213 | public String toString() {
214 | return "ExceptionData{" +
215 | "className='" + className + '\'' +
216 | ", type='" + type + '\'' +
217 | ", methodName='" + methodName + '\'' +
218 | ", lineNumber=" + lineNumber +
219 | '}';
220 | }
221 | }
222 | }
223 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/exception/RecoveryException.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.exception;
2 |
3 | /**
4 | * Created by zhengxiaoyong on 16/8/28.
5 | */
6 | public class RecoveryException extends RuntimeException {
7 | public RecoveryException(String message) {
8 | super(message);
9 | }
10 |
11 | public RecoveryException(String message, Throwable cause) {
12 | super(message, cause);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/exception/ReflectException.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.exception;
2 |
3 | /**
4 | * Created by zhengxiaoyong on 16/8/28.
5 | */
6 | public class ReflectException extends RuntimeException {
7 | public ReflectException() {
8 | super();
9 | }
10 |
11 | public ReflectException(String detailMessage) {
12 | super(detailMessage);
13 | }
14 |
15 | public ReflectException(String detailMessage, Throwable throwable) {
16 | super(detailMessage, throwable);
17 | }
18 |
19 | public ReflectException(Throwable throwable) {
20 | super(throwable);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/tools/DefaultHandlerUtil.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.tools;
2 |
3 |
4 | import android.os.Build;
5 |
6 | import com.zxy.recovery.exception.RecoveryException;
7 |
8 | /**
9 | * Created by zgxiaoyong on 16/8/28.
10 | */
11 | public class DefaultHandlerUtil {
12 |
13 | private DefaultHandlerUtil() {
14 | throw new RecoveryException("Stub!");
15 | }
16 |
17 | private static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() {
18 | try {
19 | Class> clazz;
20 | if (Build.VERSION.SDK_INT >= 26) {
21 | clazz = Class.forName("com.android.internal.os.RuntimeInit$KillApplicationHandler");
22 | } else {
23 | clazz = Class.forName("com.android.internal.os.RuntimeInit$UncaughtHandler");
24 | }
25 |
26 | Object object = clazz.getDeclaredConstructor().newInstance();
27 | return (Thread.UncaughtExceptionHandler) object;
28 | } catch (Throwable e) {
29 | e.printStackTrace();
30 | }
31 | return null;
32 | }
33 |
34 | public static boolean isSystemDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler) {
35 | if (handler == null)
36 | return false;
37 | Thread.UncaughtExceptionHandler defHandler = getDefaultUncaughtExceptionHandler();
38 | return defHandler != null && defHandler.getClass().isInstance(handler);
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/tools/RecoveryLog.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.tools;
2 |
3 | import android.util.Log;
4 |
5 | import com.zxy.recovery.core.Recovery;
6 |
7 | /**
8 | * Created by zhengxiaoyong on 16/8/26.
9 | */
10 | public class RecoveryLog {
11 |
12 | private static final String TAG = "Recovery";
13 |
14 | public static void e(String message) {
15 | if (Recovery.getInstance().isDebug())
16 | Log.e(TAG, message);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/tools/RecoverySharedPrefsUtil.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.tools;
2 |
3 | import com.zxy.recovery.core.CrashData;
4 | import com.zxy.recovery.core.Recovery;
5 | import com.zxy.recovery.exception.RecoveryException;
6 |
7 | /**
8 | * Created by zhengxiaoyong on 16/8/27.
9 | */
10 | public class RecoverySharedPrefsUtil {
11 |
12 | private static final long DEFAULT_TIME_INTERVAL = 60 * 1000;
13 |
14 | private static final int DEFAULT_MAX_COUNT = 3;
15 |
16 | private static final String SHARED_PREFS_NAME = "recovery_info";
17 |
18 | private static final String CRASH_COUNT = "crash_count";
19 |
20 | private static final String CRASH_TIME = "crash_time";
21 |
22 | private static final String SHOULD_RESTART_APP = "should_restart_app";
23 |
24 | private RecoverySharedPrefsUtil() {
25 | throw new RecoveryException("Stub!");
26 | }
27 |
28 | public static void recordCrashData() {
29 | int count = 0;
30 | long time = 0L;
31 | boolean shouldRestart = false;
32 | try {
33 | count = Integer.parseInt(get(CRASH_COUNT, String.valueOf(0)));
34 | time = Long.parseLong(get(CRASH_TIME, String.valueOf(0L)));
35 | } catch (Exception e) {
36 | count = 0;
37 | time = 0L;
38 | RecoveryLog.e(e.getMessage());
39 | }
40 | count = Math.max(count, 0);
41 | time = Math.max(time, 0L);
42 |
43 | count += 1;
44 | time = time == 0L ? System.currentTimeMillis() : time;
45 |
46 | long interval = System.currentTimeMillis() - time;
47 | if (count >= DEFAULT_MAX_COUNT && interval <= DEFAULT_TIME_INTERVAL) {
48 | shouldRestart = true;
49 | count = 0;
50 | time = 0L;
51 | } else {
52 | if (count >= DEFAULT_MAX_COUNT || interval > DEFAULT_TIME_INTERVAL) {
53 | count = 1;
54 | time = System.currentTimeMillis();
55 | }
56 | }
57 | CrashData data = CrashData.newInstance()
58 | .count(count)
59 | .time(time)
60 | .restart(shouldRestart);
61 | RecoveryLog.e(data.toString());
62 | saveCrashData(data);
63 | }
64 |
65 | private static void saveCrashData(CrashData data) {
66 | if (data == null)
67 | return;
68 | SharedPreferencesCompat.newBuilder(Recovery.getInstance().getContext(), SHARED_PREFS_NAME)
69 | .put(CRASH_COUNT, String.valueOf(data.crashCount))
70 | .put(CRASH_TIME, String.valueOf(data.crashTime))
71 | .put(SHOULD_RESTART_APP, String.valueOf(data.shouldRestart))
72 | .apply();
73 | }
74 |
75 | public static boolean shouldRestartApp() {
76 | return Boolean.parseBoolean(get(SHOULD_RESTART_APP, String.valueOf(false)));
77 | }
78 |
79 | public static void clear() {
80 | SharedPreferencesCompat.clear(Recovery.getInstance().getContext(), SHARED_PREFS_NAME);
81 | }
82 |
83 | private static void put(String key, String value) {
84 | SharedPreferencesCompat.put(Recovery.getInstance().getContext(), SHARED_PREFS_NAME, key, value);
85 | }
86 |
87 | private static String get(String key, String defValue) {
88 | return SharedPreferencesCompat.get(Recovery.getInstance().getContext(), SHARED_PREFS_NAME, key, defValue);
89 | }
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/tools/RecoverySilentSharedPrefsUtil.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.tools;
2 |
3 | import com.zxy.recovery.core.CrashData;
4 | import com.zxy.recovery.core.Recovery;
5 | import com.zxy.recovery.exception.RecoveryException;
6 |
7 | /**
8 | * Created by zhengxiaoyong on 2016/9/29.
9 | */
10 | public class RecoverySilentSharedPrefsUtil {
11 |
12 | private static final long DEFAULT_TIME_INTERVAL = 30 * 1000;
13 |
14 | private static final int DEFAULT_MAX_COUNT = 2;
15 |
16 | private static final String SHARED_PREFS_NAME = "recovery_silent_info";
17 |
18 | private static final String CRASH_COUNT = "crash_count";
19 |
20 | private static final String CRASH_TIME = "crash_time";
21 |
22 | private static final String SHOULD_CLEAR_APP_AND_NOT_RESTART = "should_clear_app_and_not_restart";
23 |
24 | private RecoverySilentSharedPrefsUtil() {
25 | throw new RecoveryException("Stub!");
26 | }
27 |
28 | public static void recordCrashData() {
29 | int count = 0;
30 | long time = 0L;
31 | boolean shouldRestart = false;
32 | try {
33 | count = Integer.parseInt(get(CRASH_COUNT, String.valueOf(0)));
34 | time = Long.parseLong(get(CRASH_TIME, String.valueOf(0L)));
35 | } catch (Exception e) {
36 | count = 0;
37 | time = 0L;
38 | RecoveryLog.e(e.getMessage());
39 | }
40 | count = Math.max(count, 0);
41 | time = Math.max(time, 0L);
42 |
43 | count += 1;
44 | time = time == 0L ? System.currentTimeMillis() : time;
45 |
46 | long interval = System.currentTimeMillis() - time;
47 | if (count >= DEFAULT_MAX_COUNT && interval <= DEFAULT_TIME_INTERVAL) {
48 | shouldRestart = true;
49 | count = 0;
50 | time = 0L;
51 | } else {
52 | if (count >= DEFAULT_MAX_COUNT || interval > DEFAULT_TIME_INTERVAL) {
53 | count = 1;
54 | time = System.currentTimeMillis();
55 | }
56 | }
57 | CrashData data = CrashData.newInstance()
58 | .count(count)
59 | .time(time)
60 | .restart(shouldRestart);
61 | RecoveryLog.e(data.toString());
62 | saveCrashData(data);
63 | }
64 |
65 | private static void saveCrashData(CrashData data) {
66 | if (data == null)
67 | return;
68 | SharedPreferencesCompat.newBuilder(Recovery.getInstance().getContext(), SHARED_PREFS_NAME)
69 | .put(CRASH_COUNT, String.valueOf(data.crashCount))
70 | .put(CRASH_TIME, String.valueOf(data.crashTime))
71 | .put(SHOULD_CLEAR_APP_AND_NOT_RESTART, String.valueOf(data.shouldRestart))
72 | .apply();
73 | }
74 |
75 | public static boolean shouldClearAppNotRestart() {
76 | return Boolean.parseBoolean(get(SHOULD_CLEAR_APP_AND_NOT_RESTART, String.valueOf(false)));
77 | }
78 |
79 | public static void clear() {
80 | SharedPreferencesCompat.clear(Recovery.getInstance().getContext(), SHARED_PREFS_NAME);
81 | }
82 |
83 | private static void put(String key, String value) {
84 | SharedPreferencesCompat.put(Recovery.getInstance().getContext(), SHARED_PREFS_NAME, key, value);
85 | }
86 |
87 | private static String get(String key, String defValue) {
88 | return SharedPreferencesCompat.get(Recovery.getInstance().getContext(), SHARED_PREFS_NAME, key, defValue);
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/tools/RecoveryUtil.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.tools;
2 |
3 | import android.app.ActivityManager;
4 | import android.app.Application;
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.content.pm.ApplicationInfo;
8 | import android.content.pm.PackageManager;
9 | import android.content.pm.ResolveInfo;
10 | import android.os.Environment;
11 |
12 | import com.zxy.recovery.core.Recovery;
13 | import com.zxy.recovery.exception.RecoveryException;
14 |
15 | import java.io.File;
16 | import java.text.DateFormat;
17 | import java.text.SimpleDateFormat;
18 | import java.util.List;
19 |
20 | /**
21 | * Created by zhengxiaoyong on 16/8/28.
22 | */
23 | public class RecoveryUtil {
24 |
25 | private static final ThreadLocal DATE_FORMAT_THREAD_LOCAL = new ThreadLocal() {
26 | @Override
27 | protected DateFormat initialValue() {
28 | return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
29 | }
30 | };
31 |
32 | private RecoveryUtil() {
33 | throw new RecoveryException("Stub!");
34 | }
35 |
36 | public static T checkNotNull(T t, String message) {
37 | if (t == null)
38 | throw new RecoveryException(String.valueOf(message));
39 | return t;
40 | }
41 |
42 | public static boolean isIntentAvailable(Context context, Intent intent) {
43 | if (context == null || intent == null)
44 | return false;
45 | PackageManager packageManager = context.getApplicationContext().getPackageManager();
46 | List list = packageManager.queryIntentActivities(intent,
47 | PackageManager.MATCH_DEFAULT_ONLY);
48 | return list.size() > 0;
49 | }
50 |
51 | public static boolean isAppInBackground(Context context) {
52 | ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
53 | List appProcesses = activityManager.getRunningAppProcesses();
54 | if (appProcesses == null)
55 | return true;
56 | for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
57 | if (appProcess.processName.equals(context.getPackageName())) {
58 | return appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
59 | }
60 | }
61 | return false;
62 | }
63 |
64 | public static String getAppName(Context context) {
65 | PackageManager packageManager = null;
66 | ApplicationInfo applicationInfo = null;
67 | if (!(context instanceof Application))
68 | context = context.getApplicationContext();
69 | try {
70 | packageManager = context.getPackageManager();
71 | applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
72 | } catch (PackageManager.NameNotFoundException e) {
73 | applicationInfo = null;
74 | }
75 | CharSequence charSequence = packageManager.getApplicationLabel(applicationInfo);
76 | return charSequence == null ? "" : (String) charSequence;
77 | }
78 |
79 | public static boolean isMainProcess(Context context) {
80 | try {
81 | ActivityManager am = ((ActivityManager) context
82 | .getSystemService(Context.ACTIVITY_SERVICE));
83 | List processInfo = am.getRunningAppProcesses();
84 | String mainProcessName = context.getPackageName();
85 | int myPid = android.os.Process.myPid();
86 | for (ActivityManager.RunningAppProcessInfo info : processInfo) {
87 | if (info.pid == myPid && mainProcessName.equals(info.processName)) {
88 | return true;
89 | }
90 | }
91 | } catch (Exception e) {
92 | e.printStackTrace();
93 | }
94 | return false;
95 | }
96 |
97 | private static File getDataDir() {
98 | return new File(File.separator + "data" + File.separator + "data" + File.separator + Recovery.getInstance().getContext().getPackageName());
99 | }
100 |
101 | private static File getExternalDataDir() {
102 | File file = null;
103 | if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
104 | file = Recovery.getInstance().getContext().getExternalCacheDir();
105 | }
106 | return file == null ? null : file.getParentFile();
107 | }
108 |
109 | private static boolean clearAppData(File dir) {
110 | if (dir == null || !dir.isDirectory() || !dir.exists())
111 | return false;
112 | File[] files = dir.listFiles();
113 | int length = files.length;
114 | for (int i = 0; i < length; i++) {
115 | File file = files[i];
116 | if (file == null)
117 | continue;
118 | if (file.isFile() && file.exists()) {
119 | boolean result = file.delete();
120 | RecoveryLog.e(file.getName() + (result ? " delete success!" : " delete failed!"));
121 | continue;
122 | }
123 | if (file.isDirectory() && file.exists()) {
124 | clearAppData(file);
125 | }
126 | }
127 | return true;
128 | }
129 |
130 | public static void clearApplicationData() {
131 | clearAppData(getDataDir());
132 | clearAppData(getExternalDataDir());
133 | }
134 |
135 | public static int dp2px(Context context, float dpValue) {
136 | final float scale = context.getResources().getDisplayMetrics().density;
137 | return (int) (dpValue * scale + 0.5f);
138 | }
139 |
140 | public static DateFormat getDateFormat() {
141 | return DATE_FORMAT_THREAD_LOCAL.get();
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/tools/Reflect.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.tools;
2 |
3 | import android.text.TextUtils;
4 |
5 | import com.zxy.recovery.exception.ReflectException;
6 |
7 | import java.lang.reflect.Constructor;
8 | import java.lang.reflect.Field;
9 | import java.lang.reflect.InvocationTargetException;
10 | import java.lang.reflect.Method;
11 | import java.lang.reflect.Modifier;
12 |
13 | /**
14 | * Created by zhengxiaoyong on 16/8/26.
15 | */
16 | public class Reflect {
17 |
18 | private Class> mReflectObjectClazz;
19 |
20 | private Reflect(String className) {
21 | checkNotEmpty(className, "ClassName can not be empty!");
22 | try {
23 | this.mReflectObjectClazz = Class.forName(className);
24 | } catch (ClassNotFoundException e) {
25 | throw new ReflectException("Class:" + className + " can not be found!", e.getCause());
26 | }
27 | }
28 |
29 | private Reflect(Class> clazz) {
30 | checkNotNull(clazz, "Reflect class can not be null!");
31 | this.mReflectObjectClazz = clazz;
32 | }
33 |
34 | public static Reflect on(String className) {
35 | return new Reflect(className);
36 | }
37 |
38 | public static Reflect on(Class> clazz) {
39 | return new Reflect(clazz);
40 | }
41 |
42 | public final ReflectMethod method(String methodName, Class>... types) {
43 | checkNotEmpty(methodName, "MethodName can not be empty!");
44 | Method method;
45 | try {
46 | if (types == null || types.length == 0) {
47 | method = mReflectObjectClazz.getDeclaredMethod(methodName);
48 | } else {
49 | method = mReflectObjectClazz.getDeclaredMethod(methodName, types);
50 | }
51 | method.setAccessible(true);
52 | return ReflectMethod.create(method);
53 | } catch (NoSuchMethodException e) {
54 | e.printStackTrace();
55 | }
56 | return ReflectMethod.create(null);
57 | }
58 |
59 | public static final class ReflectMethod {
60 | private Method method;
61 |
62 | private ReflectMethod(Method method) {
63 | this.method = method;
64 | }
65 |
66 | static ReflectMethod create(Method method) {
67 | return new ReflectMethod(method);
68 | }
69 |
70 | public Method obtain() {
71 | return method;
72 | }
73 |
74 | public Object invoke(Object invoker, Object... params) {
75 | if (method == null)
76 | return null;
77 | if (invoker == null) {
78 | if ((method.getModifiers() & Modifier.STATIC) == 0)
79 | throw new ReflectException("Invoker can not be null!");
80 | }
81 | try {
82 | if (params == null || params.length == 0)
83 | return method.invoke(invoker);
84 | return method.invoke(invoker, params);
85 | } catch (IllegalAccessException e) {
86 | e.printStackTrace();
87 | } catch (InvocationTargetException e) {
88 | e.printStackTrace();
89 | }
90 | return null;
91 | }
92 | }
93 |
94 | public final ReflectField field(String fieldName) {
95 | checkNotEmpty(fieldName, "FieldName can not be empty!");
96 | try {
97 | Field field = mReflectObjectClazz.getDeclaredField(fieldName);
98 | field.setAccessible(true);
99 | return ReflectField.create(field);
100 | } catch (NoSuchFieldException e) {
101 | e.printStackTrace();
102 | }
103 | return ReflectField.create(null);
104 | }
105 |
106 | public static final class ReflectField {
107 | private Field field;
108 |
109 | private ReflectField(Field field) {
110 | this.field = field;
111 | }
112 |
113 | static ReflectField create(Field field) {
114 | return new ReflectField(field);
115 | }
116 |
117 | public Field obtain() {
118 | return field;
119 | }
120 |
121 | public void set(Object target, Object value) {
122 | if (field == null)
123 | return;
124 | if (target == null) {
125 | if ((field.getModifiers() & Modifier.STATIC) == 0)
126 | throw new ReflectException("Target object can not be null!");
127 | }
128 | try {
129 | field.set(target, value);
130 | } catch (IllegalAccessException e) {
131 | e.printStackTrace();
132 | }
133 | }
134 |
135 | public Object get(Object target) {
136 | if (field == null)
137 | return null;
138 | if (target == null) {
139 | if ((field.getModifiers() & Modifier.STATIC) == 0)
140 | throw new ReflectException("Target object can not be null!");
141 | }
142 | try {
143 | return field.get(target);
144 | } catch (IllegalAccessException e) {
145 | e.printStackTrace();
146 | }
147 | return null;
148 | }
149 | }
150 |
151 | public final ReflectConstructor constructor(Class>... types) {
152 | Constructor constructor;
153 | try {
154 | if (types == null || types.length == 0) {
155 | constructor = mReflectObjectClazz.getDeclaredConstructor();
156 | } else {
157 | constructor = mReflectObjectClazz.getDeclaredConstructor(types);
158 | }
159 | constructor.setAccessible(true);
160 | return ReflectConstructor.create(constructor);
161 | } catch (NoSuchMethodException e) {
162 | e.printStackTrace();
163 | }
164 | return ReflectConstructor.create(null);
165 | }
166 |
167 | public static final class ReflectConstructor {
168 | private Constructor constructor;
169 |
170 | private ReflectConstructor(Constructor constructor) {
171 | this.constructor = constructor;
172 | }
173 |
174 | static ReflectConstructor create(Constructor constructor) {
175 | return new ReflectConstructor(constructor);
176 | }
177 |
178 | public Constructor obtain() {
179 | return constructor;
180 | }
181 |
182 | public Object newInstance(Object... params) {
183 | if (constructor == null)
184 | return null;
185 | try {
186 | if (params == null || params.length == 0)
187 | return constructor.newInstance();
188 | return constructor.newInstance(params);
189 | } catch (InstantiationException e) {
190 | e.printStackTrace();
191 | } catch (IllegalAccessException e) {
192 | e.printStackTrace();
193 | } catch (InvocationTargetException e) {
194 | e.printStackTrace();
195 | }
196 | return null;
197 | }
198 | }
199 |
200 | public Object newInstance() {
201 | if (mReflectObjectClazz == null)
202 | return null;
203 | try {
204 | return mReflectObjectClazz.newInstance();
205 | } catch (InstantiationException e) {
206 | e.printStackTrace();
207 | } catch (IllegalAccessException e) {
208 | e.printStackTrace();
209 | }
210 | return null;
211 | }
212 |
213 |
214 | private static void checkNotNull(T t, String message) {
215 | if (t == null)
216 | throw new ReflectException(String.valueOf(message));
217 | }
218 |
219 | private static void checkNotEmpty(String t, String message) {
220 | if (TextUtils.isEmpty(t))
221 | throw new ReflectException(String.valueOf(message));
222 | }
223 |
224 | }
225 |
--------------------------------------------------------------------------------
/recovery/src/main/java/com/zxy/recovery/tools/SharedPreferencesCompat.java:
--------------------------------------------------------------------------------
1 | package com.zxy.recovery.tools;
2 |
3 |
4 | import android.content.Context;
5 | import android.content.SharedPreferences;
6 | import android.os.Process;
7 | import android.support.annotation.NonNull;
8 | import android.text.TextUtils;
9 |
10 | import java.util.Map;
11 | import java.util.Set;
12 | import java.util.concurrent.ExecutorService;
13 | import java.util.concurrent.Executors;
14 | import java.util.concurrent.ThreadFactory;
15 |
16 | /**
17 | * Created by zhengxiaoyong on 16/8/27.
18 | */
19 | public class SharedPreferencesCompat {
20 |
21 | private SharedPreferencesCompat() {
22 | throw new SharedPreferencesException("Stub!");
23 | }
24 |
25 | private static SharedPreferences getSharedPrefs(Context context, String sharedPrefsName) {
26 | checkNotNull(context, "Context can not be null!");
27 | checkNotEmpty(sharedPrefsName, "SharedPreferences name can not be empty!");
28 | return context.getSharedPreferences(sharedPrefsName, Context.MODE_PRIVATE);
29 | }
30 |
31 | public static void put(Context context, String sharedPrefsName, String key, String value) {
32 | checkNotEmpty(key, "SharedPreferences key can not be empty!");
33 | checkNotNull(value, "SharedPreferences value can not be null!");
34 | SharedPreferences.Editor editor = getSharedPrefs(context, sharedPrefsName).edit();
35 | editor.putString(key, value);
36 | SharedPreferencesEditorCompat.apply(editor);
37 | }
38 |
39 | public static String get(Context context, String sharedPrefsName, String key, String defValue) {
40 | checkNotEmpty(key, "SharedPreferences key can not be empty!");
41 | return getSharedPrefs(context, sharedPrefsName).getString(key, defValue);
42 | }
43 |
44 | public static void clear(Context context, String sharedPrefsName) {
45 | SharedPreferences.Editor editor = getSharedPrefs(context, sharedPrefsName).edit();
46 | editor.clear();
47 | SharedPreferencesEditorCompat.apply(editor);
48 | }
49 |
50 | public static void remove(Context context, String sharedPrefsName, String key) {
51 | checkNotEmpty(key, "SharedPreferences key can not be empty!");
52 | SharedPreferences.Editor editor = getSharedPrefs(context, sharedPrefsName).edit();
53 | editor.remove(key);
54 | SharedPreferencesEditorCompat.apply(editor);
55 | }
56 |
57 | public static Map getAll(Context context, String sharedPrefsName) {
58 | checkNotNull(context, "Context can not be null!");
59 | return getSharedPrefs(context, sharedPrefsName).getAll();
60 | }
61 |
62 | public static boolean contains(Context context, String sharedPrefsName, String key) {
63 | checkNotEmpty(key, "SharedPreferences key can not be empty!");
64 | return getSharedPrefs(context, sharedPrefsName).contains(key);
65 | }
66 |
67 | public static Set getStringSet(Context context, String sharedPrefsName, String key, Set defValues) {
68 | checkNotEmpty(key, "SharedPreferences key can not be empty!");
69 | return getSharedPrefs(context, sharedPrefsName).getStringSet(key, defValues);
70 | }
71 |
72 | public static Builder newBuilder(Context context, String sharedPrefsName) {
73 | return new Builder(context, sharedPrefsName);
74 | }
75 |
76 | public static final class Builder {
77 |
78 | private SharedPreferences.Editor mEditor;
79 |
80 | private Builder(Context context, String sharedPrefsName) {
81 | mEditor = getSharedPrefs(context, sharedPrefsName).edit();
82 | }
83 |
84 | public Builder put(String key, String value) {
85 | checkNotEmpty(key, "SharedPreferences key can not be empty!");
86 | checkNotNull(value, "SharedPreferences value can not be null!");
87 | mEditor.putString(key, value);
88 | return this;
89 | }
90 |
91 | public void apply() {
92 | if (mEditor != null)
93 | SharedPreferencesEditorCompat.apply(mEditor);
94 | }
95 |
96 | public void commit() {
97 | if (mEditor != null)
98 | SharedPreferencesEditorCompat.commit(mEditor);
99 | }
100 |
101 | }
102 |
103 | private static void checkNotNull(T t, String message) {
104 | if (t == null)
105 | throw new SharedPreferencesException(String.valueOf(message));
106 | }
107 |
108 | private static void checkNotEmpty(String t, String message) {
109 | if (TextUtils.isEmpty(t))
110 | throw new SharedPreferencesException(String.valueOf(message));
111 | }
112 |
113 | private static final class SharedPreferencesException extends RuntimeException {
114 | public SharedPreferencesException(String message, Throwable cause) {
115 | super(message, cause);
116 | }
117 |
118 | public SharedPreferencesException(String message) {
119 | super(message);
120 | }
121 | }
122 |
123 | private static final class SharedPreferencesEditorCompat {
124 |
125 | private static final ExecutorService SINGLE_THREAD_POOL;
126 |
127 | static {
128 | SINGLE_THREAD_POOL = Executors.newFixedThreadPool(1, new SharedPreferencesThreadFactory());
129 | }
130 |
131 | static void apply(final SharedPreferences.Editor editor) {
132 | try {
133 | editor.apply();
134 | } catch (Throwable e) {
135 | SINGLE_THREAD_POOL.submit(new Runnable() {
136 | @Override
137 | public void run() {
138 | editor.commit();
139 | }
140 | });
141 | }
142 | }
143 |
144 | static void commit(SharedPreferences.Editor editor) {
145 | editor.commit();
146 | }
147 | }
148 |
149 | private static final class SharedPreferencesThreadFactory implements ThreadFactory {
150 |
151 | private static final String THREAD_NAME = "SharedPreferencesThread";
152 |
153 | @Override
154 | public Thread newThread(@NonNull final Runnable r) {
155 | Runnable wrapper = new Runnable() {
156 | @Override
157 | public void run() {
158 | try {
159 | Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
160 | } catch (Throwable t) {
161 | t.printStackTrace();
162 | }
163 | r.run();
164 | }
165 | };
166 | Thread thread = new Thread(wrapper, THREAD_NAME);
167 | if (thread.isDaemon())
168 | thread.setDaemon(false);
169 | return thread;
170 | }
171 | }
172 | }
--------------------------------------------------------------------------------
/recovery/src/main/res/drawable-xhdpi/ic_recovery_page.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Sunzxyong/Recovery/bca6d12b91e37aaf8b85a9e8eccd2518047f434c/recovery/src/main/res/drawable-xhdpi/ic_recovery_page.png
--------------------------------------------------------------------------------
/recovery/src/main/res/drawable/recovery_default_btn_selector.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | -
4 |
5 |
6 |
7 |
8 |
9 | -
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/recovery/src/main/res/layout/recovery_activity_recover.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
16 |
17 |
21 |
22 |
31 |
32 |
37 |
38 |
49 |
50 |
59 |
60 |
69 |
70 |
79 |
80 |
81 |
82 |
93 |
94 |
--------------------------------------------------------------------------------
/recovery/src/main/res/layout/recovery_layout_debug.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
16 |
17 |
21 |
22 |
32 |
33 |
38 |
39 |
43 |
44 |
57 |
58 |
71 |
72 |
85 |
86 |
99 |
100 |
101 |
111 |
112 |
117 |
118 |
130 |
131 |
141 |
142 |
147 |
148 |
158 |
159 |
160 |
--------------------------------------------------------------------------------
/recovery/src/main/res/menu/recovery_menu.xml:
--------------------------------------------------------------------------------
1 |
11 |
--------------------------------------------------------------------------------
/recovery/src/main/res/menu/recovery_menu_sub.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/recovery/src/main/res/values-en/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Debug
4 | Save
5 | Restart and clear
6 | Restart
7 | Recover
8 | Tips
9 | Sure
10 | Cancel
11 | This will clear all the data and restart the application.
12 | ExceptionType: %s
13 | ClassName: %s
14 | MethodName: %s
15 | LineNumber: %d
16 | %s.An error occurred when used\nPlease try to recover or restart the application.
17 |
--------------------------------------------------------------------------------
/recovery/src/main/res/values-v19/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
--------------------------------------------------------------------------------
/recovery/src/main/res/values-v21/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
--------------------------------------------------------------------------------
/recovery/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #2E2E36
4 | #2E2E36
5 | #BDBDBD
6 | #3C4350
7 | #FFFFFF
8 | #C6C6C6
9 |
--------------------------------------------------------------------------------
/recovery/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 8dp
5 | 4dp
6 |
7 | 14sp
8 |
9 |
--------------------------------------------------------------------------------
/recovery/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Debug
3 | Save
4 | 重启并清空缓存
5 | 重启应用
6 | 恢复界面
7 | 提示
8 | 确定
9 | 取消
10 | 此操作将清空应用的所有数据并重新启动应用!
11 | ExceptionType: %s
12 | ClassName: %s
13 | MethodName: %s
14 | LineNumber: %d
15 | %s在使用时发生一个错误\n请尝试恢复或重启应用!
16 |
17 |
--------------------------------------------------------------------------------
/recovery/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':recovery', ':recovery-no-op'
2 |
--------------------------------------------------------------------------------