Some important knowledge points of Android development online [3]

Source: Internet
Author: User
Tags time in milliseconds gdb debugger android games

31. View and surfaceview

In Android games, the display class is mainly used in addition to the control class. In j2s, we use display and canvas to implement the display class. In Google Android, the display class is used, display and game logic processing are important and complex in android game development. Here we will talk about Android. View. View and Android. View. surfaceview. Surfaceview is a display class derived from the view base class. Its direct sub-classes include glsurfaceview and videoview. It can be seen that Gl, video playback, and camera cameras generally use surfaceview. What are the advantages? Surfaceview can control the surface format, such as the size and position of the display on the screen. The most important thing is to provide the surfaceholder class, which is obtained using the getholder method and related to canvas lockcanvas ()
Canvas lockcanvas (rect dirty), void removecallback (surfaceholder. callback callback), void unlockcanvasandpost (canvas) controls graphics and painting, while in surfaceholder. in the callback of the callback interface, you can use the following three abstract classes to define specific implementations, such as the first change of the format and display screen.

Abstract void surfacechanged (surfaceholder holder, int format, int width, int height)
Abstract void surfacecreated (surfaceholder holder)
Abstract void surfacedestroyed (surfaceholder holder)
For surface-related applications, the android underlying layer also provides GPU acceleration. Therefore, surfaceview is generally used in highly real-time applications rather than directly built from view, at the same time, the glsurfaceview in OpenGL mentioned later in android123 will also be implemented from this class.

32. Read-only for memory management of Android apps

Many developers come from j2-based or J2EE and do not have a good understanding of memory usage. The Android Development Network provides some architectural guidance for you, prevent the occurrence of the bean curd residue project. Android, as an intelligent Platform Based on Java language, is required to understand the memory management mechanism of Android programs for developing high-performance and quality software. There is no major difference between the Dalvik Vm of Android and Sun JVM in terms of the basic aspect. It is only the optimization of bytecode. We need to know when to use GC, when to use recycle, and whether to use finalization, because Java only needs to release memory that new developers do not need to display for memory allocation, but this leads to a higher chance of Memory leakage.

1. For general developers, you need to understand the four reference methods of Java, such as strong reference, soft reference, weak reference, and virtual reference. Some Complex programs may encounter exceptions similar to outofmemoryerror during long-term operation.

2. don't count on GC too much. The unused objects can be set to null. For example, OBJ = NULL. Here, android123 prompts you that Java GC uses a directed graph, determining whether an object is valid depends on whether other objects can reach the vertex of this object. The overhead of a directed graph is imaginable relative to a linked list or binary tree.

3. android can use the totalmemory () freememory () method of the runtime class to obtain some memory information of the VM. For the heap memory of the system, you can use Dalvik. the getminimumheapsize () method of the vmruntime class obtains the minimum available heap memory. It also shows that releasing soft references can call the gcsoftreferences () method of the class to obtain more running memory.

4. For multi-threaded processing, if there are many concurrent threads and frequent creation and release at the same time, you can solve the efficiency bottleneck of thread creation through the concurrent thread pool.

5. Do not create too many local variables in the loop.

For System Performance Analysis of Android and Java, android123 will detail how to debug Java to Analyze memory leakage and how to analyze the gdb debugger on Android to improve the memory performance.

33. embedded font in Android for personalization

In Android, our applications can flexibly embed their own font files to enable normal display of personalized text on various mobile phones. We all know that the settypeface method of textview can set the display characteristics of the target text, such as font, color, bold, and italic. We can directly find a truetypefont font file named. TTF. for Win32 users, you can find a lot in the Windows/fonts folder. For example, is good, but the size is too large. Because the android assets class has a size limit of 1 MB for a single file, we should first find an English font for testing. Here we place the font file android123.ttf In the fonts directory of the assets folder of the project.

Typeface TF = typeface. createfromasset (getassets (), "fonts/android123.ttf ");
Textview TV = (textview) findviewbyid (R. Id. Text );

TV. settypeface (TF); // sets the textview style.
TV. settext ("cwj test ");
TV. settextsize (12 );
TV. settextcolor (color. Red );

34. Get and set the selection items of listview

