Share 40 optimization recommendations for Android development _android

Source: Internet
Author: User
Tags garbage collection

Here's a good way to start Android programming:

1, find some similar to the function you want to develop code;

2, adjust it, try to make it become what you want;

3, review the problems encountered in the development

4, the use of StackOverflow to solve problems encountered

Repeat the process for every thing you want to achieve. Using this method can motivate you, because you are keeping iterative updates and you will learn a lot in the process. Of course, when you release the application you have to do something deeper.

This is a qualitative leap from some code that can be compiled properly into an application, and is more pronounced than ios,android. When iOS apps are released, it's actually just jumping between devices, similar to many iOS models, the same size screens, and good hardware support, with 95% models running the same version of the iOS operating system. In Android applications, however, this is not the case.

Our programs must be able to deal with everything: including different screens, processors, custom operating systems, APIs, and any other devices with an Android operating system.

Here are some suggestions I think are better for Android.

Target screen size and solutions

There are more than 100 different screen sizes in the Big world of Android, and there are a lot of ways to address the screen adaptation. To make your Android screen fit, you need to determine the following two things:

1, for different screen resolution and size has a good layout and structure to adapt to it

2, the UI image can adapt to different resolution of the mobile phone

These are separate tasks, and maybe you have a super tablet layout, but the picture on the layout looks bad. Next I'll discuss them in turn.

Design layouts for different screen sizes

1, generally with scrollview+listview easy to handle it

When we have a series of mobile phones with different screen sizes, the biggest difference between them is the height of the screen. So ScrollView and ListView are usually well displayed, although sometimes they don't completely cover the entire screen. We can see everything under the dashboard tag in opensignal, they don't need to slide, but for many advanced controls, sliding shows are not a bad thing. If you can make your application fit with a variety of different sizes of mobile phones, that's perfect, otherwise the two controls will give you the minimum cost to ensure your application matches most of the different screen sizes.


Dashboard style doesn't need scrolling.

2. Use folder structure

Android's Res folder is a powerful structure that allows developers to change the resources of pictures, text, layout files, size specifications, colors, and so on. The following example shows the usefulness of the Res folder:


There is a bools.xml file in the Values-small folder with the following lines of code in the file:

<resources> <bool name= "Small_screen" >true</bool></resources>

You can make a call in code:

if (Getresources (). Getboolean (R.bool.small_screen)) {Getsupportactionbar (). Hide ();}

Set the Boolean value to true in a small screen device so that the Actionbar is hidden to save space. This piece of code is part of the Actionbarsherlock extension library, and will talk about him later. In the VALUES-SW360DP folder, store a res file with a screen width of 360DP. The corresponding code is as follows:

<resources> <bool name= "Small_screen" >false</bool></resources>

On a large screen device, the Actionbar is placed in the visible state.

We don't necessarily need to put the Bools.xml file in the VALUES-SW400DP folder because the Android operating system will automatically search for the appropriate path. For example, a device wide 600DP (600/160=3.75 inch) operating system will search for bools.xml files in VALUES-SW600DP and its corresponding folders, search VALUES-SW400DP folder if not found, and then search for values- SW360DP folder, and so on.

3, 160DP = 1 inches. The 2-inch DP =. DP = Dip.

4, you can use these directory structure techniques to deal with all types of resources.

For example, the XML layout is resolved with the specified size, such as the LAYOUT-SW360DP directory can match the target width is 360DP model, if you need to support the same screen can be used in the following directory:

Layout-sw360dp-landlayout-sw360dp-port

Wait, if half of your users are Arab, change the layout file to the following:

Layout-sw360dp-landlayout-sw360dp-portlayout-sw360dp-land-arlayout-sw360dp-port-ar

The layout of the first two folders can be applied to all languages, and the latter two-ar represent Arabic.

5. Res resource naming rules:

XXX      //No suffix, default applies to Nexus one,droid 2,s2 XXX-SW360DP    //Larger cell phone –galaxy Nexus, S3, S4 xxx-sw600dp    //7 "flat XXX-SW 720DP    //10 "flat panel

