40 optimization suggestions for Android Developers and 40 android Developers

Source: Internet
Author: User

40 optimization suggestions for Android Developers and 40 android Developers

From: http://blog.csdn.net/zhang3776813/article/details/38518509

The following is a good way to start Android programming: Find some code similar to what you want to do, and try to make it do what you want to do. Use StackOverflow to solve the problem.

Repeat the above process for each feature you add. This method can motivate you, because you have learned a lot while keeping on iteration. However, when you release an application, you need to do more in-depth things.

From some code that can work properly to a terrible application is a huge jump, especially for Android on iOS platform. When releasing apps on iOS, you just jump on a device-your phone-similar to many devices-a screen of the same size has good hardware, 95% run the same version of the operating system. This is not the case in Android applications.

Your program must be able to handle everything from screens, processors, custom operating systems, API levels, and any other specific device.

This is my personal suggestion for making Android apps more comfortable.

Target screen size and Solution

In the Android world, there are more than 100 different screen sizes, but there are also a wide range of solutions. There are two things you need to determine to adapt your application to different screen configurations: You have a good layout and structure for different screen sizes, and your images work well at different resolutions.

These are independent tasks. You may have a super tablet layout, but the figure above looks terrible. We will discuss them in sequence.

Design for different screens 1. It is usually done with ScrollView and ListView

When we have a series of big screen mobile phones of different sizes, the biggest difference between them is the screen height. Therefore, ScrollView and ListView work effectively, although sometimes they cannot completely overwrite all the screens. Under the Dashboard label in OpenSignal, we can see that all parts are in one breath and there is no slide. For many advanced labels, slide display is not necessarily a bad thing. If you can match all your designs to a variety of screens, it is better. Otherwise, these two controls allow you to use the minimum development cost to ensure that your software is normally displayed on most screens.

Scroll is not required for Dashboard style design.

2: Use folders. the resource folder structure of Android is very powerful. It allows developers to store different images, strings, layout files, shapes, colors, and other resources in api, code, screen size, and other parts. the following is an example of how to do this in the resource Folder:

A bools. xml file is stored in the values-small folder. The file contains the following lines of code: 123 true

In the code, I can reference 123if (getResources (). getBoolean (R. bool. small_screen) {getsuppactionactionbar (). hide ();}

In small-size devices, the boolean value will be set to true. Therefore, the ActionBar will save space. this code is part of the extraordinary ActionBarSherlock extension library and will be detailed later. in the values-sw360dp folder, store the resource files with a screen width of DP. In the same position as above, the following code is 123 false.

For a large screen, the ActionBar is set to display status.

I do not need to set bools. the xml file is placed in the values-sw400dp folder, because the operating system will automatically search by the corresponding path. for example, a device with a width of 600/160 dp (3.75 inch =, which is what we call a 7-pack) the operating system will search for bools in the values-sw600dp and its contained folders. xml file, search for the values-sw400dp folder if not found, search for the values-sw360dp folder, and so on.

Suggestion 3: 160dp = 1 inch. 320 dp = 2 inch. Dp = dip

Suggestion 4: You can use these directory structure techniques to handle all resource types **. For example, you can use the specified system directory name for your XML layout.

To solve this problem, such as: layout-sw360dp directory can match the target width is 360dp machine. If you want to support horizontal and vertical screen layout switching, you can use the following directory:

Layout-sw360dp-land

Layout-sw360dp-port

Don't worry. Half of you speak Arabic? Change the layout name to the following format:

Layout-sw360dp-land

Layout-sw360dp-port

Layout-sw360dp-land-ar

Layout-sw360dp-port-ar

The first two can be used in all languages, and-ar represents Arabic.

Suggestion 5: Resource rule introduction:

XXX // example: No directory name is added: default-applicable to Nexus One, Droid 2, S2

XXX-sw360dp // relatively large phone-Galaxy Nexus, S3, S4

XXX-sw600dp // 7 Tib flat

XXX-sw720dp // 10 "Tablet

The Kindle devices are somewhat different, as shown below:

XXX-large-mdpi // kindle fire 7 found 〃

XXX-large-hdpi // kindle fire 7 platinum HD

Recommendation 6: if you do not want to crop all layout files, you can use the dimens. xml file **. If you pay attention to my article above, you will notice that there are many dimens in my values directory. xml, because I prefer layout. set the value in xml. I like this in every layout file: 12345678910111213 small_margin is in dimen. the xml file defines 4dp.

The 4dp variable is in all dimen files. I have an Excel file that creates all the sizes required based on different factors. Maybe you will ask: why not let android OS handle all sizes? Why not? Why don't we use a values directory and a layout directory to replace all written dead values? Yes, of course. If you set it properly, you will get all the sizes, but some elements do not look so good in size.

Suggestion 7: Make the blank space greater than the image space. Make the image space larger than the button size. If you select multiple buttons, it is ugly to zoom in the control. A 0.63 Dip (1.25 ") button does not want to display the original Dip (") twice the width on the tablet. the reason is that the screen has become larger, which does not mean that the tablet is used by giants. We can do this by adding a blank space in the space added by the button and the extended image space.

Recommendation 8: Use the GraphicalLayout tool to quickly Preview data. GraphicalLayout is the wysiwg xml editor. I like to write elements directly-instead of dragging and dropping visible programming methods. However, after adding some elements, you can select different screen sizes from the GraphicalLayout drop-down menu for testing.

There are many options for you to choose from.

Image Scaling

Recommendation 9: Do not scale all images. Using layout files to adapt to different screen sizes is only half the success. The layout elements (such as images) must work well on high-resolution screens. A simple concept is to create a complete set of image directories and match them with many drawable directories.

Drawable-sw600dp-ldpi

Drawable-sw600dp-mdpi

Drawable-sw600dp-hdpi

Drawable-sw600dp-xhdpi

Drawable-sw600dp-xxhdpi

... Others are similar.

Do not do this:

Don't trust your books too much.

In general, directories such as drawble-ldpi and drawable-hdpi are enough.

Suggestion 10: Avoid using Bitmap (jpg, png ). For some icons, using bitmap is a good choice, because they are easy to use. However, if you can avoid using bitmap, you can save a lot of space. However, different methods can also achieve good results.

Recommendation 11: draw data in XML format. Bitmap can be replaced by XML plotting. XML plotting is not omnipotent, but its convenience is still surprising to me.Android development documentationFor details, here is a simple example: 1234567891011121314151617

A rounded rectangle and a gradient side (dark blue) are defined here ). You can reference the layout file anywhere, and it can adapt to any screen. You can use it to make the desired button.

