├── .gitignore ├── .idea ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── encodings.xml ├── misc.xml ├── modules.xml └── vcs.xml ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the ART/Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | out/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | 20 | # Local configuration file (sdk path, etc) 21 | local.properties 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | 26 | # Log Files 27 | *.log 28 | 29 | # Android Studio Navigation editor temp files 30 | .navigation/ 31 | 32 | # Android Studio captures folder 33 | captures/ 34 | 35 | # Intellij 36 | *.iml 37 | .idea/workspace.xml 38 | 39 | # Keystore files 40 | *.jks 41 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # android常见bug及解决方案总结 2 | ### 空指针 3 | ##### 解决方案 4 | * 不确定对象在使用前先做是否为空判断 5 | * 特别注意:fragment getActivity为null处理 6 | 7 | ### 数组越界 8 | ##### 解决方案 9 | * 使用索引值获取对象值时,需判断索引值是否小于数据源大小 10 | example: 11 | ```javascript 12 | if (mData != null && mData.size() !=0 && i < mData.size()){ 13 | Obj obj = mData.get(i); 14 | } 15 | ``` 16 | 17 | ### ListView或RecycleView 更新数据源命令不同步 18 | ##### 解决方案 19 | * 保证设置数据源和执行adapter.notifyDataSetChanged在同一个线程并且在Ui线程 20 | example: 21 | ```javascript 22 | adapter.setData(mData); 23 | adapter.notifyDataSetChanged(); 24 | ``` 25 | 26 | ### Windows无页面附加(Unable to add window.....is your activity running?) 27 | ##### 解决方案 28 | * 执行windows窗体Dialog或PopupWindow时,先判断当前页面是否销毁,若页面还在则可以执行窗体显示操作,可以通过全局变量或activity自定义堆栈管理判断当前页面是否销毁,在onDestory里面做关闭窗体操作并置空 29 | example: 30 | ```javascript 31 | @Override 32 | protected void onDestroy() { 33 | if (mDialog != null && mDialog.isShowing()){ 34 | mDialog.dismiss(); 35 | mDialog = null; 36 | } 37 | super.onDestroy(); 38 | } 39 | ``` 40 | 41 | ### sqlite问题(数据库缺字段或执行过程异常) 42 | ##### 解决方案 43 | 升级sqlite方法里面添加字段处理,此时记得加入try catch处理方式,防止出现崩溃现象。 44 | example: 45 | ```javascript 46 | FinalDb.DaoConfig daoConfig = new FinalDb.DaoConfig(); 47 | daoConfig.setContext(this); 48 | daoConfig.setDbName(ChatDao.DATABASE_NAME); 49 | daoConfig.setDebug(true); 50 | daoConfig.setDbVersion(ChatDao.DATABASE_VERSION_CODE); 51 | daoConfig.setDbUpdateListener(new FinalDb.DbUpdateListener() { 52 | @Override 53 | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 54 | // 当之前版本的数据升级到新版版本的数据,我们需要给对应表增加新的字段 55 | try { 56 | // 添加字段has_appraised字段 57 | db.execSQL(ChatDao.VERSION_3_SQL_ADD_COLUMN_HAS_PRAISED); 58 | } 59 | catch (Exception e){ 60 | e.printStackTrace(); 61 | } 62 | 63 | try { 64 | // 添加字段receiveDate字段 65 | db.execSQL(ChatDao.VERSION_4_SQL_ADD_CLUMN_RECEIVE_DATE); 66 | } 67 | catch (Exception e){ 68 | e.printStackTrace(); 69 | } 70 | } 71 | }); 72 | FinalDb.create(daoConfig); 73 | ``` 74 | ### OOM(内存溢出) 75 | #### 情况一 76 | 处理bitmap资源不得当造成(压缩或者变换得到新bitmap) 77 | ##### 解决方案 78 | 采用try catch处理方式,若出现异常再做压缩,期间采用弱引用方式处理。 79 | example: 80 | 81 | ```javascript 82 | WeakReference bitmapWeakReference; 83 | // First decode with inJustDecodeBounds=true to check dimensions 84 | final BitmapFactory.Options options = new BitmapFactory.Options(); 85 | try { 86 | options.inJustDecodeBounds = true; 87 | BitmapFactory.decodeFileDescriptor(fd, null, options); 88 | 89 | // Calculate inSampleSize 90 | options.inSampleSize = calculateInSampleSize(options, reqWidth, 91 | reqHeight); 92 | 93 | // Decode bitmap with inSampleSize set 94 | options.inJustDecodeBounds = false; 95 | // 弱引用处理图片 add leibing 2016/12/8 96 | bitmapWeakReference 97 | = new WeakReference(BitmapFactory.decodeFileDescriptor(fd, null, options)); 98 | if (bitmapWeakReference != null && bitmapWeakReference.get() != null) 99 | return bitmapWeakReference.get(); 100 | }catch (OutOfMemoryError ex){ 101 | // 压缩图片指定值 add by leibing 2016/12/8 102 | options.inSampleSize = options.inSampleSize + 4; 103 | options.inJustDecodeBounds = false; 104 | // 弱引用处理图片 add leibing 2016/12/8 105 | bitmapWeakReference 106 | = new WeakReference(BitmapFactory.decodeFileDescriptor(fd, null, options)); 107 | if (bitmapWeakReference != null && bitmapWeakReference.get() != null) 108 | return bitmapWeakReference.get(); 109 | } 110 | ``` 111 | #### 情况二 112 | 各种内存泄漏问题造成,主要有以下: 113 | ##### 单例造成的内存泄露 114 | ###### 解决方案 115 | 1、将该属性的引用方式改为弱引用; 116 | 2、如果传入Context,使用ApplicationContext; 117 | example 118 | 泄漏代码片段 119 | ```javascript 120 | // sington 121 | private static InstanceClass instance; 122 | // activity refer 123 | private Context mContext; 124 | 125 | /** 126 | * set activity refer 127 | * @author leibing 128 | * @createTime 2016/12/9 129 | * @lastModify 2016/12/9 130 | * @param mContext activity refer 131 | * @return 132 | */ 133 | public void setRefer(Context mContext){ 134 | this.mContext = mContext; 135 | } 136 | 137 | /** 138 | * constructor 139 | * @author leibing 140 | * @createTime 2016/12/9 141 | * @lastModify 2016/12/9 142 | * @param 143 | * @return 144 | */ 145 | private InstanceClass(){ 146 | } 147 | 148 | /** 149 | * sington 150 | * @author leibing 151 | * @createTime 2016/12/9 152 | * @lastModify 2016/12/9 153 | * @param 154 | * @return 155 | */ 156 | public static InstanceClass getInstance(){ 157 | if (instance == null){ 158 | synchronized (InstanceClass.class){ 159 | if (instance == null) 160 | instance = new InstanceClass(); 161 | } 162 | } 163 | 164 | return instance; 165 | } 166 | ``` 167 | Solution:使用WeakReference 168 | 169 | ```javascript 170 | // sington 171 | private static InstanceClass instance; 172 | // activity refer 173 | private WeakReference mContextWeakRef; 174 | 175 | /** 176 | * set activity refer 177 | * @author leibing 178 | * @createTime 2016/12/9 179 | * @lastModify 2016/12/9 180 | * @param mContext activity refer 181 | * @return 182 | */ 183 | public void setRefer(Context mContext){ 184 | mContextWeakRef = new WeakReference(mContext); 185 | } 186 | 187 | /** 188 | * constructor 189 | * @author leibing 190 | * @createTime 2016/12/9 191 | * @lastModify 2016/12/9 192 | * @param 193 | * @return 194 | */ 195 | private InstanceClass(){ 196 | } 197 | 198 | /** 199 | * sington 200 | * @author leibing 201 | * @createTime 2016/12/9 202 | * @lastModify 2016/12/9 203 | * @param 204 | * @return 205 | */ 206 | public static InstanceClass getInstance(){ 207 | if (instance == null){ 208 | synchronized (InstanceClass.class){ 209 | if (instance == null) 210 | instance = new InstanceClass(); 211 | } 212 | } 213 | 214 | return instance; 215 | } 216 | ``` 217 | ##### InnerClass匿名内部类 218 | ###### 解决方案 219 | 1、将内部类变成静态内部类; 220 | 2、如果有强引用Activity中的属性,则将该属性的引用方式改为弱引用; 221 | 3、在业务允许的情况下,当Activity执行onDestory时,结束这些耗时任务; 222 | example 223 | 泄漏代码片段 224 | 225 | ```javascript 226 | public class InnerClassActivity extends Activity{ 227 | 228 | @Override 229 | protected void onCreate(Bundle savedInstanceState) { 230 | super.onCreate(savedInstanceState); 231 | // start a thread to work 232 | new InnerThread().start(); 233 | } 234 | 235 | /** 236 | * @interfaceName: InnerThread 237 | * @interfaceDescription: custom thread 238 | * @author: leibing 239 | * @createTime: 2016/12/9 240 | */ 241 | class InnerThread extends Thread{ 242 | @Override 243 | public synchronized void start() { 244 | super.start(); 245 | } 246 | 247 | } 248 | } 249 | ``` 250 | Solution:使用WeakReference + static 251 | 252 | ```javascript 253 | public class InnerClassActivity extends Activity{ 254 | // 图片资源 255 | private Drawable mDrawable; 256 | // inner thread 257 | private InnerThread mInnerThread; 258 | 259 | @Override 260 | protected void onCreate(Bundle savedInstanceState) { 261 | super.onCreate(savedInstanceState); 262 | // init drawable 263 | mDrawable = getResources().getDrawable(R.drawable.ic_launcher); 264 | // start a thread to work 265 | mInnerThread = new InnerThread(mDrawable); 266 | mInnerThread.start(); 267 | } 268 | 269 | @Override 270 | protected void onDestroy() { 271 | if (mInnerThread != null) 272 | mInnerThread.setIsRun(false); 273 | super.onDestroy(); 274 | } 275 | 276 | /** 277 | * @interfaceName: InnerThread 278 | * @interfaceDescription: custom thread 279 | * @author: leibing 280 | * @createTime: 2016/12/9 281 | */ 282 | static class InnerThread extends Thread{ 283 | // weak ref 284 | public WeakReference mDrawableWeakRef; 285 | // is run 286 | private boolean isRun = true; 287 | 288 | /** 289 | * constructor 290 | * @author leibing 291 | * @createTime 2016/12/9 292 | * @lastModify 2016/12/9 293 | * @param mDrawable 图片资源(存在对页面的引用风险) 294 | * @return 295 | */ 296 | public InnerThread(Drawable mDrawable){ 297 | mDrawableWeakRef = new WeakReference(mDrawable); 298 | } 299 | 300 | /** 301 | * set is run 302 | * @author leibing 303 | * @createTime 2016/12/9 304 | * @lastModify 2016/12/9 305 | * @param isRun 306 | * @return 307 | */ 308 | public void setIsRun(boolean isRun){ 309 | this.isRun = isRun; 310 | } 311 | 312 | @Override 313 | public void run() { 314 | while (isRun){ 315 | // do work 316 | try { 317 | // sleep one second 318 | Thread.sleep(1000); 319 | } catch (InterruptedException e) { 320 | e.printStackTrace(); 321 | } 322 | } 323 | } 324 | 325 | @Override 326 | public synchronized void start() { 327 | super.start(); 328 | } 329 | } 330 | } 331 | ``` 332 | #####Activity Context 的不正确使用 333 | ###### 解决方案 334 | 1、使用ApplicationContext代替ActivityContext,因为ApplicationContext会随着应用程序的存在而存在,而不依赖于activity的生命周期; 335 | 2、对Context的引用不要超过它本身的生命周期,慎重的对Context使用“static”关键字。Context里如果有线程,一定要在onDestroy()里及时停掉。 336 | example 337 | 泄漏代码片段 338 | ```javascript 339 | public class DrawableActivity extends Activity{ 340 | // static drawable 341 | private static Drawable leakDrawable; 342 | 343 | @Override 344 | protected void onCreate(Bundle state) { 345 | super.onCreate(state); 346 | TextView label = new TextView(this); 347 | // init drawable 348 | if (leakDrawable == null) { 349 | leakDrawable = getResources().getDrawable(R.drawable.ic_launcher); 350 | } 351 | // view set drawable 352 | label.setBackgroundDrawable(leakDrawable); 353 | 354 | setContentView(label); 355 | } 356 | } 357 | ``` 358 | Solution: 359 | ```javascript 360 | public class DrawableActivity extends Activity{ 361 | // static drawable 362 | private static Drawable leakDrawable; 363 | 364 | @Override 365 | protected void onCreate(Bundle state) { 366 | super.onCreate(state); 367 | TextView label = new TextView(this); 368 | // init drawable 369 | if (leakDrawable == null) { 370 | leakDrawable = getApplicationContext().getResources().getDrawable(R.drawable.ic_launcher); 371 | } 372 | // view set drawable 373 | label.setBackgroundDrawable(leakDrawable); 374 | 375 | setContentView(label); 376 | } 377 | } 378 | ``` 379 | ##### Handler引起的内存泄漏 380 | ###### 解决方案 381 | 1、可以把Handler类放在单独的类文件中,或者使用静态内部类便可以避免泄露; 382 | 2、如果想在Handler内部去调用所在的Activity,那么可以在handler内部使用弱引用的方式去指向所在Activity.使用Static + WeakReference的方式来达到断开Handler与Activity之间存在引用关系的目的。 383 | example 384 | 泄漏代码片段 385 | 386 | ```javascript 387 | public class HandlerActivity extends Activity{ 388 | // custom handler 389 | private CustomHandler mHandler; 390 | 391 | @Override 392 | protected void onCreate(Bundle savedInstanceState) { 393 | super.onCreate(savedInstanceState); 394 | // init custom handler 395 | mHandler = new CustomHandler(); 396 | // sendMsg 397 | Message msg = new Message(); 398 | mHandler.sendMessage(msg); 399 | } 400 | 401 | /** 402 | * @interfaceName: CustomHandler 403 | * @interfaceDescription: custom handler 404 | * @author: leibing 405 | * @createTime: 2016/12/9 406 | */ 407 | class CustomHandler extends Handler{ 408 | @Override 409 | public void handleMessage(Message msg) { 410 | super.handleMessage(msg); 411 | } 412 | } 413 | } 414 | ``` 415 | Solution(static + weakRef): 416 | 417 | ```javascript 418 | public class HandlerActivity extends Activity{ 419 | // custom handler 420 | private CustomHandler mHandler; 421 | 422 | @Override 423 | protected void onCreate(Bundle savedInstanceState) { 424 | super.onCreate(savedInstanceState); 425 | // init custom handler 426 | mHandler = new CustomHandler(this); 427 | // sendMsg 428 | Message msg = new Message(); 429 | mHandler.sendMessage(msg); 430 | } 431 | 432 | /** 433 | * @interfaceName: CustomHandler 434 | * @interfaceDescription: custom handler 435 | * @author: leibing 436 | * @createTime: 2016/12/9 437 | */ 438 | static class CustomHandler extends Handler{ 439 | // weak ref 440 | private WeakReference mContextWeakRef; 441 | 442 | /** 443 | * constructor 444 | * @author leibing 445 | * @createTime 2016/12/9 446 | * @lastModify 2016/12/9 447 | * @param mContext activity ref 448 | * @return 449 | */ 450 | public CustomHandler(Context mContext){ 451 | mContextWeakRef = new WeakReference(mContext); 452 | } 453 | 454 | @Override 455 | public void handleMessage(Message msg) { 456 | super.handleMessage(msg); 457 | if (mContextWeakRef != null && mContextWeakRef.get() != null){ 458 | // do work 459 | } 460 | } 461 | } 462 | } 463 | ``` 464 | ##### 注册监听器的泄漏 465 | ###### 解决方案 466 | 1、使用ApplicationContext代替ActivityContext; 467 | 2、在Activity执行onDestory时,调用反注册; 468 | 469 | ##### Cursor,Stream没有close,View没有recyle; 470 | ###### 解决方案 471 | 资源性对象比如(Cursor,File文件等)往往都用了一些缓冲,我们在不使用的时候,应该及时关闭它们,以便它们的缓冲及时回收内存。它们的缓冲不仅存在于 java虚拟机内,还存在于java虚拟机外。如果我们仅仅是把它的引用设置为null,而不关闭它们,往往会造成内存泄漏。因为有些资源性对象,比如SQLiteCursor(在析构函数finalize(),如果我们没有关闭它,它自己会调close()关闭),如果我们没有关闭它,系统在回收它时也会关闭它,但是这样的效率太低了。因此对于资源性对象在不使用的时候,应该调用它的close()函数,将其关闭掉,然后才置为null. 在我们的程序退出时一定要确保我们的资源性对象已经关闭。 472 | 473 | ##### 集合中对象没清理造成的内存泄漏 474 | ###### 解决方案 475 | 在Activity退出之前,将集合里的东西clear,然后置为null,再退出程序。 476 | 477 | ```javascript 478 | private List mData; 479 | public void onDestory() { 480 | if (mData!= null) { 481 | mData.clear(); 482 | mData= null; 483 | } 484 | } 485 | ``` 486 | ##### WebView造成的泄露 487 | ###### 解决方案 488 | 为webView开启另外一个进程,通过AIDL与主线程进行通信,WebView所在的进程可以根据业务的需要选择合适的时机进行销毁,从而达到内存的完整释放。 489 | 490 | ### 类型转换错误 491 | #### 解决方案 492 | 首先判断类型转换前数据是否符合转化后的数据再做处理。 493 | example: 494 | 字符串转整型数字 495 | 首先判断字符串是否为数字字符串,然后再转换,此时最好加上try catch处理,防止崩溃。 496 | 497 | ### Android Studio: GC overhead limit exceeded 498 | #### 报错现象 499 | ```javascript 500 | Error:Execution failed for task ':app:transformClassesWithDexForDebug'. 501 | > java.lang.OutOfMemoryError: GC overhead limit exceeded 502 | ``` 503 | #### 解决方案 504 | 往module gradle里面添加代码 505 | 506 | dexOptions { 507 | javaMaxHeapSize "4g" 508 | } 509 | 510 | code: 511 | 512 | ```javascript 513 | android { 514 | compileSdkVersion 23 515 | buildToolsVersion "23.0.2" 516 | 517 | defaultConfig { 518 | applicationId "com.xxxxx.android" 519 | minSdkVersion 16 520 | targetSdkVersion 23 521 | versionCode 8 522 | versionName "1.3" 523 | } 524 | 525 | dexOptions { 526 | javaMaxHeapSize "4g" 527 | } 528 | 529 | buildTypes { 530 | release { 531 | minifyEnabled false 532 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 533 | } 534 | } 535 | } 536 | ``` 537 | 链接:http://stackoverflow.com/questions/35034830/android-studio-gc-overhead-limit-exceeded 538 | 539 | 540 | 以上是笔者在项目中遇到的常见bug以及解决方案,如有不足,请补充。 541 | 542 | ### 关于作者 543 | * QQ:872721111 544 | * Email:leibing1989@126.com 545 | * Github:https://github.com/leibing8912 --------------------------------------------------------------------------------