StrictModeCompat Library

Init StrcitMode safely on any Android version

Kirill Rozov
2 min readMar 24, 2019
The image was taken from http://bit.ly/2HPkWHw

Want to learn more interesting news about Android Development (in Russian)— subscribe to the Android Broadcast Telegram channel.

StrictMode is a developer tool which detects things you might be doing by accident and brings them to your attention so you can fix them. It’s very useful when you need to detect database queries that run on the main thread or you have not closed I/O streams or any other Closeable object.

The main issue of the StrictMode API is fragmentation. When you want to setup some special checks for an application, initialization code will look like:

StrictMode.ThreadPolicy.Builder builder =
new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.penaltyLog();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
builder.detectResourceMismatches();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.detectUnbufferedIo();
}
StrictMode.setThreadPolicy(builder.build());

An example is given for the application with minSdk=21, as it the most popular version as of March 2019.

It looks ugly 😥. That’s why I created StrictModeCompat library. It has safe API to init StrictMode without check of actual SDK version. With the library initialization of StrictMode will be the following:

StrictModeCompat.ThreadPolicy.Builder builder =
new StrictModeCompat.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectResourceMismatches()
.detectUnbufferedIo()

.penaltyLog();
StrictMode.setThreadPolicy(builder.build());

With StrictModeCompat you can setup detection of any problem without thinking about the version of Android on a device.

The library has Kotlin extension library that contains DSL for setup

initStrictMode { 
threadPolicy {
diskReads = true
diskWrites = true
resourceMismatches = true
unbufferedIo = true

penalty {
log = true
}
}
}

Add the library to a project

If you want to add StrictLibraryCompat to a project you need to add dependencies in Gradle file:

dependencies {
implementation "com.kirich1409:strict-mode-compat:X.X.X"
// Kotlin Extensions
implementation "com.kirich1409:strict-mode-compat-kotlin:X.X.X"
}

A version of the library is et by the following rule and based on a project compileSdk:

<compileSdk>.<major>.<minor>-<postfix>

If a version of the SDK isn’t stable than postfix will be added. For the first beta of Android Q SDK the version of the library is 29.0.0-beta1.

More information about StrictModeCompat library can be found at github.com/kirich1409/StrictModeCompat

--

--

Kirill Rozov
Kirill Rozov

No responses yet