Android Performance(1) StrictMode
转载请注明来自:http://blog.csdn.net/liaoqianchuan00/article/details/23432475
概述
我们应该避免在主线程中作一些耗时的操作,这些操作包括文件读写,网络获取。而从android API9 2.3.3开始就提供了StrictMode为我们来监测这些耗时的操作。
防止程序出现ANR。
StrictMode有两大策略,每种策略又可以设置一些监测规则。
常用线程策略:
detectDiskReads | 监测磁盘读 |
detectDiskWrites | 监测磁盘写 |
detectNetwork | 监测网络获取 |
监测所有的规则 | |
| 监测速度慢的代码 |
penaltyLog | 打印log |
让程序crash | |
关闭监测 | |
关闭磁盘监测 | |
关闭磁盘写监测 | |
关闭网络获取监测 |
常用虚拟机策略
监测泄露的activity | |
监测全部 | |
监测未释放对象 | |
监测没有取消注册的对象,比如BroadcastReceiver | |
监测泄露的数据库对象 | |
监测到这些违背的时候让程序crash | |
打印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,Handler, AsyncTask, IntentService来避免程序违反这些规则,但是我们没有必要完全避免这些规则,有的时候在主线程中进行快速的磁盘读写是有必要的。但是网络请求是必须要避免在主线程中进行的。