Android applications improve performance and user experience

Source: Internet
Author: User
Excellent user experience has three features: fast speed, timely response, and seamless. The following information helps your application implement these features on Android. 1. Fast speed you can't assume that the mobile phone is as fast as the Desktop System and server, but you need to pay more attention to whether your code is efficient. Two principles should be followed for writing efficient Android code: do not do unnecessary things do not allocate unnecessary memory the following are some tips to achieve this goal (some tips are conflicting with oo principles, consider use cases ): 1. Avoid creating objects. For example, the int array is better than the Integer array. Likewise, this applies to the combination of all basic types. 2. Use local methods instead of using String. indexOf (), String. special implementation methods such as lastIndexOf () (specialty methods ). These methods are implemented using C/C ++. 3. Use the implementation analogy interface to Map myMap1 = new HashMap (); HashMap myMap2 = new HashMap (); calling an interface will take twice as long as calling an object class. 4. You do not need to use getter or setter to directly access the variable. 5. You can cache the member variables to the local for (int I = 0; I <this. mCount; I ++) dumpItem (this. mItems ); It is best to change it to this: Int count = this. mCount; Item [] items = this. mItems; For (int I = 0; I <count; I ++) dumpItems (items); In addition, never call any method in the second condition of 6. Add final to the constant Static int intVal = 42; Static String strVal = "Hello, world !"; The compiler will generate a method called the initialization class. This method will be executed when the class is used for the first time. The method will assign 42 to intVal, and then assign a reference pointing to a common table in the class to strVal. When these values are used in the future, they will be found in the member variable table. Static final int intVal = 42; Static final String strVal = "Hello, world !"; Currently, classes do not need methods because constants are directly saved to class files during initialization of member variables. The code that uses intVal is directly replaced with 42, and strVal points to a String constant instead of a member variable. 7. Use foreach with caution Foreach can be used in the collection type that implements the Iterable interface. Foreach assigns an iterator to these objects and then calls the hasNext () and next () methods. You 'd better use foreach to process the ArrayList object, but for other set objects, foreach is equivalent to using iterator 8. Avoid enumeration. It is very convenient to enumerate variables, but unfortunately it will sacrifice the execution speed and greatly increase the file size. 9. Declare the external variables or methods to be accessed by the internal class within the package range. Public class Foo { Private int mValue; Public void run (){ Inner in = new Inner (); MValue = 27; In. stuff (); } Private class Inner { Void stuff (){ System. out. println (Foo. this. mValue ); } } } Foo $ Inner is a completely independent class. It is illegal to directly access the private members of Foo. The compiler automatically generates a method: /* Package */static int Foo. access $100 (Foo foo ){ Return foo. mValue; } The internal class calls this static method every time it accesses the "mValue" method. Similarly, the same is true for internal classes to access private methods. 10. Avoid using floating point numbers. Embedded processors generally do not support floating-point computing hardware. All the operations on "float" and "double" are implemented through software. We can avoid this problem by changing the variable and function declaration for internal class access from private range to package range. This can make the code run faster and avoid generating additional static methods. (Unfortunately, these member variables and methods can be directly accessed by other classes in the same package, which is contrary to the classic OO principle. Therefore, you should exercise caution when designing this optimization principle) 2. Timely response 1. Submit the time-consuming work to the sub-Thread 2. If your program processes user input in the background, a working prompt (ProgressBar (progress bar) and ProgressDialog (Progress dialog box) are good choices) 3. for a game, place the computing steps in the Child thread Iii. Seamless 1. Do not lose data. inherit the onPause () method. 2. Use ContentProvider to share data 3. Do not interrupt users and use notifications With the development of the mobile phone platform and the improvement of the provided applications, quality has become the most important factor for the success of applications. If those applications cannot provide powerful functions and stable user experience, they will soon be uninstalled by users. Developers must remember that, although the speed of Android smartphones and tablets is growing, their applications are still running in environments with limited resources, its battery and processor performance are still different from those of the latest desktop and laptop computers. The following are some methods to optimize the Running Effect of applications:
Let's first explain some programming skills that make the application responsive.

Tip 1: Start with excellent programming