Obtain the selected int curpos = listview. getfirstvisibleposition (); of course, you can also use the getitematposition (INT NPOs) method to set the current selected position listview. setselectedposition (lastpos); this method can be used for controls such as listview Based on the abslistview class.

35. Android. Text. Format File Size and Date Parsing class

Many netizens may directly port their own j2's projects to the Android platform. In fact, Google provides us with the file size and time and date parsing class, which is located in Android. text. in the format package, it provides a powerful standard resolution method:

1. IP Address Resolution class in Android. text. format. the string formatipaddress (int addr) method is provided in formatter to easily convert the int type in the socket to an IP format similar to 127.0.0.1. Note the byte sequence of the Linux platform, that is, little-Endian is available in small-byte order and Low-byte order.

2. users who are careful about file size parsing may also see android. text. format. formatfilesize method in formatter. This method is string formatfilesize (context, long number). The second parameter is the long type. It is generally the method of the last modification time or creation time of the file object, returns a string of 20 MB, which is a string of 12 kb and 5 bytes.

3. date and Time parsing class, which is located in Android. text. format. in the dateformat package, this class provides three time objects in Java. android123 prompts you that the following three methods can be called directly in static mode:

Final Static charsequence format (charsequence hour, date indate) // input a date object
Given a format string and a date object, returns a charsequence containing the requested date.

Final Static charsequence format (charsequence seconds, calendar indate) // Calendar Object
Given a format string and a Calendar Object, returns a charsequence containing the requested date.

Final Static charsequence format (charsequence seconds, long intimeinmillis) // long object
Given a format string and a time in milliseconds since Jan 1, 1970 GMT, returns a charsequence containing the requested date.

We may see that the first parameter is bytes, which is a string type of the charsequence interface. It provides a flexible time format to parse the string description. Android Development Network prompts you to pay attention to Case sensitivity, as shown in figure

In the example of April 6, 1970 at AM, the write method of the handler parameter and the final execution result are as follows. The following uses the cwj birthday of android123 as an example:

"Mm/DD/yy H: MPAA"-> "11/03/87 am"
"Mmm DD, yyyy H: MPAA"-> "Nov 3, 1987 am"
"Mmmm DD, yyyy H: MPAA"-> "November 3, 1987 am"
"E, Mmmm DD, yyyy H: MPAA"-> "Tues, November 3, 1987 am"
"Eeee, Mmmm DD, yyyy H: MPAA"-> "Tuesday, Nov 3, 1987 am"

You can use the static Boolean is24hourformat (context) method of the android. Text. format. dateformat class to determine whether a time is 24-hour.

36. Android code performance optimization skills

At present, the JIT performance of Android 2.2 has been substantially improved. However, for older versions of programs that improve Java execution efficiency, there are still many language features. Today, android123 does not mention syntactic sugar, it is a basic problem, which will be significantly improved after Java 1.5. The following example is from the SDK:

Static class Foo {
Int msplat;
}
Foo [] marray =...

The execution results and performance of the above static class Foo are compared in three methods: zero, one, and two.
Public void zero () {// Most people may simply write it like this
Int sum = 0;
For (INT I = 0; I <marray. length; ++ I ){
Sum + = marray [I]. msplat;
}
}
Public void one () {// improve performance through local objects
Int sum = 0;
Foo [] localarray = marray;
Int Len = localarray. length;
For (INT I = 0; I <Len; ++ I ){
Sum + = localarray [I]. msplat;
}
}
Public void two () {// recommended method. The performance can be greatly improved through the new syntax feature of Java 1.5.
Int sum = 0;
For (foo a: marray ){
Sum + = A. msplat;
}
}

Zero ()Is slowest, because the JIT can't yet optimize away the cost of getting the array length once for every iteration through the loop.

One ()Is faster. It pulls everything out into local variables, avoiding the lookups. Only the array length offers a performance benefit.

Two ()Is fastest for devices without a JIT, and indistinguishable fromOne ()For devices with a JIT. It uses the enhanced for loop syntax introduced in version 1.5 of the Java programming language.

37. Android Development notes Part One

Android has many details of the problem we through the platform development summary constantly improve this list, if you have related content can contact android123@163.com.

I. assetmanager-it is known that the processing of a single file cannot be greater than 1 MB. Therefore, if the resources are large, we recommend using zip compression for storage.

