Android Optimization Guide

Source: Internet
Author: User

Optimization of the ListView

  • Reuse Convertview, Historical view object
  • Reduce the number of child queries Viewholder
  • Load data asynchronously (cache the picture)
  • Page load data with multiple hours of entry
  • Show progress bar while loading to allow user to wait

  • The layout hierarchy of item is as simple as possible, avoiding the layout too deep or redrawing unnecessarily

  • Avoid time-consuming operations in the GetView method:
    Loading the local Image, for example, requires loading memory and parsing the Bitmap, which is a time-consuming operation, and if the user slides the ListView quickly, it can cause slippage due to the complexity and time-consuming getview logic. Do not load the picture when the user swipe, to be able to slide to complete reload, can use this third party library glide

  • You should avoid static member variables referencing resources that are consuming too many instances, such as Context.
  • Try to use Getapplicationcontext: if you have to use the context to meet your needs: Context uses application context as much as possible, because application's context has a longer life cycle, There is no memory leak to reference it

  • In some scenarios, the Scollview contains multiple listview, which can be used to fix the height of the listview.
    Because the Scollview in the fast sliding process needs to calculate the height of each listview, blocking the UI thread causes the lag phenomenon, if each of our item height is uniform, can be calculated to determine the height of the ListView, to avoid the phenomenon of stalling

  • Use Recycleview instead of ListView:
    Every time the item content changes, the ListView needs to call notifydatasetchanged to update the entire item, which is a waste of performance. Recycleview can implement local refresh of the item, and introduce the dynamic effect of adding and deleting, which greatly improves the performance and customization.

  • Elements in the ListView avoid translucency:
    Semi-transparent drawing requires a lot of multiplication calculation, in the sliding constantly redraw will cause a lot of calculations, on the relatively poor machine will compare cards. In the design can not be translucent, not not translucent. It's really going to be set to opaque when sliding, and then back to translucent after sliding.

  • Try to turn on hardware acceleration:
    Hardware acceleration increases dramatically, avoiding the use of unsupported functions that cause a tearful shutdown of hardware acceleration somewhere. Of course this one is not just for the ListView.

Optimization of layouts

    • Reuse a layout file as much as possible, using the include tag, multiple identical layouts can be reused
    • Reduce unnecessary nodes of a layout
    • Try to use the view's own parameters, for example: Button, there is a parameter that can draw the diagram on the left: Android:drawableleft
    • Use the < viewstub/> tag to load some less commonly used layouts; use < merge/> tags to reduce nesting levels of layouts

Optimization of Viewpager

    • Viewpager will load the left and right pages by default, sometimes we do not want to see, will waste the user's traffic, Which page can be selected in Setonpagechangelistener's Onpageselected method, which page is initialized
    • because Viewpager destroys the third page by default, You can force Viewpager to load all of the page Pagerview.setoffscreenpagelimit (PageCount), but you can't do that if you have more pages.
    • can define a collection to cache the page. Save it in Destroyitem, read the collection in Instantiateitem, have it, and then create it with no words, just like the Convertview of the ListView
Class Homeadapter extends Pageradapter {//current Viewpager The number of entries linkedlist<imageview> convertview=new LinkedList <ImageView> (); @Overridepublic int GetCount () {returninteger.max_value;} /* Determines the relationship between the returned object and the load View Object */@Overridepublic Boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = arg1;} @Overridepublic void Destroyitem (ViewGroup container, int position, object object) {ImageView view= (ImageView) object; Convertview.add (view);//Add the removed object to the Cache collection Container.removeview (view);} @Overridepublic Object Instantiateitem (viewgroup container, int position) {ImageView view;if (convertview.size () >0) {view=convertview.remove (0);} else{view= New ImageView (Uiutils.getcontext ());} Bitmaputils.display (view, Httphelper.url + "image?name=" + datas.get (index)); Container.addview (view); Load the View object return view; Returned object}}

  

Optimization of memory

    • Reclaim resources already in use, such as cursors cursor, I/O, Bitmap (Close and reference null)
    • Reasonable use of the cache, the chip is very memory-consuming, using LRU cache pictures and compression
    • Set the scope of the variable rationally
    • Controlled use of the service, the background task runs out, even if it does not do anything, the service will always run, these are very memory-intensive, can be used Intentservice
    • Frees memory when the interface is not visible, resources related to the UI in the activity's Ontrimmemory method, and the resources associated with the component in OnStop
    • Reasonable use of multi-process, if the background task and the foreground interface is independent of each other, you can write the process under the component label, so that the build is in another process. And the service is more inclined to open up their dependence on the city, and that process may not need a lot of things, such as the UI
    • Using the thread pool, object pooling
    • When the bitmap object is not in use, it should call recycle () to free memory before it is set to null.

Code optimization

That's part of the refinement, but it's much more subtle, and it's a memory saver.

Any Java class, including internal classes, anonymous classes, consumes approximately 500 bytes of memory space.
An instance of any class consumes 12-16 bytes of memory, so creating instances frequently can also affect memory on some programs, so avoid creating unnecessary objects

    1. If you have a string that needs to be stitched together, you might prefer to use stringbuffer or StringBuilder for stitching instead of the plus connector, because using the plus sign to connect inode creates extra objects, the longer the concatenated string, the lower the performance of the plus connector
    2. Try to use the basic data class instead of the encapsulated data type, int is more efficient than integer, and the other data types are the same

Use static

    1. Using enumerations typically consumes more than twice times more memory than using static constants, and you should not use enumerations as much as possible in Android development.
    2. If you do not need to access some of the fields in an object, just want to invoke one of its methods to complete a common function, then you can set this method to a static method, which will increase the speed of the call 15%-20%, but also do not need to call this method to specifically create objects, This also satisfies one of the above principles. This is also a good programming habit, because we can safely invoke a static method without worrying about whether it will change the state of the object after the method is called (non-static fields cannot be accessed in a static method)

Use the static final modifier for constants

Using enhanced for-loop syntax

Use a system-encapsulated API, such as: IndexOf (), System.arraycopy ()

Performance optimization: Use Drawable objects as much as possible to save pictures instead of bitmap

drawable = drawable.createfromstream (new URL). OpenStream (), "image.png");

The image that the UI component needs to use is the APK package, so use Setimageresource or Setbackgroundresource instead of the ResourceID

Note: Get (Getresources (), R.drawable.btn_achievement_normal) This method is converted to drawable by RESID, you need to consider the issue of recycling, if drawable is an object private object, The memory is definitely not freed until the object is destroyed.

Android Optimization Guide

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.