This is only thrown for applications targeting the Honeycomb + * SDK or higher. Applications targeting earlier SDK versions + * are allowed to do networking on their main event loop threads, + * but it's heavily discouraged. See the document + * + * Designing for Responsiveness. + * + *
Also see {@link StrictMode}. + */ +public class NetworkOnMainThreadException extends RuntimeException { +} diff --git a/core/java/android/os/StrictMode.java b/core/java/android/os/StrictMode.java index 40aceb3713dc1..5a6369c3a5c72 100644 --- a/core/java/android/os/StrictMode.java +++ b/core/java/android/os/StrictMode.java @@ -150,10 +150,19 @@ public final class StrictMode { public static final int PENALTY_DIALOG = 0x20; /** + * Death on any detected violation. + * * @hide */ public static final int PENALTY_DEATH = 0x40; + /** + * Death just for detected network usage. + * + * @hide + */ + public static final int PENALTY_DEATH_ON_NETWORK = 0x200; + /** * @hide */ @@ -176,7 +185,8 @@ public final class StrictMode { * Mask of all the penalty bits. */ private static final int PENALTY_MASK = - PENALTY_LOG | PENALTY_DIALOG | PENALTY_DEATH | PENALTY_DROPBOX | PENALTY_GATHER; + PENALTY_LOG | PENALTY_DIALOG | PENALTY_DEATH | PENALTY_DROPBOX | PENALTY_GATHER | + PENALTY_DEATH_ON_NETWORK; /** * The current VmPolicy in effect. @@ -323,11 +333,27 @@ public final class StrictMode { * Crash the whole process on violation. This penalty runs at * the end of all enabled penalties so you'll still get * see logging or other violations before the process dies. + * + *
Unlike {@link #penaltyDeathOnNetwork}, this applies + * to disk reads, disk writes, and network usage if their + * corresponding detect flags are set. */ public Builder penaltyDeath() { return enable(PENALTY_DEATH); } + /** + * Crash the whole process on any network usage. Unlike + * {@link #penaltyDeath}, this penalty runs + * before anything else. You must still have + * called {@link #detectNetwork} to enable this. + * + *
In the Honeycomb or later SDKs, this is on by default. + */ + public Builder penaltyDeathOnNetwork() { + return enable(PENALTY_DEATH_ON_NETWORK); + } + /** * Log detected violations to the system log. */ @@ -648,6 +674,18 @@ public final class StrictMode { return true; } + /** + * Used by the framework to make network usage on the main + * thread a fatal error. + * + * @hide + */ + public static void enableDeathOnNetwork() { + int oldPolicy = getThreadPolicyMask(); + int newPolicy = oldPolicy | DETECT_NETWORK | PENALTY_DEATH_ON_NETWORK; + setThreadPolicyMask(newPolicy); + } + /** * Parses the BlockGuard policy mask out from the Exception's * getMessage() String value. Kinda gross, but least @@ -758,6 +796,9 @@ public final class StrictMode { if ((mPolicyMask & DETECT_NETWORK) == 0) { return; } + if ((mPolicyMask & PENALTY_DEATH_ON_NETWORK) != 0) { + throw new NetworkOnMainThreadException(); + } if (tooManyViolationsThisLoop()) { return; }