Suggestion 12: use more XML for plotting. Let's introduce an example of how to use XML plotting to make you more excited. The following radar background looks more complicated:

Without bitmap, there is no harm to your UI (except icons ).

Suggestion 13: still use more XML plotting (if necessary, use Bitmap ). So how can we build a cool icon for the weather signal-let the light bulb dynamically fill in based on the intensity of light, and how can we click the pointer to let it rotate? Here we use bitmap and XML to make an example:

We use a PNG Image: icon_magnitude_min (an empty light bulb) and icon_magnitude_max (a light bulb). Then we dynamically crop the latter. To achieve this goal, I did this: 123456789101112

In the java program, I will get a reference to the paper clip, and then I can use it to control the light intensity.

Recommendation 14: Why use 9-patch (when you can use XML drawables )? Android uses 9-patches to define the choice of drawables. Some tutorials explain how to use them as a button, in this way, several corners can be kept unchanged during Stretching (and pixel processing is avoided ). If you already know how to use 9-patches, it may be learned from web design, so they may be worth using. If you are not familiar with 9-patches, I suggest you keep it as it is. If you want to adapt to something, such as the arc or color of the corner, creating nine small pieces is more involved than creating bitmap, it is like returning to the era of image editor. Many results obtained using 9-patches can also be obtained through XML.

Suggestion 15: overwrite onDraw () to create custom views. XML is not very good at some things. We have painted many images in OpenSignal and WeatherSignal. For this reason, there are many libraries, but we need to write code for custom images. This is interesting. You may never need to do this, but this is often the only way to make the image highly dynamic and custom.

Suggestion 16: Use SVG where XML cannot be used. Sometimes it is too technical to override onDraw () and write code for custom views to draw the lines and arcs required. After all, there is a vector image language called... Scalable Vector Graphics (Extensible Vector Graphics ). It is also the power source of Androidify, one of the coolest Android apps in history. In fact, they created this library for that application. They published it here: SVG for Android. This is what we use to draw a dashboard in OpenSignal.

Recommendation 17: compress the SVG file GZip to make them smaller and process them faster.

Suggestion 18: the SVG library does not support everything. It does not seem to work properly in some specific alpha channels, and you even have to remove them in code.

Achieve consistent display in all android versions

Recommendation 19: In some android systems (such as TouchWhizz/HTC Sense/MotoBlur), the default buttons and other UI components will look very different from those in the native system. ** I hope this is not true, but it is true.

Suggestion 20: Customize your UI components. To ensure that your app looks consistent across all devices, you will need to customize everything. This is actually not as difficult as you think. As long as you do, you will be able to better grasp the display appearance of your app.

Recommendation 21: Selectors is a powerful tool for creating buttons. We mentioned how to define the background of the button in XML, but how do you create a button that will change when you press it? Simple: Define the background in the xml file as follows. The xml file receives the current status of the button and changes its appearance accordingly. 123456 <? Xml version = "1.0" encoding = "UTF-8"?>

Recommendation 22: In versions earlier than Honeycomb, there are no ActionBar and many animation styles. Therefore, you can use ActionBarSherlock and ** NineOldAndroids instead. The Android open-source components written by Jacob Wharton are well-developed and compatible. What's even more surprising is that ABS has powerful functions to define ActionBar.

