Android Performance(1) StrictMode

Android Performance(1) StrictMode

转载请注明来自:http://blog.csdn.net/liaoqianchuan00/article/details/23432475

概述

我们应该避免在主线程中作一些耗时的操作,这些操作包括文件读写,网络获取。而从android API9 2.3.3开始就提供了StrictMode为我们来监测这些耗时的操作。

防止程序出现ANR。

StrictMode有两大策略,每种策略又可以设置一些监测规则。

 

常用线程策略:

detectDiskReads

监测磁盘读

detectDiskWrites

监测磁盘写

detectNetwork

监测网络获取

detectAll

监测所有的规则

detectCustomSlowCalls

 

监测速度慢的代码

penaltyLog

打印log

penaltyDeath

让程序crash

permitAll

关闭监测

permitDiskReads

关闭磁盘监测

permitDiskWrites

关闭磁盘写监测

permitNetwork

关闭网络获取监测

 

常用虚拟机策略

 

detectActivityLeaks

监测泄露的activity

detectAll

监测全部

detectLeakedClosableObjects

监测未释放对象

detectLeakedRegistrationObjects

监测没有取消注册的对象,比如BroadcastReceiver

detectLeakedSqlLiteObjects

监测泄露的数据库对象

penaltyDeath

监测到这些违背的时候让程序crash

penaltyLog

打印log

 

我们可以在Application,Activity或者其他应用程序组件的onCreate中开启这些监测。但是这些监测应该只是在调试的时候启用,只用于调试优化我们的程序,不应该在发布的应用程序中。

例子

public void onCreate() {
     if (DEVELOPER_MODE) {
         StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                 .detectDiskReads()
                 .detectDiskWrites()
                 .detectNetwork()  // or .detectAll() for all detectable problems
                 .penaltyLog()
                 .build());
         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                 .detectLeakedSqlLiteObjects()
                 .detectLeakedClosableObjects()
                 .penaltyLog()
                 .penaltyDeath()
                 .build());
     }
     super.onCreate();
 }

忽略某些规则

有的时候,我们需要忽略到这些监测,比如在主线程中快速的读写文件其实对性能没有多大的影响,这个时候我们可以忽略掉这些监测。    

例如:

 

StrictMode.ThreadPolicy old =StrictMode.getThreadPolicy();

StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder(old)

.permitDiskWrites()

.build());

//这里是快速写磁盘的代码。

StrictMode.setThreadPolicy(old);

 

最后我们又重新启用这些规则。

避免违反这些规则

我们可以用Thread,HandlerAsyncTaskIntentService来避免程序违反这些规则,但是我们没有必要完全避免这些规则,有的时候在主线程中进行快速的磁盘读写是有必要的。但是网络请求是必须要避免在主线程中进行的。

      

      

             

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值