We need to adopt the operational rules and standard design patterns that have been accepted by users. These long-Used programming rules also apply to Android applications, especially when these applications use internal device services.
For example, assume that the application you write needs to be based on the geographic location service. You only need to start registration when necessary to update the location. When you do not need to update information, make sure that the application stops the update process. This helps reduce the power of the device and the burden on the system processor.

Tip 2: Keep the application flexible
Use AsyncTask, IntentService, or custom background services to maintain application flexibility. The loader is used to simplify the State management of data that has been loaded for a long time, such as the cursor. Applications cannot appear slow or completely static in other processes.
If some operations require a certain amount of time and resources, you should separate the process for asynchronous processing so that your application can run smoothly. Operations that can be performed in this way include disk read/write, access to content providers, databases, and networks, and other tasks that require a long period of time.

Tip 3: Use the latest Android SDK version and API
Keep the app updated and use the latest content provided by the Android platform. With the development of the Android platform, it is gradually improving. Some features are removed or replaced with better options. The vulnerability in the core API has been fixed, and the performance of the entire API has been improved. This platform has introduced new APIs such as loaders to help developers write more stable and responsive applications.
Android 3.0 Applications Support Hardware acceleration, which can be applied. It should be understood that the best performance will change over time. Wise developers will update the latest content and APIs released by the platform.

Tip 4: Check Strict Mode
You can use the Android API called "StrictMode" to find programming problems. StrictMode helps you identify whether the application is consuming memory, or you can check whether the application is trying to perform long modular operations.
StrictMode (Note: android. OS. StrictMode) is released in the same period as Android 2.3.

Tip 5: Disable or minimize debugging and diagnosis before release
You may build some debugging code in Android application development. Ensure that these features are minimized or completely disabled before the application is released.
Next, let's discuss how to use excellent User Interface Design Principles to make your application load faster.

Tip 6: Keep the layout simple and natural
The concise and natural layout will speed up loading. Do not fill the screen layout with excessive unnecessary content. Spend some time developing simple user interfaces that users can effectively use. Do not put too much functional content into a single screen. This not only helps the application performance, but also helps users use the application more effectively.
The split content helps to divide User Interface functionality without sacrificing the flexibility of applications on different devices.

Tip 7: Adjust application resources based on the target device
Adjust resources based on specific device configurations so that they can be effectively loaded. This is especially important in terms of image resources. If your application has large image resources that need to be loaded, make adjustments.
Another trick is to keep the application package file size appropriate when targeting many devices. You only need to include the core resources required for running the application, then, let the user download other content of the application based on the specific device.

Tip 8: Use Hierarchy Viewer
The Hierarchy Viewer tool helps you remove vulnerabilities in the application layout. It also provides a lot of valuable information, such as how long each View takes to control. Find the domain to which the problem belongs, which makes it easier to solve the problem.

Tip 9: Use the layoutopt Tool
The layoutopt tool is a simple command line tool that helps you identify unnecessary controls and other things that make your layout resources crash and improve its performance. It helps you find unnecessary layout control. The application running performance can be optimized in a relatively small and shallow layout.
Finally, test the application when you think it is the best.

Tip 10: Use Traceview and Other Android app compression tools
The Android SDK has many tools that can compress applications. Traceview is probably the most popular tool. This image tool can help you debug and locate performance problems of applications.

