Android interview question Summary-from csdn

Source: Internet
Author: User

2. lifecycle of the activity during horizontal and vertical screen Switching
1. When the Android: configchanges of the activity is not set, the split screen will call the lifecycle of each activity again. The split screen will be executed once, and the split screen will be executed twice.

2. When you set the activity's Android: configchanges = "orientation", the screen will be switched to call each lifecycle, and the screen will only be executed once.

3. When the Android: configchanges = "orientation | keyboardhidden" of the activity is set, the live cycle is not re-called and only the onconfigurationchanged method is executed.

3. What are the features and differences of animations in Android?
Two types: tween animation and frame animation. Tween animation, which allows view components to move, zoom in, zoom out, and change transparency. Another Frame Animation, the traditional animation method, it is achieved through sequential playback of arranged images, similar to movies.
4. How many bytes does the longest Short Message count?
70 Chinese characters (including punctuation marks), 160,160 English bytes.

5. Handler mechanism Principle
Andriod provides handler and logoff to satisfy inter-thread communication. Handler first-in-first-out principle. The logoff class is used to manage message exchange between objects in a specific thread ).
1) loue: A thread can generate a loue object to manage the Message Queue (Message Queue) in this thread ).
2) handler: You can construct a handler object to communicate with logoff so as to push new messages to the Message Queue or receive messages sent by logoff from the message queue.
3) Message Queue: used to store messages placed by threads.
4) thread: the UI thread is usually the main thread, and Android will create a message queue for it when starting the program.

6. What is an embedded real-time operating system? Does the Android operating system belong to a real-time operating system?

An embedded real-time operating system can accept and process external events or data at a high speed, the processing result can control the production process or quickly respond to the processing system within the specified time, and control all real-time tasks to coordinate and operate in an embedded operating system. It is mainly used for industrial control, military equipment, aerospace and other fields with demanding system response time requirements, which requires the use of real-time systems. It can be divided into soft real-time and hard real-time, while Android is based on the Linux kernel, so it is soft real-time.

7. How to communicate between threads and threads in Android and between processes
1. When an android program starts running, a process is started separately.
By default, all the activities or services in this program run in this process.
By default, an android program also has only one process, but a process can have many threads.
2. When an android program starts running, a main thread is created. This thread is mainly responsible for display, update, and control interaction of the UI interface, so it is also called the UI thread.
At the beginning of an android program, a process presents a single-threaded model, that is, the main thread. All tasks are run in one thread. Therefore, the shorter the time consumed for each function called by main thread, the better. For time-consuming work, we should try to hand it over to the sub-thread to avoid blocking the main thread (the main thread is blocked, and the program will be suspended ).

3. Android single-threaded model: Android UI operations are not thread-safe and must be executed in the UI thread. If you modify the UI directly in the Child thread, an exception occurs.

8. Check whether the process of Android DVM is the same concept as that of Linux.
DVM refers to the Virtual Machine of dalivk. Every android application runs in its own process and has an independent Dalvik Virtual Machine instance. Every DVM is a process in Linux, so it can be considered the same concept.

9. What is the role of the EF file on the SIM card?
The SIM card file system has its own specifications, mainly for communication with mobile phones. Sim itself can have its own operating system. EF is used for storage and communication with mobile phones.

10. What are the features and differences of animations in Android?
Two types: tween animation and frame animation. Tween animation, which allows view components to move, zoom in, zoom out, and change transparency. Another Frame Animation, the traditional animation method, it is achieved through sequential playback of arranged images, similar to movies.

11. Change activity to a window: Activity attribute setting

It's easy to talk about it. Some people may want to make the app something floating on the main interface of the mobile phone. It's easy to set the theme of the activity in androidmanifest. one sentence for defining an activity in XML:

XML Code

1. Android: theme = "@ Android: style/theme. Dialog"

This makes your application pop up in the form of a dialog box, or

XML Code

1. Android: theme = "@ Android: style/theme. translucent"

It becomes translucent. [friendly reminder -. -] attributes of similar activities can be found in Android. r. the androidmanifestactivity method of the styleable class shows androidmanifest. for more information about the attributes of all elements in XML, see android. r. styleable

