Android's Strictmode

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/tonyfield/article/details/8238251

Android 2.3 offers a debug feature called the Tough Mode (Strictmode), which Google says has benefited hundreds of of Google apps on Android. So what does it do? It will report policy violations related to threads and virtual machines. Once a policy violation has been detected, you will get a warning that it contains a stack trace showing where your app is violating the violation. You can force a warning instead of a crash (crash), or you can just count the warnings into the log for your app to continue executing. The details of the strategy are hard to determine and you can expect Google to add more strategies as it matures with Android.

There are currently 2 strategies available, the first of which is thread-dependent, and it is primarily for the main thread (or UI thread). Since it is not good to read and write disks and network access in the main thread, Google has added a strict mode (Strictmode) hook (hook) to the disk and network code. If you turn on strict mode (Strictmode) on a thread, you will get a warning when that thread is accessing the disk and network. You can choose the warning mode. Some of the violations contain user slow calls (custom slow calls so translate line?). ), disk read-write, network access. You can choose to write a warning to Logcat, display a dialog box, flash down the screen, write to the Dropbox log file, or let the app crash. The most common practice is to write logcat or let the app crash. Listing 2-9 shows an example of setting a strict mode for threading policy (Strictmode).

Listing 2-9 threading policies for setting strict mode (Strictmode)

[Java]View Plaincopy
    1. Strictmode.setthreadpolicy (new StrictMode.ThreadPolicy.Builder ()
    2. . Detectdiskreads ()
    3. . Detectdiskwrites ()
    4. . Detectnetwork ()
    5. . Penaltylog ()
    6. . build ());

The builder class makes setup simple, and the builder function defines that all policies return builder objects so that they can be concatenated like List 2-9. The last call to the build () function returns an Threadpolicy object as an argument to the Setthreadpolicy () function of the Strictmode object. Note that Setthreadpolicy () is a static function, so you do not need to instantiate the Strictmode object. Internally, Setthreadpolicy () applies the policy to the current thread. If you do not specify a detection function, you can also use Detectall () instead. Penaltylog () indicates that the warning output to Logcat, you can also use other or add new penalty (penalty) functions, such as using Penaltydeath (), once the Strictmode message is written to Logcat after the application will crash.

You do not need to open the strict mode frequently (Strictmode), you can open it in the OnCreate () function of the main activity, or you can set the strict mode (Strictmode) in the OnCreate () function of the application derived class. Any code running in a thread can be set in strict mode (Strictmode), but you do only need to set it once, once enough.

Similar to Thread policy (threadpolicy), strict mode (Strictmode) has a virtual machine policy (vmpolicy). A virtual machine policy (vmpolicy) can check for memory leaks, such as the end operation before closing a SQLite object, or any other similar closure of an object before it is closed. The virtual machine policy (Vmpolicy) is created by a similar builder class, as shown in Listing 2-10. Unlike thread policy (threadpolicy), Virtual machine policy (Vmpolicy) cannot provide a warning through a dialog box.

Listing 2-10 Setting the virtual machine policy for strict mode (Strictmode)

[Java]View Plaincopy
    1. Strictmode.setvmpolicy (new StrictMode.VmPolicy.Builder ()
    2. . Detectleakedsqlliteobjects ()
    3. . Penaltylog ()
    4. . Penaltydeath ()
    5. . build ());

Because the settings occur in threads, strict mode (Strictmode) can even find violations in the control flow from one object to another. When the violation occurs, you will be surprised to notice that the code is running on the main thread, and the stack trace will help you find out how it happened. You can then debug the problem in one step, or move the code to its own background thread, or keep it in its original way. It all depends on you. Of course, you might want to turn off tough mode (Strictmode) When your program is released as a product, and you don't want it to crash in your users ' hands just for a warning.

There are two ways to turn off the harsh mode (Strictmode), the most straightforward is to remove the code, but this is not conducive to the continuous development of the product. You can usually define an application-level Boolean variable to test if you need to invoke the harsh mode (Strictmode) code. This value is defined as false before the product is released. A more elegant approach is to define this Boolean variable in Androidmanifest.xml, using the features of debug mode. One of the properties of the <application> field is android:debuggable, which is self-explanatory. Listing 2-11 shows a controlled-release method using this feature.

