For the More Curious: StrictMode

There are some things you simply should not do in your Android app – mistakes that lead directly to crashes and security holes. For example, executing a network request on the main thread would probably result in an ANR error in poor network conditions.

Instead of Android happily allowing you to invoke a network request on the application’s main thread, you get a NetworkOnMainThread exception and log message instead. This is because of StrictMode, which noticed your mistake and helpfully let you know about it. StrictMode was introduced to help you detect this and many other programming mistakes and security problems in your code.

Without any configuration, networking on the main thread is guarded against. StrictMode can also help you detect other mistakes that could drag down your application’s performance. To enable all of StrictMode’s recommended policies, call StrictMode.enableDefaults() (developer.android.com/​reference/​android/​os/​StrictMode.html#enableDefaults()).

Once StrictMode.enableDefaults() has been called, you will hear about the following violations in Logcat:

  • networking on the main thread

  • disk reads and writes on the main thread

  • activities kept alive beyond their natural lifecycle (also known as an “activity leak”)

  • unclosed SQLite database cursors

  • cleartext network traffic not wrapped in SSL/TLS

For custom control over what happens when policy violations occur, you can configure the ThreadPolicy.Builder and VmPolicy.Builder classes. You can specify whether you want an exception to occur, a dialog to be shown, or a statement to be logged to alert you to the violation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.250.1