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

penaltyFlashScreen     闪屏提示

我们可以在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);

猜你喜欢

转载自blog.csdn.net/jamin0107/article/details/43152197