Speed as the target

Recommendation 23: run the test on a slow mobile phone. You will find many problems on slow mobile phones, and it will drive you crazy, no one will like to run slow programs.

Recommendation 24: Minimize the XML layout level. More Layers mean that the system will do more work to parse your code, which will make image rendering slower.

Suggestion 25: Use Android Lint. Right-click the project directory and choose Eclipse> Android Tools> Run Lint. It will get some information about the program and increase the running speed of the program, or it will make your code more fresh.

Recommendation 26: Android Lint can get the error message. It provides detailed information for your code and prompts you before an error occurs.

Recommendation 27: helps you reduce the view hierarchy. This is a simple way to remove redundant layers. All the good articles have some explanations for this, and it is also distinctive in Android Developer.

Suggestion 28: Use HierarchyViewer to intuitively view the layers of your layout. This Smart tool shows how many layers of the layout are, and shows which ones can slow down the program.

Recommendation 29: If you can try to use RelativeLayout **. ** If AbsoluteLayout has expired, do not use it. You may often choose between RelativeLayout and LinearLayout, so use RelativeLayouot directly, because it can reduce the view level. For example, you want to implement the following view:

Box A is at the left half of the screen | Box B is at the right half of the screen

First, you will think of this:

00001.LinearLayout

00002. 

00003.Android: layout_width = match_parent

00004. 

00005.Android: layout_height = wrap_content

00006. 

00007.Android: orientation = horizontal

"That works just fine, but you coshould also use:

00001.RelativeLayout

00002. 

00003.Android: layout_width = match_parent

00004. 

00005.Android: layout_height = wrap_content

00006. 

00007.Android: orientation = horizontal"

00008. 

00009.View

00010. 

00011.Android: id = + id/dummy_center"

00012. 

00013.Android: layout_width = "0dip"

00014. 

00015.Android: layout_height = "0dip"

00016. 

00017.Android: layout_gravity = "center "/"@

The second form is much more ugly than the first one. In fact, it is quite bad: We have already introduced a complete new element. But if we want to add an image to each box, we generally do this:

Box A is at the left half of the screen | Box B is at the right half of the screen

In the first method, you have to create a LinearLayout with two layers. If you use the second method, you can directly add images to the same RelativeLayout, for example, to specify the first image, it must be on the left of "dummy_center" and A TextView A must be on the left. Then you have to use seven elements and three view layers (in the LinearLayout mode), and (in the RelativeLayout mode) only use six elements and two layers, so that all the work can be added.

Suggestion 30: use some extension tools such as DDMS. This helps you discover unnecessary network calls, view battery usage, garbage collection information, and status changes (for example, when onStop and onDestroy are called back. LittleEye is my favorite tool.

Recommendation 31: Use AsyncTasks. The Anroid engineering team is fed up by people who often implement network calls in the UI thread (Note: time-consuming operations, easily blocking UI refresh), so they have implemented some APIs that can generate compilation-level error messages. However, some work in many apps will drag down the UI thread. We need to consider the UI layout to be fast and improve the UI responsiveness.

Small Target machine Space

Suggestion 32: Some Aandroid devices have a size limit of MB. The situation has changed, but many users still worry that 5 MB apps will waste space. If you can mount the app to the SD card, this is not a problem, but if your app needs to be started in onBoot, you cannot mount the SD card (example: such as some form widgets ). even for some new devices, if you can quickly download a small APK, the user is still very happy.

Suggestion 33: use XML resources (I swear I have already reminded you), which saves a lot of space than PNG resources. When you only need a configuration that can meet a lot of screen sizes, an XML file saves space than PNG that can implement the same function.

Recommendation 34: If you want to use PNG, you 'd better optimize it (use PNGCrush or ImageOptim)

Target bugs

Suggestion 35: Check all automatically detected buckets on the Android developer console.

Suggestion 36: ProGuard is currently started by default. Proguard is too easy to use (increase your app speed and reduce the file size), but it also makes StackTraces very difficult to handle. You will need to retrack your StackTraces, so you will need to keep the proing file of Proguard created in each build. I put them all in the folder named after the code version number.

Suggestion 37: to display the number of rows in StackTraces, You need to modify the ProGuard configuration. Make sure your proguard. cfg has the following sentence:

-Keepattributes SourceFile, LineNumberTable

Suggestion 38: Use staged rolouts. Test 5% of basic users and observe the bug report.

Recommendation 39: Use a real device testing platform. Device Anywhere and Perfecto Mobile provides a virtual testing platform where you can use real Mobile devices. I found that they were clumsy. Joining continuous tests could lead to some bad situations. If you work in a joint office environment or have friends who are developed by Android, start a "device pool.

Suggestion 40: write more code and write less blogs. Actually, no. Sharing is caring. I just don't know what to write in 40th.




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.