The above is the property name. The specific value is in Android. r. style, such as @ Android: style/theme. "dialog" corresponds to Android. r. style. theme_dialog, (replace '_' '. '<-Note: The content of this article is not a smiley face. You can use it in the description file to find the ing between the class definition and the description file.

12. How to publish the SQLite database (dictionary. DB file) with the APK file?
A: You can copy the dictionary. DB file to the res aw directory of the eclipse Android project. All files in the res aw directory will not be compressed, so that files in the directory can be extracted directly. You can copy the dictionary. DB file to the res aw directory.

13. How can I open the database files in the res aw directory?

A: In Android, you cannot directly open the database file in the res aw directory. Instead, you need to copy the file to a directory on the phone memory or SD card when the program is started for the first time, then open the database file. The basic method of copying is to use the getresources (). openrawresource method to obtain the resource inputstream object in the res aw directory, and then write the data in the inputstream object to the corresponding file in other directories. In the android SDK, you can use sqlitedatabase. openorcreatedatabase to open
SQLite database file.

14. The specific embodiment of MVC in Android

MVC is short for model, view, and controller. It can be seen that MVC consists of three parts:
... Model object: it is the main part of the application, and all business logic should be written in this
Layer.
.. View object: part of the application that generates the user interface. Also in the whole
The only layer that users can see in the MVC Architecture receives user input and displays processing results.
.. Controller (Control) object: controls the display and update of user interface data based on user input.
Model object status, a more important navigation function of the controller.
Shut down the event and hand it over to M.

Android encourages weak coupling and Component Reuse. In Android, MVC is embodied as follows:
1) view layer (View): it generally uses XML files to describe the interface, which can be easily introduced during use. Of course, if you know more about Android, in Android, JavaScript + HTML can also be used as the view layer. Of course, communication between Java and JavaScript is required. Fortunately, android provides convenient communication between them.

2) control layer (Controller): The re-authorization of the control layer of Android usually falls on the shoulders of many acitores. This statement also implies that you should not write code in acitivity, another reason for doing so is that the response time of acitivity in Android is 5S, if time-consuming operations are put here, programs are easily recycled.

3) model layer: database operations and network operations should all be processed in the model. Of course, operations such as business computing must also be placed in this layer.

15. architecture of the android System
Android adopts a hierarchical architecture like its operating system. From the structural diagram, Android is divided into four layers: application layer, application framework layer, system Runtime Library layer, and Linux core layer.
1. Applications
Android is released together with a series of core application packages, including email clients, SMS Short Message programs, calendars, maps, browsers, and contact management programs. All applications are written in Java.
2. Application Framework
Developers can also fully access the API framework used by core applications. The architecture design of this application simplifies Component reuse; any application can publish its functional blocks, and any other application can use the released functional blocks (but the security restrictions of the framework must be followed ). Similarly, this application reuse mechanism allows you to easily replace program components.
A series of services and systems are hidden behind each application, including;
* Rich and scalable views can be used to build applications, including lists, grids, and text boxes ), button (buttons), or even an embedded web browser.
* Content providers allow applications to access data of another application (such as the contact database) or share their own data.
* Resource manager provides access to non-code resources, such as local strings, images, and layout files ).
* Notification Manager allows applications to display custom prompts in the status bar.
* Activity manager is used to manage the application lifecycle and provides common navigation rollback functions.
For more details and how to write an application from scratch, see how to write an Android Application.
3. System Runtime Library
1) Library
Android contains some C/C ++ libraries that can be used by different components in the Android system. They provide services to developers through the Android Application Framework. The following are some core databases:
* System C library-a standard C system function library (libc) inherited from BSD, which is specially customized for Embedded Linux devices.
* Media library-Based on packetvideo opencore. This Library supports multiple common audio and video formats for playback and recording, and supports static image files. The encoding formats include MPEG4, H.264, MP3, AAC, Amr, JPG, and PNG.
* Surface Manager-manages the display subsystem and provides seamless integration of 2D and 3D layers for multiple applications.
* Libwebcore-the latest web browser engine that supports Android browsers and an embedded Web View.
* SGL-underlying 2D graphics engine
* 3D libraries-implemented based on OpenGL ES 1.0 APIs. This library can use hardware 3D acceleration (if available) or highly optimized 3D soft acceleration.
* FreeType-bitmap and Vector Fonts.

