Skip to content

Commit 0134248

Browse files
authored
Merge pull request #1050 from android/bw/threadPolicy
Enable the thread police 👮 for debug builds
2 parents 4854419 + 27a05c4 commit 0134248

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

app/src/main/kotlin/com/google/samples/apps/nowinandroid/NiaApplication.kt

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@
1717
package com.google.samples.apps.nowinandroid
1818

1919
import android.app.Application
20+
import android.content.pm.ApplicationInfo
21+
import android.os.StrictMode
22+
import android.os.StrictMode.ThreadPolicy.Builder
2023
import coil.ImageLoader
2124
import coil.ImageLoaderFactory
2225
import com.google.samples.apps.nowinandroid.sync.initializers.Sync
@@ -37,10 +40,34 @@ class NiaApplication : Application(), ImageLoaderFactory {
3740

3841
override fun onCreate() {
3942
super.onCreate()
43+
44+
setStrictModePolicy()
45+
4046
// Initialize Sync; the system responsible for keeping data in the app up to date.
4147
Sync.initialize(context = this)
4248
profileVerifierLogger()
4349
}
4450

4551
override fun newImageLoader(): ImageLoader = imageLoader.get()
52+
53+
/**
54+
* Return true if the application is debuggable.
55+
*/
56+
private fun isDebuggable(): Boolean {
57+
return 0 != applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE
58+
}
59+
60+
/**
61+
* Set a thread policy that detects all potential problems on the main thread, such as network
62+
* and disk access.
63+
*
64+
* If a problem is found, the offending call will be logged and the application will be killed.
65+
*/
66+
private fun setStrictModePolicy() {
67+
if (isDebuggable()) {
68+
StrictMode.setThreadPolicy(
69+
Builder().detectAll().penaltyLog().penaltyDeath().build(),
70+
)
71+
}
72+
}
4673
}

0 commit comments

Comments
 (0)