android2.3新增api StrictMode介绍

google在android2.3中新增了StrictMode API来设置对一个thread的策略(ui线程或者分线程),它主要检测了读写操作,访问网络,数据库读写等耗时的操作并将其以log或者dialog等形式打印出来。分析这些日志,我们可以尽快找出程序运行缓慢的原因进而优化代码,避免ANR(Application Not Responding)窗口的出现。

启用StrictMode 
推荐的使用StrictMode的方式是,在开发阶段,打开它,在发布应用前,关闭它。 
例如:在你的应用中,onCreate():

public void onCreate() {  
   if (DEVELOPER_MODE) {   
       StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() //构造StrictMode  
               .detectDiskReads() //当发生磁盘读操作时输出  
               .detectDiskWrites()//当发生磁盘写操作时输出   
               .detectNetwork()  //访问网络时输出,这里可以替换为detectAll() 就包括了磁盘读写和网络I/O   
               .penaltyLog()  //以日志的方式输出   
               .build());  
       StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()  
               .detectLeakedSqlLiteObjects() //探测SQLite数据库操作   
          .penaltyLog() //以日志的方式输出   
               .penaltyDeath()  
               .build());  
   }  
 super.onCreate();    

当触发策略中的操作时系统会打印出一条StrictMode日志,格式如下:

02-27 10:03:56.122: DEBUG/StrictMode(16210): StrictMode policy violation; ~duration=696 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=23 violation=2   
02 02-27 10:03:56.122: DEBUG/StrictMode(16210):     at android.os.StrictMode$AndroidBlockGuardPolicy.onReadFromDisk(StrictMode.java:745) 

另外说明两点:

1.在android2.3版本直接在ui线程中访问网络会报错

2.ANR窗口会在程序阻塞或者耗时超过5秒的运算后弹出 




原文地址:https://www.cnblogs.com/itrena/p/7434317.html