In a slightly different place for the Kindle device, as follows:

xxx-large-mdpi    //Kindle Fire 7 "xxx-large-hdpi    

6, if you do not want this layout, you can use Dimens.xml file.

If you look at it just now, you will find that there are a lot of dimens.xml in my values list, because I prefer to set the value in the layout file, which I usually like to do in every XML layout file:

<imageview android:layout_centerhorizontal= "true" android:layout_margintop= "@dimen/small_margin" Android: Layout_width= "@dimen/dashboardwidth" android:layout_height= "@dimen/dashboardheight" android:id= "@+id/dashboard" >

The value of the small_margin is defined in the Dimen.xml file:

<resources> <dimen name= "Small_margin" >4dp</dimen></resources>

This 4DP variable is written in all dimen files. I have an Excel file that creates definitions for all the different dimensions. Maybe you have a question: why don't you let the Android OS handle these screen adapters? Why not use a list of values and a layout directory to replace all the dead values? That's certainly possible, and if properly set, all sizes will be available, but for some elements it's not easy to get the size.

7, let the blank size is larger than the image size, so that the image size is larger than the button size.

If you put a button on a multiple-selection box, switching the control to enlarge it is ugly. A 100dip (0.63 ") size button is not intended to appear on the tablet as the original twice times the width of 200dip (1.25"), because the screen has become larger, but this does not mean that the tablet is for the Giants. We can do this by adding white space to the button and picture extension locations.

8, with graphicallayout tools to quickly preview. Graphicallayout is a WYSIWG XML editor. But I prefer to write code directly, rather than drag and drop controls and discard the programming, but after adding some elements, you can choose a different screen size to test in the Graphicallayout Drop-down selection menu.


9, do not zoom all the pictures.

Using a layout file to accommodate different screen sizes is only half the success, and the controls in the layout (such as images) should be displayed well on a high-resolution screen. The easy way to do this is to create a complete set of picture catalogs that match the various drawable directories.
drawable-sw600dp-ldpi
drawable-sw600dp-mdpi
drawable-sw600dp-hdpi
drawable-sw600dp-xhdpi
DRAWABLE-SW600DP-XXHDPI and so on ...

However, in fact, there is no need to do so, generally there are drawble-ldpi, drawable-hdpi and other directories are enough, do not need to add all.

10, try to avoid using bitmaps (bitmap) (jpg, PNG).

Bitmaps are a good choice for some icons because they are simple to use. But if you can avoid using bitmaps, you can save a lot of space and use different methods to achieve good results.

11, using XML for drawing. Bitmaps can be replaced with XML drawings, although the XML drawing is not omnipotent, but its convenience is still shocking to me, in the Android development documentation is described in detail, here is a simple example:

 <shape  xmlns:android= "http://schemas.android.com/apk/res/android"  android:shape= "Rectangle" >  <corners   android:bottomrightradius= "14DP"   android:bottomleftradius= "14DP"   android: topleftradius= "14DP"   android:toprightradius= "14DP"/>  <gradient   android:startcolor= "@color Off_white "   android:endcolor=" @color/pale_yellow "   android:angle=" 270 "android:type=" linear "/>"  <stroke   android:width= "4DP"   android:color= "@color/osm_darkerblue"/> </shape>

The code above defines a rounded rectangle with a tapered edge (dark blue). You can quote him in the layout file, and it adapts to any screen. Use it to make the ideal button background.

12. Use more XML drawings.

Another example of using XML graphics to make you more excited is whether the following radar effects look more complicated:

There is no harm in using a bitmap for the UI (an icon exception).

13, or XML drawing (if necessary, use a bitmap).

So how do we draw a cool weather icon-let the bulb adjust its brightness dynamically according to the intensity of the light, and how do we make it rotate after clicking? Here we combine bitmaps and XML for an example:


We use PNG chart: icon_magnitude_min (an empty bulb) and Icon_magnitude_max (the highest brightness bulb), and then we crop the latter dynamically. I did it in order to achieve this goal:

 <layer-list xmlns:android= "Http://schemas.android.com/apk/res/android" >  <item   android:drawable = "@drawable/icon_magnitude_min"/>  <item >   <clip    android:cliporientation= "vertical"    android:drawable= "@drawable/icon_magnitude_max"    android:gravity= "top"/>  </item> </ Layer-list>