* SQLite-a lightweight relational database engine that is available to all applications and has powerful functionality.
2) Android Runtime Library
Android includes a core library that provides most of the functions of the core library of Java programming language.
Every android application runs in its own process and has an independent Dalvik Virtual Machine instance. Dalvik is designed as a device to efficiently run multiple virtual systems at the same time. Dalvik executable files executed by the Dalvik Virtual Machine (. Dex), which are optimized for small memory usage. At the same time, the virtual machine is register-based. All classes are compiled by the Java compiler, and then converted to the. Dex format using the "dx" tool in the SDK is executed by the virtual machine.
The Dalvik virtual machine depends on some features of the Linux kernel, such as the thread mechanism and the underlying memory management mechanism.
4. Linux Kernel
Android core system services depend on the Linux 2.6 kernel, such as security, memory management, process management, network protocol stack and driver model. The Linux kernel is also an abstraction layer between the hardware and software stacks.

16. Information about common android controls
Single partition (radiobutton and radiogroup ):
Radiogroup is used to group A single region. Only one region in the same group is selected.
Event: setoncheckedchangelistener () to process the selected event of a single token. Input the radiogroup. oncheckedchangelistener instance as a parameter.
Multi-choice box (checkbox ):
Each multiple-choice box is independent. You can iterate all the multiple-choice boxes and obtain their values based on whether their statuses are selected.
Event: setoncheckchangelistener () processes the selected event in the Multi-choice box. Pass the compoundbutton. oncheckedchangelistener instance as a parameter
Drop-down list box (spring ):
Spinner. getitematposition (spinner. getselecteditemposition (); get the value of the drop-down list box.
Event: setonitemselectedlistener (), processing the event selected in the drop-down list box, and passing the adapterview. onitemselectedlistener instance as a parameter;
Drag bar ):
Seekbar. getprogress () Get the current value of the drag bar
Event: setonseekbarchangelistener () is used to handle the event of changing the drag value. The seekbar. onseekbarchangelistener instance is passed in as a parameter.
Menu ):
Override the oncreatoptionmenu (menu) method of the activity. This method is used to create the option menu. When you press the "menu" button on your phone, the created menu is displayed. In oncreatoptionmenu (menu) you can call menu. add () method to add a menu.
Override the onmenuitemselected () method of the activity to process the selected menu events.
Progress dialog box (progressdialog ):
Create and display a progress dialog box: progressdialog. Show (progressdialogactivity. This, "Please wait", "Data Loading ...." , True );
Set the style of the dialog box: setprogressstyle ()
Progressdialog. style_spinner rotation progress bar style (default style)
Progressdialog. style_horizontal horizontal progress bar style

17. Introduce the five la s commonly used in Android.
Android layout is an important part of application interface development. There are five layout methods in Android: framelayout (Framework layout), linearlayout (linear layout ),
Absolutelayout (absolute layout), relativelayout (relative layout), and tablelayout (table layout ).
1. framelayout
This layout can be seen as a heap of the wall. There is a wall foot in the upper left corner of the rectangular square. We put the first thing, and we want to put another one, which is placed on the top of the original place, in this way, it will cover the original things. This layout is relatively simple, and you can only put something simple.
2. linearlayout
Linear layout, which can be understood as a div from the external frame. First, it is listed one by one on the screen. Each linearlayout can be divided into vertical layout (Android: Orientation = "vertical") and horizontal layout (Android: Orientation = "horizontal "). In vertical layout, each row has only one element, and multiple elements are vertical down in sequence. in horizontal layout, there is only one row, and each element is arranged to the right in sequence.
Linearlayout has an important property: Android: layout_weight = "1". This Weight represents the line spacing in vertical layout; horizontal represents the column width; the larger the weight value, the larger the value.
3. absolutelayout
The absolute layout is like a div that specifies the absolute attribute. The X and Y coordinates are used to specify the element location. Android: layout_x = "20px" Android: layout_y = "12px" is also relatively simple, however, when you switch vertically, problems often occur, and when there are multiple elements, the computation is troublesome.
4. relativelayout
The relative layout can be understood as the layout method for positioning an element as a reference object. Main attributes include:
Relative to an element
Android: layout_below = "@ ID/AAA". The element is under AAA.
Android: layout_toleftof = "@ ID/BBB". The left side of the element is BBB.
Relative to the parent Element
Android: layout_alignparentleft = "true" is aligned to the left of the parent element.
Android: layout_alignparentright = "true" is aligned to the right of the parent element.
You can also specify margins. For details, see API

