public final class StrictMode extends Object
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.
StrictMode is most commonly used to catch accidental disk or network access on the application's main thread, where UI operations are received and animations take place. Keeping disk and network operations off the main thread makes for much smoother, more responsive applications. By keeping your application's main thread responsive, you also prevent ANR dialogs from being shown to users.
Note that even though an Android device's disk is often on flash memory, many devices run a filesystem on top of that memory with very limited concurrency. It's often the case that almost all disk accesses are fast, but may in individual cases be dramatically slower when certain I/O is happening in the background from other processes. If possible, it's best to assume that such things are not fast.
Example code to enable from early in your
Application
, Activity
, or
other application component's
Application.onCreate()
method:
public void onCreate() { if (DEVELOPER_MODE) { StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder
() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()); StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder
() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()); } super.onCreate(); }
You can decide what should happen when a violation is detected.
For example, using StrictMode.ThreadPolicy.Builder.penaltyLog()
you can
watch the output of adb logcat
while you use your
application to see the violations as they happen.
If you find violations that you feel are problematic, there are
a variety of tools to help solve them: threads, Handler
,
AsyncTask
, IntentService
, etc.
But don't feel compelled to fix everything that StrictMode finds. In particular,
many cases of disk access are often necessary during the normal activity lifecycle. Use
StrictMode to find things you did by accident. Network requests on the UI thread
are almost always a problem, though.
StrictMode is not a security mechanism and is not
guaranteed to find all disk or network accesses. While it does
propagate its state across process boundaries when doing
Binder
calls, it's still ultimately a best
effort mechanism. Notably, disk or network access from JNI calls
won't necessarily trigger it. Future versions of Android may catch
more (or fewer) operations, so you should never leave StrictMode
enabled in applications distributed on Google Play.
Modifier and Type | Class and Description |
---|---|
static class |
StrictMode.Span
A tracked, critical time span.
|
static class |
StrictMode.StrictModeNetworkViolation |
static class |
StrictMode.StrictModeViolation |
static class |
StrictMode.ThreadPolicy
StrictMode policy applied to a certain thread. |
static class |
StrictMode.ViolationInfo
Parcelable that gets sent in Binder call headers back to callers
to report violations that happened during a cross-process call.
|
static class |
StrictMode.VmPolicy
StrictMode policy applied to all threads in the virtual machine's process. |
Modifier and Type | Field and Description |
---|---|
static int |
DETECT_CUSTOM
For StrictMode.noteSlowCall()
|
static int |
DETECT_DISK_READ |
static int |
DETECT_DISK_WRITE |
static int |
DETECT_NETWORK |
static int |
DETECT_RESOURCE_MISMATCH
For StrictMode.noteResourceMismatch()
|
static int |
DETECT_VM_ACTIVITY_LEAKS
Note, a "VM_" bit, not thread.
|
static int |
DETECT_VM_CLOSABLE_LEAKS
Note, a "VM_" bit, not thread.
|
static int |
DETECT_VM_CURSOR_LEAKS
Note, a "VM_" bit, not thread.
|
static int |
DETECT_VM_REGISTRATION_LEAKS |
static String |
DISABLE_PROPERTY
Boolean system property to disable strict mode checks outright.
|
static int |
NETWORK_POLICY_ACCEPT |
static int |
NETWORK_POLICY_LOG |
static int |
NETWORK_POLICY_REJECT |
static int |
PENALTY_DEATH |
static int |
PENALTY_DEATH_ON_CLEARTEXT_NETWORK
Death when cleartext network traffic is detected.
|
static int |
PENALTY_DEATH_ON_FILE_URI_EXPOSURE
Death when file exposure is detected.
|
static int |
PENALTY_DEATH_ON_NETWORK
Death when network traffic is detected on main thread.
|
static int |
PENALTY_DIALOG |
static int |
PENALTY_DROPBOX |
static int |
PENALTY_FLASH |
static int |
PENALTY_GATHER
Non-public penalty mode which overrides all the other penalty
bits and signals that we're in a Binder call and we should
ignore the other penalty bits and instead serialize back all
our offending stack traces to the caller to ultimately handle
in the originating process.
|
static int |
PENALTY_LOG |
static String |
VISUAL_PROPERTY
The boolean system property to control screen flashes on violations.
|
Modifier and Type | Method and Description |
---|---|
static StrictMode.ThreadPolicy |
allowThreadDiskReads()
A convenience wrapper that takes the current
StrictMode.ThreadPolicy from getThreadPolicy() , modifies it
to permit disk reads, and sets the new policy
with setThreadPolicy(android.os.StrictMode.ThreadPolicy) , returning the old policy so you
can restore it at the end of a block. |
static StrictMode.ThreadPolicy |
allowThreadDiskWrites()
A convenience wrapper that takes the current
StrictMode.ThreadPolicy from getThreadPolicy() , modifies it
to permit both disk reads & writes, and sets the new policy
with setThreadPolicy(android.os.StrictMode.ThreadPolicy) , returning the old policy so you
can restore it at the end of a block. |
static void |
conditionallyCheckInstanceCounts() |
static boolean |
conditionallyEnableDebugLogging()
Enable DropBox logging for debug phone builds.
|
static void |
decrementExpectedActivityCount(Class klass) |
static void |
disableDeathOnFileUriExposure()
Used by lame internal apps that haven't done the hard work to get
themselves off file:// Uris yet.
|
static void |
enableDeathOnFileUriExposure()
Used by the framework to make file usage a fatal error.
|
static void |
enableDeathOnNetwork()
Used by the framework to make network usage on the main
thread a fatal error.
|
static void |
enableDefaults()
Enable the recommended StrictMode defaults, with violations just being logged.
|
static StrictMode.Span |
enterCriticalSpan(String name)
Enter a named critical span (e.g. an animation)
The name is an arbitary label (or tag) that will be applied
to any strictmode violation that happens while this span is
active.
|
static StrictMode.ThreadPolicy |
getThreadPolicy()
Returns the current thread's policy.
|
static int |
getThreadPolicyMask()
Returns the bitmask of the current thread's policy.
|
static StrictMode.VmPolicy |
getVmPolicy()
Gets the current VM policy.
|
static void |
incrementExpectedActivityCount(Class klass) |
static void |
noteDiskRead() |
static void |
noteDiskWrite() |
static void |
noteResourceMismatch(Object tag)
For code to note that a resource was obtained using a type other than
its defined type.
|
static void |
noteSlowCall(String name)
For code to note that it's slow.
|
static void |
onCleartextNetworkDetected(byte[] firstPacket) |
static void |
onFileUriExposed(Uri uri,
String location) |
static void |
onIntentReceiverLeaked(Throwable originStack) |
static void |
onServiceConnectionLeaked(Throwable originStack) |
static void |
onSqliteObjectLeaked(String message,
Throwable originStack) |
static void |
onVmPolicyViolation(String message,
Throwable originStack) |
static void |
onVmPolicyViolation(String message,
Throwable originStack,
boolean forceDeath) |
static void |
onWebViewMethodCalledOnWrongThread(Throwable originStack) |
static void |
setThreadPolicy(StrictMode.ThreadPolicy policy)
Sets the policy for what actions on the current thread should
be detected, as well as the penalty if such actions occur.
|
static void |
setVmPolicy(StrictMode.VmPolicy policy)
Sets the policy for what actions in the VM process (on any
thread) should be detected, as well as the penalty if such
actions occur.
|
static Object |
trackActivity(Object instance)
Returns an object that is used to track instances of activites.
|
static boolean |
vmCleartextNetworkEnabled() |
static boolean |
vmClosableObjectLeaksEnabled() |
static boolean |
vmFileUriExposureEnabled() |
static boolean |
vmRegistrationLeaksEnabled() |
static boolean |
vmSqliteObjectLeaksEnabled() |
public static final String DISABLE_PROPERTY
public static final String VISUAL_PROPERTY
public static final int DETECT_DISK_WRITE
public static final int DETECT_DISK_READ
public static final int DETECT_NETWORK
public static final int DETECT_CUSTOM
public static final int DETECT_RESOURCE_MISMATCH
public static final int DETECT_VM_CURSOR_LEAKS
public static final int DETECT_VM_CLOSABLE_LEAKS
public static final int DETECT_VM_ACTIVITY_LEAKS
public static final int DETECT_VM_REGISTRATION_LEAKS
public static final int PENALTY_LOG
public static final int PENALTY_DIALOG
public static final int PENALTY_DEATH
public static final int PENALTY_FLASH
public static final int PENALTY_DROPBOX
public static final int PENALTY_GATHER
public static final int PENALTY_DEATH_ON_NETWORK
public static final int PENALTY_DEATH_ON_CLEARTEXT_NETWORK
public static final int PENALTY_DEATH_ON_FILE_URI_EXPOSURE
public static final int NETWORK_POLICY_ACCEPT
public static final int NETWORK_POLICY_LOG
public static final int NETWORK_POLICY_REJECT
public static void setThreadPolicy(StrictMode.ThreadPolicy policy)
Internally this sets a thread-local variable which is propagated across cross-process IPC calls, meaning you can catch violations when a system service or another process accesses the disk or network on your behalf.
policy
- the policy to put into placepublic static int getThreadPolicyMask()
public static StrictMode.ThreadPolicy getThreadPolicy()
public static StrictMode.ThreadPolicy allowThreadDiskWrites()
StrictMode.ThreadPolicy
from getThreadPolicy()
, modifies it
to permit both disk reads & writes, and sets the new policy
with setThreadPolicy(android.os.StrictMode.ThreadPolicy)
, returning the old policy so you
can restore it at the end of a block.setThreadPolicy(android.os.StrictMode.ThreadPolicy)
to
restore the policy at the end of a blockpublic static StrictMode.ThreadPolicy allowThreadDiskReads()
StrictMode.ThreadPolicy
from getThreadPolicy()
, modifies it
to permit disk reads, and sets the new policy
with setThreadPolicy(android.os.StrictMode.ThreadPolicy)
, returning the old policy so you
can restore it at the end of a block.public static boolean conditionallyEnableDebugLogging()
public static void enableDeathOnNetwork()
public static void enableDeathOnFileUriExposure()
public static void disableDeathOnFileUriExposure()
public static void conditionallyCheckInstanceCounts()
public static void setVmPolicy(StrictMode.VmPolicy policy)
policy
- the policy to put into placepublic static StrictMode.VmPolicy getVmPolicy()
public static void enableDefaults()
This catches disk and network access on the main thread, as
well as leaked SQLite cursors and unclosed resources. This is
simply a wrapper around setVmPolicy(android.os.StrictMode.VmPolicy)
and setThreadPolicy(android.os.StrictMode.ThreadPolicy)
.
public static boolean vmSqliteObjectLeaksEnabled()
public static boolean vmClosableObjectLeaksEnabled()
public static boolean vmRegistrationLeaksEnabled()
public static boolean vmFileUriExposureEnabled()
public static boolean vmCleartextNetworkEnabled()
public static void onWebViewMethodCalledOnWrongThread(Throwable originStack)
public static void onIntentReceiverLeaked(Throwable originStack)
public static void onServiceConnectionLeaked(Throwable originStack)
public static void onCleartextNetworkDetected(byte[] firstPacket)
public static void onVmPolicyViolation(String message, Throwable originStack, boolean forceDeath)
public static StrictMode.Span enterCriticalSpan(String name)
The name is an arbitary label (or tag) that will be applied to any strictmode violation that happens while this span is active. You must call finish() on the span when done.
This will never return null, but on devices without debugging enabled, this may return a dummy object on which the finish() method is a no-op.
TODO: add CloseGuard to this, verifying callers call finish.
public static void noteSlowCall(String name)
StrictMode.ThreadPolicy
has
StrictMode.ThreadPolicy.Builder.detectCustomSlowCalls()
enabled.name
- a short string for the exception stack trace that's
built if when this fires.public static void noteResourceMismatch(Object tag)
StrictMode.ThreadPolicy
has
StrictMode.ThreadPolicy.Builder.detectResourceMismatches()
enabled.tag
- an object for the exception stack trace that's
built if when this fires.public static void noteDiskRead()
public static void noteDiskWrite()
public static Object trackActivity(Object instance)
public static void incrementExpectedActivityCount(Class klass)
public static void decrementExpectedActivityCount(Class klass)