A reference in a Java program to control the intensity of the light.

14, why use 9-patch (when you can use XML, Drawables time)?

Android has the option of using. 9 files to define Drawables, and some tutorials explain how to use them to make a button so that you can maintain a few corner sizes while stretching (and avoid pixel processing). If you already know how to use. 9, which may be learned from web design, then they might be worth it. If you are unfamiliar with 9-patches, it is recommended that you stay the same. If you want to adapt to some such as rounded corners or colors, it's like going back to the age of the image editor. Many of the effects of. 9 implementations can also be implemented through XML.

15, the custom control is implemented by overriding the OnDraw () method.

There are things that are not fully implemented in XML, we have many images in opensignal and weathersignal, so there are many libraries, but we have to write code for our custom images. It's funny, maybe you'll never have to do this, but this is often the only way to make the image highly dynamic and to achieve customization.

16. Use SVG where XML is not available.

Sometimes it's too technical to cover OnDraw () and work hard to write code that requires lines and arcs for custom view writing. After all, there is a vector-image language Scalable Vector Graphics (extensible vectorial Graphics). It's also one of the coolest Android apps in history,--androidify's power source. In fact they created the library for that app and they posted it here: SVG for Android. This is what we use to draw the dashboard in the OpenSignal.

17, the SVG file gzip compression, they will be smaller they will be processed faster.

18, the SVG library is not supporting everything. It doesn't seem to work properly in some specific alpha channels, and you even have to remove them in your code.

Achieve consistent goals in all versions of Android

19, in some Android systems (such as TOUCHWHIZZ/HTC sense/motoblur, etc.), the default button and other UI components will look very different from the Google native system. I hope it's not true, but it's true.

20, custom UI controls.

To ensure that your app looks the same in all devices, you'll need to customize everything. This is not as difficult as you think, as long as you do it, you will be able to better grasp your app's display appearance.

21, selectors is the tool to create a button.

We mentioned above how to define the background of a button in XML, but how would you create a button that would change when pressed? Simply, define the background in the XML file as follows. The XML file can change the click state and the normal state of the button.

<?xml version= "1.0" encoding= "Utf-8" ><selector xmlns:android= "http://schemas.android.com/apk/res/" Android "> <item android:state_pressed=" true "android:drawable=" @drawable/btn_bg_selected "/> <item Android:state_focused= "true" android:drawable= "@drawable/btn_bg"/> <item android:drawable= "@drawable/BTN_BG "/> <!--default--></selector>

22, in the previous version of the Honeycomb did not actionbar and a lot of animation style, so you can use Actionbarsherlock and nineoldandroids to replace.

Jake Wharton's Android Open source component is an elaborate masterpiece of backward-compatible APIs. More comforting is that ABS has a powerful function to define Actionbar.

The response speed as a target

23, in the slow running of the mobile phone test.

You'll find a lot of problems on slow-moving phones, even if it makes you mad because no one likes slow programs.

24. Minimize the level of XML layout.

More layers mean that the system will do more work to parse your code, which will make the image more slow to render.

25, with the Android lint inspection procedures.

Right-click on the engineering directory to select Eclipse>android tools>run Lint. It will get some relevant information about the application and can improve the speed of the program, or it can make your code more refreshing.

26, the Android lint can get the error message.

It can give you very detailed information about your code, and you can give a hint before you make a mistake.

27, with <merge> can help you reduce the view hierarchy.

This is an easy way to get rid of unnecessary layers. Good articles explain this, and it's also unusual in Android developer.

28, with Hierarchyviewer can be intuitive to see the level of your layout.

This intelligent tool can show how many levels there are in the layout, and it can be suggested that those can slow down the program.

29, if you can use relativelayout as far as possible.

The absolutelayout has expired, so don't use it. You often encounter a choice between relativelayout and linearlayout, so use Relativelayouot directly, because it allows you to reduce the level of view. For example, you want to implement a view such as:

A Box on the left half of the screen | B box on the right half of the screen

The first thing you want to do is:

 <linearlayout  android:layout_width= "match_parent"  android:layout_height= "Wrap_content"  Android : orientation= "Horizontal" >  <textview   android:layout_width= "0dip"   android:layout_height= "wrap" _content "   android:layout_weight=" 1 "   android:text=" box A takes up left half of the ' screen '/>  < TextView   android:layout_width= "0dip"   android:layout_height= "wrap_content"   android:layout_weight = "1"   android:text= "box B takes up left half to the screen"/> </LinearLayout>

The code is fine, but you can do the same:

 < Relativelayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" Horizontal "> <textview android:layout_width=" match_parent "android:layout_height=" Wrap_content "Android:layo" ut_toleftof= "@+id/dummy_center" android:text= "box A takes up left half of the" "/> <view" android:id= " /dummy_center "android:layout_width=" 0dip "android:layout_height=" 0dip "android:layout_gravity=" center "/> <T Extview android:layout_width= "match_parent" android:layout_height= wrap_content "android:layout_torightof=" @+id/ Dummy_center "android:text=" box B takes up to left half to the "screen"/> </relativelayout> 

The second form is much uglier than the first, and in fact it's pretty bad: we've introduced a whole new element. But if we're going to add a picture to each box, we'll do it in general:
A box on the left half of the screen picture | B box on the right half of the screen picture
With the first method, you have to create a two-level linearlayout, and if you use the second method, you can add a picture directly to the same relativelayout, such as to specify that the first picture must be on the left side of the "Dummy_center" And a TextView a must also be on its left. Then you have to use 7 elements 3 view levels (LinearLayout way), and (Relativelayout way) only 6 elements 2 levels, so all the work is added complete.

30, with some extension tools such as DDMS.

This can help you find unnecessary network calls, view battery usage, garbage collection information, state changes (examples: When callbacks OnStop and OnDestroy), and so on. Littleeye is my favorite tool at the moment.

31, with Asynctasks.

Anroid Engineering team is fed up with people often implement network calls within the UI thread (note: Time-consuming operations, easy to block UI refreshes), so they implement some APIs that generate compile-level error messages. But some of the work that still works in many apps will drag down the UI thread, taking into account the UI layout quickly and the responsiveness of the UI.

Small Target machine space

32, some aandroid equipment has the limit of 100mb space size.

Things have changed now, but there are still a lot of users who are worried about the size of 5Mb apps wasting space. If you can choose to load the app into the SD card, it's not a problem, but you can't load an SD card if your app needs to be in Onboot (example: some form widgets). Even for some new devices, users are happy to download a small apk quickly.

33, with XML resources (I swear last time I have said), this will save a lot of space than the PNG resources.

When you just need a configuration that meets a lot of screen sizes, an XML file can be more space than the PNG province that can do the same thing.

34, if you want to use PNG, the best optimization (with Pngcrush or Imageoptim)

Target Bug

35. Check all bugs that are automatically detected in the Android console.

36, Proguard is now started by default.

Proguard is very useful (increases your app's speed and reduces file size), but it also makes stacktraces very difficult to handle. You will need to track your stacktraces, so you will need to keep the Proguard mapping file created in each build. I put them all in a folder named after the code version number.

37, in order to show the number of lines in the stacktraces, you need to modify the Proguard configuration.

Make sure that your proguard.cfg has the following sentence:
-keepattributes sourcefile,linenumbertable

38, the use of staged rollouts. Test the base user for 5% and observe the bug report.

39, the use of real equipment testing platform.

Device Anywhere and Perfecto Mobile offers a virtual test platform where you can use real mobile devices. I found that they had some bad places, and if they were tested continuously, some bad things would happen. If you work in an office environment, or if you have some friends with Android development, start a "device pool".

40, write more code less blog.

In fact, sharing is love, I just can't think of the 40th article what to write.

Original English: http://opensignal.com/blog/2013/07/30/40-developer-tips-for-android-optimization/

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.