StrictMode是什么
StrictMode意思為嚴格模式,是用來檢測程序中違例情況的開發者工具。
最常用的場景就是檢測主線程中本地磁盤和網絡讀寫等耗時的操作。
StrictMode最常用來捕捉應用程序的主線程,它將報告與線程及虛擬機相關的策略違例。一旦檢測到策略違例(policy violation),你將獲得警告,其包含了一個棧trace顯示你的應用在何處發生違例。
嚴格模式會將應用的違例細節暴露給開發者方便優化與改善。
StrictMode的檢查策略
線程策略(TreadPolicy)
自定義的耗時調用 使用detectCustomSlowCalls()開啟
磁盤讀取操作 使用detectDiskReads()開啟
磁盤寫入操作 使用detectDiskWrites()開啟
網絡操作 使用detectNetwork()開啟
VM策略(VmPolicy)
Activity泄露 使用detectActivityLeaks()開啟
未關閉的Closable對象泄露 使用detectLeakedClosableObjects()開啟
泄露的Sqlite對象 使用detectLeakedSqlLiteObjects()開啟
檢測實例數量 使用setClassInstanceLimit()開啟
怎么使用StrictMode
嚴格模式需要在debug模式開啟,不要在release版本中啟用。
放在哪里
嚴格模式的開啟可以放在Application或者Activity以及其他組件的onCreate方法。
為了更好地分析應用中的問題,建議放在Application的onCreate方法中。
- 實現方式一
開啟與否只在這里設置true或者false就可以了
---------------------------------------------------------------------------
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
}
這段代碼放在Application的onCreate方法中,一般放在最開始的地方。
-----------------------------------------------------------------------------
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
}
- 實現方式二
開啟與否:使用AndroidMainifest文件中的debuggable屬性來實現
關于這個屬性的解釋:
Whether or not the application can be debugged, even when running on a device in user mode
— "true " if it can be, and "false " if not.
The default value is "false ".
-----------------------------------------------------------------------------
android:debuggable="true"
這段代碼放在Application的onCreate方法中,一般放在最開始的地方。
-----------------------------------------------------------------------------
// Return if this application is not in debug mode
ApplicationInfo appInfo = context.getApplicationInfo();
int appFlags = appInfo.flags;
if ((appFlags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
}
- 查看結果
嚴格模式有很多種報告違例的形式,但是想要分析具體違例情況,還是需要查看日志,終端下過濾StrictMode就能得到違例的具體stacktrace信息。
adb logcat | grep StrictMode
- 手機端直觀觀察
除了通過日志查看之外,我們也可以在手機的開發者選項中開啟嚴格模式,開啟之后,如果主線程中有執行時間長的操作,屏幕則會閃爍,這是一個更加直接的方法。