Conclusion
There are currently many ways to accelerate the running of your Android app. Some involve some specific algorithm rules, others rely on some real debugging and Operation Supervision technologies. There are many free tools available on the Android platform to help track and adjust performance issues in applications. You have learned the above 10 skills and can try them now!
As I am currently working in a professional online game company, I need to use some methods to streamline and optimize the online game code currently in operation, you need to use an excellent viewing tool-Android TraceView provided in the Android sdk. The following describes the implementation steps and notes! What is TraceView? Let's take a look at Baidu's explanation:Traceview is a good performance analysis tool on the android platform. It allows us to understand the performance of the program we want to track in a graphical way, and can be specific to the method.Traceview usageFirst, you must add code to the program to generate a trace file. With this trace file, you can convert it into a graph.The code to be added is as follows:Java code// Start tracing to "/sdcard/yourActivityTrace. trace"Debug. startMethodTracing ("yourActivityTrace ");//... // Stop tracing Debug. stopMethodTracing ();// Start tracing to "/sdcard/yourActivityTrace. trace" Debug. startMethodTracing ("yourActivityTrace ");//... // Stop tracing Debug. stopMethodTracing ();Google Dev Guide says you can add Debug in onCreate () of the activity. startMethodTracing (), and add Debug in onDestroy. stopMethodTracing (), but we found that this method is not useful in actual tests, because the onDestroy () of our activity is usually determined by the system when to call, therefore, the trace file may not be obtained for a long time. Therefore, we decided to call Debug. stopMethodTracing () in onStop (). In this way, when we switch to another activity or click the home Key, onStop () will be called, and we can get the complete trace file.Before running the program, make sure that our AVD is an AVD with an SD card so that the trace file can be saved to/sdcard. You can perform any operation after the operation, and then click the home Key. Here, we can see a trace file under the/sdcard/directory through DDMS file explore. Now we copy this file to the specified directory on the computer, assuming it is under the C:/tracefile directory.You can run traceview through the command line. after entering the tools directory, executeTraceview C:/tracefile/yourActivityTrace. traceThen you can see the graph. The next step is to analyze the graph according to the explanation in the Google Dev Guide. The following describes how to implement and what you need to pay attention: The implementation steps are divided into three steps: 1. You must first create an sdCard in our simulator; 2. embed our debugging code into the project; 3. Use TraceView to observe and analyze the Code; 1. Write two methods for creating the sdCard of the simulator:First: When you create an avd in eclipse, you can select an Sd Card option under the api. The first option is the size of the created sdcard.


Type 2: cmd command! Open cmd and cd to the android sdk tool Path. (or configure the sdk tool Path in the environment variable Path and then re-open cmd.) Use mksdcard-l mycard 1024 m f: /mysdcard. img creates a 1 GB sdcard. Use emulator-avd my_android-sdcard F:/mysdcard. img activates sdcard! Finally, add-sdcard F:/mysdcard to eclipse Preferences --> Android --> Launch. img (this step is to add sdcard support in the first method of creation) Note 1: If the space allocated by sdcard is too small, the program Tracing file will be recorded until the sd debit card capacity is slow, therefore, it is important to generate an appropriate SD memory card for the program before debugging, because the longer the program runs, the larger the Tracing file. Note 2; (if emulator: ERROR: the user data image is used by another emulator appears in the second activation in the Second Creation Mode. aborting, disable the simulator, or enter the Directory:/Documents and Settings/user /. android/AVD/* Device */(for example, my directory is C:/Documents ents and Settings/Administrator /. android/avd/android2.0.avd) and then delete it. the folder at the end of lock (I will explain why to delete these files, in fact. lock is a lock. If the program crashes or other causes, it cannot be cleared. this problem occurs in the folder at the end of lock, that is, the avd lock is not released, causing avd manager to think that the avd is in use .)) 2. embedding our debugging code into the project is just like what Baidu has explained. Add Debug at the beginning of the program running. startMethodTracing ("yourActivityTrace"); then call Debug in onPause. stopMethodTracing (); why do you want to write the end in onPause () instead of onStop ()? If you look at the api, you will see that the Api introduces onPause () it will be triggered after you return and click the home button, while onStop () is generally triggered by the system. When the program is in the background, and when the memory is tight, it may be called, but it may never be called! Note: Do not run the project immediately after adding the debugging code to the project, but must be in AndroidMainfest. the following code defines "Write SD card Permissions" in xml: <uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE "> </uses-permission> because our debugging code generates a Tracing file in the SD card, that is, data is written to the SD card, a permission must be declared. Note the following!

3. run the project and exit the project to get the Tracing file, and use TraceView to analyze the code running status: when the project runs normally and click return or home, an SDK is generated. trace file. The sdcard directory is under eclipse. CLICK: windows-show view-other-android-File explorer.

There are two arrows in the upper right corner. The first one is to export files from the simulator sdcard, the second one is to import files from the PC to the sdcard, and the second one is to delete the files ..... then we run the generated trace file traceview C:/name in cmd and place the path of the trace file on disk C, I cannot open traceview normally on disks other than drive C. I don't know why. Name indicates the generated. trace file. You do not need to enter the suffix ". trace" during cmd. Then, the TraceView analysis window appears. [cmd command! Open cmd and cd to the android sdk tools Path. (or configure the sdk tool Path in the environment variable Path and re-open cmd.) Note 1: if this memory overflow problem occurs;