5. tablelayout
The table layout is similar to the table in HTML. Each tablelayout contains the table row tablerow, which can define each element and set its alignment mode Android: gravity = "".
Each layout has its own method. In addition, these five layout elements can be nested with each other to create a beautiful interface.

18. How to enable and disable a service
Services in Android and windows are similar. services generally do not have user operation interfaces. They run in a system and are not easily noticed by users. You can use them to develop programs such as monitoring. Service development is relatively simple, as follows:
Step 1: Inherit the service class
Public class smsservice extends Service {
}
Step 2: configure the service on the <Application> node in the androidmanifest. xml file:
<Service android: Name = ". smsservice"/>

The service cannot run on its own. You must call the context. startservice () or context. bindservice () method to start the service. Both methods can start the service, but their usage is different. The startservice () method is used to enable the service. There is no relation between the caller and the service. Even if the caller exits, the Service continues to run. When the bindservice () method is used to enable the Service, the caller and the service are bound together. Once the caller exits, the service is terminated. This feature features that the caller does not want to generate at the same time and must die at the same time.

If you plan to use the context. startservice () method to start the service, when the service is not created, the system will first call the oncreate () method of the service and then call the onstart () method. If the service has been created before the startservice () method is called, multiple call of the startservice () method will not lead to multiple creation of the service, but will lead to multiple calls of the onstart () method. A service started using the startservice () method can only end the service by calling the context. stopservice () method. The ondestroy () method is called when the service ends.

If you plan to use the context. bindservice () method to start the service, when the service is not created, the system will first call the oncreate () method of the service and then call the onbind () method. At this time, the caller and the service are bound together. After the caller exits, the system will first call the onunbind () method of the service and then call the ondestroy () method. If the service has been bound before the bindservice () method is called, multiple calls to the bindservice () method will not result in multiple service creation and binding (that is, oncreate () and onbind () the method is not called multiple times.
). If the caller wants to unbind from the service being bound, he can call the unbindservice () method. Calling this method also causes the system to call the onunbind ()-> ondestroy () method of the service.
Common lifecycle callback methods for services are as follows:
Oncreate () This method is called when a service is created. This method is called only once. No matter how many times the startservice () or bindservice () method is called, the service is created only once.
Ondestroy () is called when the service is terminated.

Life cycle method related to starting a service using context. startservice ()
Onstart () calls back this method only when the context. startservice () method is used to start the service. This method is called when the service starts running. Although the startservice () method is called multiple times, the onstart () method is called multiple times.

The lifecycle method related to starting a service using the context. bindservice () method
Onbind () calls back this method only when the context. bindservice () method is used to start the service. This method is called when the caller binds to the service. When the caller and the service are already bound, multiple calls to the context. bindservice () method will not cause this method to be called multiple times.
Onunbind () calls back this method only when the context. bindservice () method is used to start the service. This method is called when the caller and the service are unbound.

The code for starting a service using context. startservice () is as follows:
Public class helloactivity extends activity {
@ Override
Public void oncreate (bundle savedinstancestate ){
......
Button button = (button) This. findviewbyid (R. Id. Button );
Button. setonclicklistener (New View. onclicklistener (){
Public void onclick (view v ){
Intent intent = new intent (helloactivity. This, smsservice. Class );
Startservice (intent );
}});
}
}

