Android中的StrictMode


StrictMode是从Android2.3引入的一种新调试功能。它的用途是报告与线程和虚拟机相关的策略违规。如果检测到策略违规,则发出一个提醒,其中包含一个栈帧,现实违规时的应用程序状态,可是强制使应用在提醒时崩溃,或者仅仅提示,然后继续运行。
 
目前StrictMode有两种类型的策略:一种与线程有关,一种与虚拟机有关。
 
1.线程策略违规的检测:

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork()  // or .detectAll() for all detectable problems
                .penaltyLog()
                .build());

2.vm策略违规的检测:

StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .detectLeakedClosableObjects()
                .penaltyLog()
                .penaltyDeath()
                .build());

这些代码应该放在Application或者Activity的onCreate的最前面。
 
发现违规以后,我们可以使用thread,handler,intentservice等组件来解决这些问题。

相关内容