Solution: Find traceview under tools under SDK. bat file, right click-Edit (or open notepad), and replace the last line with the following: call java-Xms128m-Xmx512m-Djava. ext. dirs = % javaextdirs %-jar % jarpath % * Note 2: If the path is incorrect, for example, my himi. if the trace is on drive c, my cmd command is: traceview c:/himi and press Enter! But be careful here, because/h may be considered as an escape character !!! To avoid using h, n, r, t, and so on as much as possible, this problem can be completely avoided, for example, my C drive himi. trace file, which can be written as traceview c: // himi when writing the cmd command ~ Pay attention to the details. OK. Next, let's talk about how to improve the efficiency of Android, that is, how to optimize the performance of Android: 1. http is compressed with gzip, set connection timeout and response timeout. http requests are divided into cache and non-cache based on service requirements. In a network-less environment, some data is still browsed through the cached httpresponse, offline reading. 2. listview performance optimization 1). Reuse convertView in getItemView to determine whether convertView is empty. If it is not empty, it can be reused. If you need to add listerner to the view in couvertview, the Code must be out of if (convertView = null. 2 ). if the image item contains a webimage, it is best to load it asynchronously. 3 ). the image is not displayed during quick slide. when the list is quickly swiped (SCROLL_STATE_FLING), the image in the item or the view that consumes resources can be retrieved and not displayed; in the other two States (SCROLL_STATE_IDLE and SCROLL_STATE_TOUCH_SCROLL), the views are displayed 4 ). baseAdapter prevents memory overflow. If the entity class of BaseAdapter has attributes that consume a lot of memory, it can be saved to files. To improve performance, it can be cached and the cache size can be limited. 3. the thread pool is used, which can be divided into the Core Thread Pool and general thread pool. The time-consuming tasks such as downloading images are placed in the General thread pool to prevent time-consuming tasks from blocking the thread pool, as a result, all asynchronous tasks must wait 4. asynchronous tasks are divided into core tasks and common tasks. errors are reported only when system errors occur in core tasks. The ui operation of asynchronous tasks needs to determine whether the original activity is active. avoid using static member variables to reference instances that consume too much resources, such as Context6. use WeakReference instead of strong references. Weak references allow you to retain references to objects and allow GC to release objects when necessary, reclaim memory. For those objects that create cheap but consume a large amount of memory, that is, you want to keep the object and use it when the application needs it. If you want GC to recycle it when necessary, you can consider using weak references. 7. super fat Bitmap timely destruction (bitmap is recycled when onDestroy of Activity is used by the UI component. RuntimeException: Canvas: trying to use a recycled bitmap android will be thrown after being recycled immediately by the UI component. graphics. bitmap) sets a certain sampling rate (sampling is not required for images provided by developers. For images uploaded by users or uncontrolled by third parties, sampling can be performed to reduce the memory occupied by images ), when returning images from the server, we recommend that you use soft references to the resid resources of the drawable image. bitmap corresponds to any type of images of other resources. If it cannot be obtained (for example, the file does not exist, or when an OutOfMemory exception is run during file reading, there should be a corresponding default image (the default image is placed in the apk and obtained through resid); 8. ensure that the memory occupied by Cursor is promptly released, rather than waiting for GC to process. Android obviously prefers programmers to manually close the Cursor. 9. The thread is also an important source of Memory leakage. The main cause of thread Memory leakage is the uncontrollable thread lifecycle 10. if the ImageView image is from the network, perform asynchronous loading 11. during custom View development, do not write the interaction part as a thread to refresh the interface display constantly. Instead, update the interface automatically triggered Based on the TouchListener event 12. the image used by the Drawableui component is included in the apk package. Therefore, setImageResource or setBackgroundResource is used instead of resourceid. Note: get (getResources (), R. drawable. btn_achievement_normal) This method is converted to drawable through resid. You need to consider the recycling problem. If drawable is a private object of the object, the memory will not be released before the object is destroyed. 13. reuse and Recycle Activity objects temporary activity timely finish main interface set to singleTask general interface set to singleTop14. location information to get the user's geographic location information, when you need to get data turn on GPS, then close it in time. in onResume, set the power management on this interface, and cancel the setting in onPause.

 

Reprinted address

Android applications improve performance and user experience
Http://www.apkbus.com/android-62887-1-1.html

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.