The code for starting a service using the context. bindservice () method is as follows:
Public class helloactivity extends activity {
Serviceconnection conn = new serviceconnection (){
Public void onserviceconnected (componentname name, ibinder Service ){
}
Public void onservicedisconnected (componentname name ){
}
};
@ Override
Public void oncreate (bundle savedinstancestate ){
Button button = (button) This. findviewbyid (R. Id. Button );
Button. setonclicklistener (New View. onclicklistener (){
Public void onclick (view v ){
Intent intent = new intent (helloactivity. This, smsservice. Class );
Bindservice (intent, Conn, context. bind_auto_create );
// Unbindservice (conn); // unbind
}});
}
}

19. listview Optimization
Working principle:
For each item in the list, listview requires the adapter to "give me a view" (getview ).
A New View is returned and displayed.
What if we want to display hundreds of millions of projects? Create a new view for each project? No! This is impossible!
In fact, Android caches the view for you.
There is a recycler component in Android that works as follows:
If you have 1 billion items, only visible items are in memory, and others are in recycler.
1. listview first requests a type1 view (getview) and then requests other visible projects. Convertview is null in getview.
2. When Item1 gets out of the screen and a new project comes from the low end of the screen, listview then requests a type1 view. Convertview is not a null value. Its value is item1. You only need to set new data and return convertview. You do not need to create a new view.

20 broadcast receiver Lifecycle
A broadcast receiver has a callback method: void onreceive (context curcontext, intent broadcastmsg ). When a broadcast message arrives at the receiver, Android calls its onreceive () method and passes it to the intent object containing the message. The broadcast receiver is considered active only when it executes this method. When onreceive () is returned, it is inactive.
The process of an active broadcast receiver is protected and will not be killed. However, the system can kill processes with only inactive components at any time, when the memory occupied by other processes is required.
This brings about a problem. It is time-consuming to broadcast a message. Therefore, you should do these tasks in an independent thread to stay away from the main thread running by other components on the user interface. If the onreceive () derivative thread then returns the whole process, including the new thread, which is determined to be inactive (unless other application components in the process are active ), will put it in the crisis of being killed. To solve this problem, onreceive () starts a service and promptly performs the job. Therefore, the system knows that active work is being done in the process.

21. design mode and IOC (control inversion)
The source of the charm of the android framework is IOC. During Android development, you will always feel the benefits of IOC.
Take activity as an example, the following function is automatically called by the framework call:
Protected void oncreate (bundle savedinstancestate );
Instead of actively calling the code, the code written by the user is called by the framework.
Now! Of course, the meaning of IOC itself is far more than that, but in this example, we can also look at IOC
Benefits. Such examples can be seen everywhere in Android, such as database management,
For example, you can call the sax handler in Android. Sometimes, you even need to write your own
Single IOC implementation, The multithreading shown above is now a description.

22. Detailed explanation of length units in Android
Here we will introduce DP and sp. DP is dip. This is basically similar to sp. You can use DP or SP to specify attributes such as length and height. If you set the font, you need to use sp. DP is not related to density. SP is not only related to density, but also to scale. If the screen density is 160, DP and SP are the same as PX. 1dp = 1sp = 1px, but if PX is used as the unit, if the screen size remains unchanged (assuming it is still 3.2), the screen density is changed to 320. The original textview width is set to 320 PX, and the density is.
A 3.2-inch screen is half shorter than a 160-inch screen with a density of 3.2. But if it is set to 160dp or 160sp. The system automatically sets the width property value to 320px. That is, 160*320/160. Among them, 320/160 are called passwords.
Degree ratio factor. That is to say, if DP and SP are used, the system will automatically
.

Next, let's take a look at the meaning of other units.
Px: the actual pixel of the screen. For example, a screen of 320*480 has 320 pixels horizontally,
There are 480 pixels in the vertical direction.

In: indicates the inch, which is the physical size of the screen. Each inch equals 2.54 cm. For example, describe
Mobile phone screen size, often said, 3.2 (English), 3.5 (English), 4 (English) refers to this
Unit. These dimensions are the diagonal length of the screen. If the mobile phone screen is 3.2 inch, it indicates the mobile phone
The diagonal line length of the screen (visible area) is 3.2*2.54 = 8.128 cm. Reader can fetch
Measure the screen size of your mobile phone to see if it is the same as the actual size.

