My Android advanced tour ------ & gt; 40 optimization suggestions for Android Developers

Source: Internet
Author: User

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:

<resources><boolname="small_screen">true</bool></resources>


if(getResources().getBoolean(R.bool.small_screen)){getSupportActionBar().hide();}


<resources><boolname="small_screen">false</bool></resources>


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.

Suggestion 5: Resource rule introduction:

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

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 values in xml. I like this in every layout file:

<ImageViewandroid: Photo = "true" android: layout_marginTop = "@ dimen/small_margin" android: layout_width = "@ dimen/dashBoardWidth" android: layout_height = "@ dimen/dashBoardHeight: id = "@ + id/dashboard"/> small_margin is in dimen. <resources> <dimenname = "small_margin"> 4dp </dimen> </resources>


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.



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-mdpi
Drawable-sw600dp-hdpi
Drawable-sw600dp-xhdpi
Drawable-sw600dp-xxhdpi
... Others are similar.

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. The Android Development Documentation provides a detailed introduction. Here is a simple example:

<shapexmlns:android="http://schemas.android.com/apk/res/android"android:shape="rectangle"><cornersandroid:bottomRightRadius="14dp"android:bottomLeftRadius="14dp"android:topLeftRadius="14dp"android:topRightRadius="14dp"/><gradientandroid:startColor="@color/off_white"android:endColor="@color/pale_yellow"android:angle="270"android:type="linear"/><strokeandroid:width="4dp"android:color="@color/osm_darkerblue"/></shape>


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:

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:

<layer-listxmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:drawable="@drawable/icon_magnitude_min"/><item><clipandroid:clipOrientation="vertical"android:drawable="@drawable/icon_magnitude_max"android:gravity="top"/></item></layer-list>


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.

Recommendation 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: perform operations on SVG filesGZip Compression. Make them smaller and they will process faster.

Suggestions18: the SVG library does not support everything. It seems that some specific alpha channels cannot work normally, and you even have to remove them in code.

Achieve consistent display in all android versions

Recommendation 19: In some android systems (for exampleTouchWhizz/HTC Sense/MotoBlur, etc.), 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.

<?xmlversion="1.0"encoding="utf-8"?><selectorxmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:state_pressed="true"android:drawable="@drawable/btn_bg_selected"/><itemandroid:state_focused="true"android:drawable="@drawable/btn_bg"/><itemandroid:drawable="@drawable/btn_bg"/> <!-- default --></selector>


Recommendation 22: In versions earlier than Honeycomb, there are no ActionBar and many animation styles, so you can useActionBarSherlock andNineOldAndroids.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.

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: <merge> 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: Use RelativeLayout whenever possible.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:

<LinearLayoutandroid:layout_width=”match_parent”android:layout_height=”wrap_content”android:orientation=”horizontal”><TextViewandroid:text=”Box A takes up left half of the screen”android:layout_width=”0dip”android:layout_height=”wrap_content”android:layout_weight=”1″/><TextViewandroid:text=”Box B takes up left half of the screen”android:layout_width=”0dip”android:layout_height=”wrap_content”android:layout_weight=”1″/></LinearLayout>That works just fine, but you could also use:<RelativeLayoutandroid:layout_width=”match_parent”android:layout_height=”wrap_content”android:orientation=”horizontal”><TextViewandroid:text=”Box A takes up left half of the screen”android:layout_width=”match_parent”android:layout_height=”wrap_content”android:layout_toLeftOf=”@+id/dummy_center”/><Viewandroid:id=”@+id/dummy_center”android:layout_width=”0dip”android:layout_height=”0dip”android:layout_gravity=”center”/><TextViewandroid:text=”Box B takes up left half of the screen”android:layout_width=”match_parent”android:layout_height=”wrap_content”android:layout_toRightOf=”@+id/dummy_center”/></RelativeLayout>


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 already reminded me)This 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 achieve the same function.

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

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.

Recommendation 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.