Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Implementing Strict Mode

When you’re first programming for Android, you need to be aware of several gotchas that may trip you up. For example, it’s common to accidentally block the user interface thread and cause your application to perform badly or, even worse, to become unresponsive. Strict mode was added to the Android SDK to identify issues like this. It’s a good idea, especially when you’re starting out, to always turn on Strict mode.

Strict mode is flexible in that you can filter issues so that it reports only the ones you’re interested in and, when those issues occur, what sort of action should be taken.

You can take the following actions:

  • Logging the issue to LogCat
  • Flashing the device’s screen
  • Stopping the application
  • Opening a dialog box

Setting up Strict mode in your application is straightforward.

  1. To enable Strict mode, add the code in Listing 4.1 after the call to Log.d in the onCreate method of TimerActivity.

    Listing 4.1 Turning On Strict Mode in onCreate

    if (BuildConfig.DEBUG) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
            .detectAll().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
            .detectAll().penaltyLog().penaltyDeath().build());
    }

    This code will detect all issues with threading and display them to the LogCat view. It will also detect common memory leaks, log them, and stop the application. Note that the Builder constructor and all the various detect and penalty methods return the current instance of builder. This is known as function chaining. In this way, methods can be called together one after another to make the code more readable and concise.

  2. A few errors will show in the Problem view. Run Quick fix StrictMode to add the import statement:

    import android.os.StrictMode;
  • + Share This
  • 🔖 Save To Your Account