23. Four Activity startup Modes
Standard: standard mode. A new instance is generated when startactivity () is called.
Singletop: if an instance already exists at the top of the activity stack, a new instance is not generated, but the newinstance () method in the activity is called. If it is not at the top of the stack, a new instance is generated.
Singletask: This instance will be generated in a new task. This instance will be used for each call in the future and no new instances will be generated.
Singleinstance: this is basically the same as singletask. There is only one difference: In this mode, only the activity instance can exist in the task where the activity instance is located, but not other instances.

24. What is ANR and how to avoid it?
ANR: application not responding, 5 seconds
In Android, the activity manager and window manager system services are responsible for monitoring application responses. Android displays the ANR dialog box when the following conditions occur:
Response to input events (such as buttons and touch screen events) exceeds 5 seconds
The intentreceiver has not been executed for more than 10 seconds.
Android applications run completely in an independent thread (such as main ). This means that any operation that runs in the main thread requires a large amount of time will lead to ANR. At this time, your application has no chance to respond to input events and intent broadcast ).

Therefore, any method running in the main thread should do as little work as possible. This is especially true for important methods in the activity lifecycle, such as oncreate () and onresume. Potential time-consuming operations, such as accessing networks and databases, or computing with high overhead, such as modifying the bitmap size, must be completed in a separate sub-thread (or using asynchronous requests, such as database operations ). However, this does not mean that your main thread needs to enter the blocking status and waits for the sub-thread to end-nor does it need to call the therad. Wait () or thread. Sleep () method. Instead, the main thread provides a handler for the sub-thread)
So that the sub-thread can call it at the end of the day (xing: see the snake example. This method is different from what we used previously ). Using this method involves your application, which ensures that your program responds well to the input and avoids the ANR generated because the input event is not processed for more than five seconds. This practice needs to be applied to all the threads that display the user interface, because they all face the same timeout issue.

25. Use of Android intent
In an Android Application, components (activity, service, contentprovider, etc.) are mainly composed of intent in the communication between these components.
As some people on the Internet said, intent describes the actions, actions involving data, and additional data in an application. Android is responsible for finding the corresponding components based on the description of this intent, pass intent to the called component and complete the call of the component. Intent serves as a decoupling between the caller and the called.
During intent transmission, you need to find the target consumer (another activity, intentreceiver or service), that is, the responder of intent. There are two methods to match:
1. Explicit match ):
Public testb extents Activity
{
.........
};
Public class test extends Activity
{
......
Public void switchactivity ()
{
Intent I = new intent (test. This, testb. Class );
This. startactivity (I );
}
}
The code is concise and clear. After the switchactivity () function is executed, it will jump to the activity named testb immediately.

2. Implicit match (implicit ):

For implicit match, you must first match the values of intent: Action, category, data/type, and component.
If you enter componet, It is test. Class in the previous example.) This forms a display match. Therefore, this section only describes the first few matching types. The matching rule is the maximum matching rule,

1. If you enter action, if there is a program manifest. if the intentfilter segment of an activity in XML defines the same action, the intent matches the target action. If the filter segment does not define type, category, then the activity matches. However, if there are more than two matching programs on the phone, a dialog box will pop up to indicate the matching.
The value of action has many predefined meanings in Android. If you want to directly go to your own intent receiver, you can add a custom action value to the receiver's intentfilter (and set the category value to "android. intent. category. default), set this value to the intent action in your intent, you can directly jump to your own intent receiver. This action is unique in the system.
2, data/type, you can use URI as data, such as Uri uri = URI. parse (http://www.google.com );
Intent I = new intent (intent. action_view, Uri); During the intent delivery process of the mobile phone, the data type is determined according to the scheme of the http://www.google.com.
The phone's Brower can match it. In Brower's manifest. XML, intenfilter first contains action_view action, which can also process HTTP: type,

3. For classification category, do not set it in intent. If you write the intent receiver, it is in manifest. the intentfilter of XML activity contains android. category. default, so that all category (intent. the intent of addcategory (string C);) will match this category.

4. Extras (additional information) is a collection of all other additional information. You can use extras to provide extended information for components. For example, if you want to perform the "send email" action, you can save the email title and body in extras, send to the email sending component.

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.