2. Embed listview in scrollview-This method may show that your listview only displays one row and a half.

3. the zip processing class provided by Android cannot identify the file name encoding and does not provide the display setting method. It is written to zlib.

4. Use some resource objects to remember to close, such as the last

Fileoutputstream OS = xxx;

Try {
// Dosomething
} Finally {
OS. Close (); // use finally to close the object.
}

For cursor, when moving the position, first determine whether the cursor is empty, and the close method is still required after use. If it is reused, you can use the Deactivate method to release the current resource and use the requery method to query again.

5. the SDK is marked as deprecated. In general, there are better methods to replace them, so you can use them with confidence in the short term. These methods are generally compatible with later versions of sdks. Currently, Android has not yet abandoned some API support.

6. Notification intent cannot be passed to the target activity. Service and broardcast have not been tested. pendingintent must be passed in the middle. A problem may occur here.

38. Obtain the HTTP Communication Status on Android

Generally, the lightweight HTTP transmission Android platform can directly use the httpurlconnection class method of Sun Java for processing. If you define a request header, you can set it through setrequestproperty, the HTTP web server status we need to obtain can be obtained through httpurlconnection. getresponsecode () method.

Of course, the common HTTP return values are 200: Successful, 400 is a request error, 404 is not found, 500 is a server internal error, 403 is not authorized to view, 302 is redirection, and so on.

For Android platforms, more comprehensive Apache classes are provided: httpclient, httppost, httpresponse, httpget, and httpentity. For data header construction, httpentity is used, and the returned status value can be obtained through httpresponse.

For Android client and server communication development, we will introduce a lot of examples in future articles.

39. Android layout Java code Constructor

In general, we usually use XML files for Android program layout, which can improve the development efficiency. However, considering the code security and execution efficiency, we can use Java code execution to create a layout, although the XML compiled by Android is binary, the efficiency of loading the XML parser is still relatively large for resource usage. Generally, a simple textview, such

<Textview
Android: Id = "@ + ID/textcontrol"
Android: layout_width = "100px"
Android: layout_height = "wrap_content"/>

It can be equivalent to the following Java code:

Linearlayout. layoutparams textparams = new linearlayout. layoutparams (100, layoutparams. wrap_content); // The width is PX, and the height is the minimum adaptive height.

// Setorientation (vertical); set the layout to vertical

Textview textcontrol = new textview (this); // if you use xxxlayout. For example, if linearlayout is the base class of the view, this should be changed to the context of the created and modified class.
Textcontrol. settext ("Welcome to Android Development Network ");
Addview (textcontrol, textparams );

Of course, Java processing efficiency is much faster than XML, but writing a complex interface may require some embedded considerations. If you are flexible in thinking, using Java code to deploy your android applications is a better way.

40. Main methods to test the performance of Android software

You can use the following methods to analyze the efficiency bottleneck of software performance tests on the Android platform. Currently, Google has introduced a variety of test kits in the Android software development process, such as the unit test project, debugging class, And the dev tools of the simulator can directly reflect the execution performance.

1. Dev tools on the simulator can activate the screen to display the current FPS and CPU usage, which can help us test the performance of some 3D graphic interfaces.

2. network applications are generally involved, and the efficiency has a lot to do with the speed of the network. Here, you need to debug the program multiple times before you can actually understand it.

3. For the efficiency of logical Algorithm Execution, we use the most common android computing execution time to view:

Long start = system. currenttimemillis ();
// Android Development Network prompts you to do something
Long Duration = system. currenttimemillis ()-start;

The final duration saves the actual number of milliseconds required to process this method. Similar to gettickcount on Win32, high-precision performance counters and low-level timers are provided on Win 32 and Symbian. the Java layer on Dalvik VM is suitable for general applications.

4. GC efficiency tracking. If the application you run is relatively simple, you can view the memory release status of the logcat VM in ddms, and simulate where data can be cached or the algorithm can be improved.

5. the Android platform provides a wide range of multi-task synchronization methods for thread usage and synchronization. However, there are not many advanced applications such as spin locks in depth, however, for services and appwidgets, their actual products should be processed in multiple threads to release the CPU time. You can view the threads and heap memory in ddms.

More debugging and Performance Testing Methods android123 will be available in future.

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.