Listing 2-11 Strict mode setting only in debug mode (Strictmode)

[Java]View Plaincopy
  1. Return If this application was not in debug mode
  2. ApplicationInfo appInfo = Context.getapplicationinfo ();
  3. int appflags = Appinfo.flags;
  4. if ((Appflags & applicationinfo.flag_debuggable)! = 0) {
  5. //Do Strictmode setup here
  6. Strictmode.setvmpolicy (new StrictMode.VmPolicy.Builder ()
  7. . Detectleakedsqlliteobjects ()
  8. . Penaltylog ()
  9. . Penaltydeath ()
  10. . build ());
  11. }

With the Eclipse debugging environment, ADT automatically sets the Debuggable property for you, making the project easier to manage. When you deploy the app on the emulator or directly on the device, the Debuggable property is true, and ADT sets the property to False when you export the app to build a product version. Note that if you set this property value separately, ADT does not change it.

Tough mode (Strictmode) is good, but the mode does not work on versions prior to Android 2.3. To avoid this problem, you need to verify that the version is Android2.3 and above when the Strictmode object does not exist. You can use the reflection technique (reflection) to call it when the strict mode (Strictmode) function is active, not the other way around. Method is simple, you can follow the code in listing 2-12

Listing 2-12 using the Reflection Technology (reflection) to invoke the harsh mode (Strictmode)

[Java]View Plaincopy
  1. try {
  2. Class Smode = Class.forName ("Android.os.StrictMode");
  3. Method enabledefaults = Smode.getmethod ("enabledefaults");
  4. Enabledefaults.invoke (null);
  5. }
  6. catch (Exception e) {
  7. //Strictmode not supported on this device, punt
  8. LOG.V ("Strictmode", "... not supported".  Skipping ... ");
  9. }

When the harsh mode (Strictmode) does not exist, the classnotfoundexception exception is caught. Enabledefault () is another function of the harsh mode (Strictmode) class that detects all violations and writes to Logcat. Because the static form of Enabledefault () is called here, it is passed in as a parameter with NULL.

At some point you don't want to report all the violations. It is good to set the hard mode (Strictmode) in other threads other than the main thread. For example, you need to read the disk in the thread being monitored. At this point, you either do not call Detectdiskreads () or call Detectall () followed by a permitdiskreads (). Similar allow functions apply to other operations as well. But what if you're going to do these things before the Anroid2.3 version? Of course.

When the harsh mode (Strictmode) in the app is invalid, if you try to access it, a Verifyerror exception will be thrown. If you encapsulate the harsh mode (Strictmode) in a class and catch the error, you can ignore it when the hard mode (Strictmode) is invalid. Listing 2-13 shows a simple rigorous mode (Strictmode) wrapper class Strictmodewrapper. Listing 2-14 shows how to use this wrapper class in your app.

List 2–13 the strict mode (Strictmode) package class before Anroid2.3 version

[Java]View Plaincopy
  1. Import Android.content.Context;
  2. Import Android.content.pm.ApplicationInfo;
  3. Import Android.os.StrictMode;
  4. Public class Strictmodewrapper {
  5. public static void init (context context) {
  6. //Check if Android:debuggable is set to True
  7. int appflags = Context.getapplicationinfo (). Flags;
  8. if ((Appflags & applicationinfo.flag_debuggable)! = 0) {
  9. Strictmode.setthreadpolicy (new StrictMode.ThreadPolicy.Builder ()
  10. . Detectdiskreads ()
  11. . Detectdiskwrites ()
  12. . Detectnetwork ()
  13. . Penaltylog ()
  14. . build ());
  15. Strictmode.setvmpolicy (new StrictMode.VmPolicy.Builder ()
  16. . Detectleakedsqlliteobjects ()
  17. . Penaltylog ()
  18. . Penaltydeath ()
  19. . build ());
  20. }
  21. }
  22. }


List 2–14 calling the strict mode (Strictmode) wrapper class before Anroid2.3 version

[Java]View Plaincopy
      1. try {
      2. Strictmodewrapper.init (this);
      3. }
      4. catch (Throwable throwable) {
      5. LOG.V ("Strictmode", "... is not available. Punting ... ");
      6. }

Android's Strictmode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.