Introduction of Android Strictmode

Source: Internet
Author: User

The newest Android platform (from Android 2.3), new added a new class called Strictmode (Android.os.StrictMode). This class can be used to help developers improve the applications they write and to provide a variety of strategies that can check and report on problems in developer applications at any time, such as monitoring work that should not have been done in the main thread or some other nonstandard and bad code.

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.

Strictmode's policies and rules

Currently, there are two major types of strategies to use, one for common monitoring, and the other for VM virtual machines.

(1) Common monitoring strategies include the following:

Disk Reads disks Read

Disk writes diskette write

Network access

Custom Slow code customization for slow-running codes analysis

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.

(2) The VM strategy focuses on the following categories:

Memory-Leaking Activity object

SQLite objects with memory leaks

Freed objects with memory leaks

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.

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.

One. Enable Strictmode

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:

  

Strictmode.setthreadpolicy (new////print Logcat, of course, you can also navigate to Dropbox and save the corresponding log by file  . Build ()); Strictmode.setvmpolicy (new  StrictMode.VmPolicy.Builder (). Detectall (). Penaltylog (). build ());

  

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:

 Public void onCreate () {  if  (developer_mode) {strictmode.setthreadpolicy (new  StrictMode.ThreadPolicy.Builder (). Detectdiskreads ()
. Detectdiskwrites ()
. Detectnetwork (). Penaltylog (). build ()); Super. OnCreate ();

  

Two. Running Strictmode

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.

 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): 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): atAndroid.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 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) 09-04 16:15:34.592:debug/ Strictmode (15883): at Dalvik.system.NativeStart.main (Native Method

The following prompt window will appear prompting the user to:

Ignore Certain rules

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.

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:

 

Strictmode.threadpolicy old = strictmode.getthreadpolicy (); Strictmode.setthreadpolicy (new  StrictMode.ThreadPolicy.Builder (old). Permitdiskwrites (). Build (  ));  Docorrectstuffthatwritestodisk (); Strictmode.setthreadpolicy (old);

This first saves the current policy rule with old, and then Docorrectstuffthatwritestodisk ();

Here, you perform some quick read and write operations to the disk, and finally re-enable the rules.

Summary

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.

Original address: http://hb.qq.com/a/20110914/000054.htm

Related Article

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.