Android Strictmode Detailed

Source: Internet
Author: User
<span id="Label3"></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">Strictmode has a number of different strategies, each with different rules, and when a developer violates a rule, each strategy has a different way of showing the User. In this article, we'll give an example of how to use Strictmode in Android.</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">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.</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">currently, There are two major classes of strategies to use, one for threading monitoring:</span></p></p><pre class="brush:java;toolbar: true; auto-links: false;"><pre class="brush:java;toolbar: true; auto-links: false;">Strictmode.setthreadpolicy (new StrictMode.ThreadPolicy.Builder (). detectdiskreads (). detectdiskwrites (). de Tectnetwork (). penaltylog (). Build ());</pre></pre><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">The other is about VM VMs and other aspects of the STRATEGY.</span><br><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;"></span></p></p><pre class="brush:java;toolbar: true; auto-links: false;"><pre class="brush:java;toolbar: true; auto-links: false;">Strictmode.setvmpolicy (new StrictMode.VmPolicy.Builder (). detectleakedsqlliteobjects (). penaltylog (). Penal Tydeath (). Build ());</pre></pre><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">Common monitoring strategies include the following:</span><br><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;"></span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">1) Disk Reads diskette read</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">2) Disk writes diskette write</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">3) Network access</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">4) Custom Slow Code customization for slow-running codes analysis</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">The first three kinds of meaning readers should be very clear, just as their name shows, respectively, the disk read and write, network access Monitoring. The fourth type of custom slow code analysis, which is triggered only when the calling class is accessed, can be used to monitor slow-running Code. When called in the main thread, these validation rules will work to check your Code. For example, when your application is downloading or parsing a large amount of data, you can trigger a custom run slow code query analysis, a great Role. Strictmode can be used to capture time-consuming disk, network access, or function calls that occur in the main thread of the application, helping developers to improve their programs, making the main thread processing UI and animations smoother when disk reads and writes and network operations, avoiding blocking of the main thread.</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">The VM strategy focuses on the following categories:</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">1) Memory Leak Activity Object</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">2) memory leaks for SQLite objects</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">3) memory-leaking Objects released</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">Among them, memory leaks of activity objects and memory leaks of SQLite objects are better understood, and so-called to close the object of the check, mainly to monitor those who should be freed, such as the object should call the close () method.</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">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.</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">When a developer violates a certain type of rule, each strategy has a different way of making the developer aware of the Situation. Related violations can be recorded in Logcat or stored in the DropBox (android.os.DropBox) service. The common monitoring class strategy also shows the relevant dialog box and the context when the violation occurs, all in order to allow developers to quickly understand the flaws of the program to submit the quality of the Program. The following steps explain how to use Stritctmode.</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;"><strong>First step Enable Strictmode</strong></span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">In order to enable and configure Strictmode in the application, it is best to use the early segment of the Application's life cycle as much as possible, by calling the Strictmode method Setthreadpolicy. When using common monitoring classes, one of the best times to call is when the entry and activities are invoked before the Application. For example, in an application, you can put the code in the OnCreate () method that launches the activity class, below is a code example that enables all policies and rules in the current situation, and when a program violates a commonly used rule, the relevant prompt window Appears:</span></p></p><pre class="brush:java;toolbar: true; auto-links: false;"><pre class="brush:java;toolbar: true; auto-links: false;">Strictmode.setthreadpolicy (new StrictMode.ThreadPolicy.Builder (). detectall (). penaltylog (). Penal Tydialog ()////print logcat, of course, You can also navigate to Dropbox and save the corresponding log. build () from the file; Strictmode.setvmpolicy (new StrictMode.VmPolicy.Builder (). detectall (). penaltylog (). Build ());</pre></pre><p><p><span style="font-size: 14px;">of course, The above code should only be run in an app that is not released on-line beta, to facilitate monitoring of related operations, and Strictmode should not be enabled on the production Version. therefore, The best code practice should look like this:</span></p></p><pre class="brush:java;toolbar: true; auto-links: false;">Public void oncreate ()  {      if  (developer_mode)  {           strictmode.setthreadpolicy (new  StrictMode.ThreadPolicy.Builder ()                    .detectdiskreads ()                    .detectdiskwrites ()                    .detectnetwork ()                    .penaltylog ()                    .build () );       }      super.oncreate ();   }</pre><p><p><span style="font-size: 14px;"></span></p></p><p><p><span style="font-size: 14px;">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.</span></p></p><p><p><span style="font-size: 14px;">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</span></p></p><p><p><span style="font-size: 14px;">Listing 2-12 using the reflection technology (reflection) to invoke the harsh mode (strictmode)</span></p></p><pre class="brush:java;toolbar: true; auto-links: false;"><pre class="brush:java;toolbar: true; auto-links: false;">Try {Class smode = Class.forName ("android.os.StrictMode");      Method enabledefaults = Smode.getmethod ("enabledefaults");  Enabledefaults.invoke (null);  } catch (Exception E) {///strictmode not supported on the this device, punt log.v ("strictmode", "... not supported".  Skipping ... "); }</pre></pre><p><p><strong><span style="font-size: 14px;"></span></strong><span style="font-size: 14px;">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.</span></p></p><p><p><span style="font-size: 14px;">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.</span></p></p><p><p><span style="font-size: 14px;">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.</span></p></p><p><p><span style="font-size: 14px;">The following is a simple rigorous mode (strictmode) encapsulation class Strictmodewrapper</span></p></p><pre class="brush:java;toolbar: true; auto-links: false;">public class strictmodewrapper {      public static  Void init (context context)  {          //  check if android:debuggable is set to true           int appflags = context.getapplicationinfo () .flags;           if  (appflags & applicationinfo.flag_ DEBUGGABLE)  != 0)  {               strictmode.setthreadpolicy (new strictmode.threadpolicy.builder ()                    .detectdiskreads ()                    . Detectdiskwrites ()                    .detectnetwork ()                    .penaltylog ()                   . Build ());               Strictmode.setvmpolicy (new strictmode.vmpolicy.builder ()                    .detectleakedsqlliteobjects ()                    .penaltylog ()                    . Penaltydeath ()                    .build ());           }      }  } </pre><p><p><span style="font-size: 14px;"></span><span style="font-size: 14px;">Here's How to use this wrapper class in your app:</span></p></p><pre class="brush:java;toolbar: true; auto-links: false;"><pre class="brush:java;toolbar: true; auto-links: false;">Try {strictmodewrapper.init (this); } catch (throwable Throwable) {log.v ("strictmode", "... is not available.  Punting ... "); }</pre></pre><p><p><strong><span style="font-size: 14px;">Step two run Strictmode</span></strong></p></p><p><p><span style="font-size: 14px;">When the app is enabled for Strictmode mode, it's actually no different than a normal application, which is just like running a normal application when you're testing and Running. When Strictmode mode is enabled, All program runs are monitored and the user is prompted when a major problem or policy violation is FOUND. The following is when running an app with Strictmode mode enabled, when a violation of the rules is found, the information displayed to the user, carefully observed with ordinary error message is Different.</span></p></p><pre class="brush:java;toolbar: true; auto-links: false;">09-04 16:15:34.592: debug/strictmode (15883):  strictmode policy violation; ~ Duration=319 ms: android.os.strictmode$strictmodediskwriteviolation: policy=31 violation=1  09-04 16:15:34.592: debug/strictmode (15883):     at  Android.os.strictmode$androidblockguardpolicy.onwritetodisk (strictmode.java:1041)  09-04 16:15:34.592 :  debug/strictmode (15883):     at  Android.database.sqlite.SQLiteStatement.acquireAndLock (sqlitestatement.java:219)  09-04 16:15:34.592:  debug/strictmode (15883):     at  Android.database.sqlite.SQLiteStatement.executeUpdateDelete (sqlitestatement.java:83)  09-04  16:15:34.592: debug/strictmode (15883):     at  Android.database.sqlite.SQLiteDatabase.updateWithOnConflict (sqlitedatabase.java:1829)  09-04  16:15:34.592: debug/strictmode (15883): &NBSp;    at android.database.sqlite.sqlitedatabase.update (SQLiteDatabase.java:1780)  09-04 16:15:34.592: debug/strictmode (15883):     at  Com.mamlambo.tutorial.tutlist.data.TutListProvider.update (tutlistprovider.java:188)  09-04  16:15:34.592: debug/strictmode (15883):     at  Android.content.contentprovider$transport.update (contentprovider.java:233)  09-04 16:15:34.592:  Debug/strictmode (15883):      at android.content.contentresolver.update ( Contentresolver.java:847)  09-04 16:15:34.592: debug/strictmode (15883):      at com.mamlambo.tutorial.tutlist.data.tutlistprovider.markitemread (TutListProvider.java:229)   09-04 16:15:34.592: debug/strictmode (15883):     at  Com.mamlambo.tutorial.tutlist.TutListFragment.onListItemClick (tutlistfragment.java:99)  09-04 16:15:34.592: debug/strictmode (15883):     at  Android.support.v4.app.listfragment$2.onitemclick (listfragment.java:53)  09-04 16:15:34.592:  Debug/strictmode (15883):      at android.widget.adapterview.performitemclick ( Adapterview.java:282)  09-04 16:15:34.592: debug/strictmode (15883):      at android.widget.abslistview.performitemclick (abslistview.java:1037)  09-04 16:15:34.592:  debug/strictmode (15883):      at android.widget.abslistview$ Performclick.run (abslistview.java:2449)  09-04 16:15:34.592: debug/strictmode (15883):      at android.widget.abslistview$1.run (abslistview.java:3073)  09-04  16:15:34.592: debug/strictmode (15883):     at  Android.os.Handler.handleCallback (handler.java:587)  09-04 16:15:34.592: debug/striCtmode (15883):      at android.os.handler.dispatchmessage (Handler.java:92)   09-04 16:15:34.592: debug/strictmode (15883):     at  Android.os.Looper.loop (looper.java:132)  09-04 16:15:34.592: debug/strictmode (15883):      at android.app.activitythread.main (activitythread.java:4123)  09-04  16:15:34.592: debug/strictmode (15883):     at  Java.lang.reflect.Method.invokeNative (NATIVE&NBSP;METHOD) 09-04 16:15:34.592: debug/strictmode (15883) :      at java.lang.reflect.method.invoke (method.java:491)  09-04  16:15:34.592: debug/strictmode (15883):     at  Com.android.internal.os.zygoteinit$methodandargscaller.run (zygoteinit.java:841)  09-04 16:15:34.592:  debug/strictmode (15883):      at com.android.internal.os.zygoteinit.Main (ZYGOTEINIT.JAVA:599) </pre><p><p><span style="font-size: 14px;">The following prompt window will appear prompting the user to:</span></p></p><p><p><span style="font-size: 14px;"></span></p></p><p><p><strong><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">Ignore Certain rules</span></strong></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">It should be said that most of the rule warnings generated by Strictmode should be followed, but sometimes not all the information produced indicates that your program has Errors. For example, in the main thread of the application to quickly read and write to the disk will not have too much impact on the performance of the application, or you have some debugging code in the debugger phase violates the set rules, these can ignore these rules.</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">There are two ways to ignore the rule, one is to simply comment out the code in the code, and the other good way is to add the appropriate code to let the system stop using these rules when and where it needs to be strictmode, and then reapply the rules when the developer deems it necessary to check, such as:</span></p></p><pre class="brush:java;toolbar: true; auto-links: false;"><pre class="brush:java;toolbar: true; auto-links: false;">Strictmode.threadpolicy old = Strictmode.getthreadpolicy (); Strictmode.setthreadpolicy (new StrictMode.ThreadPolicy.Builder (old). permitdiskwrites (). Build ()); Docorrectstuffthatwritestodisk (); Strictmode.setthreadpolicy (old);</pre></pre><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">This first saves the current policy rule with old, and then Docorrectstuffthatwritestodisk ();</span></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">here, you perform some quick read and write operations to the disk, and finally re-enable the Rules.</span></p></p><p><p><strong><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">Summary</span></strong></p></p><p><p><span style="font-family: 微软雅黑, ‘Microsoft YaHei‘; font-size: 14px;">Strictmode is a very useful class that can be easily applied to check the performance and problems of Android Applications. When this mode is turned on, the developer can check the potential problems in the application very well, and refer to the relevant API instructions in the Android Documentation.</span></p></p><p><p>Android Strictmode Detailed</p></p></span>

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.