Android interview questions
1. Whether the process of android dvm is the same concept as that of Linux:
A: dvm is a dalivk virtual machine. Every android application runs in its own process and has a dalivk Virtual Machine instance. Every dvm is a process in linux. Therefore, it can be considered the same concept.
2. What types of android animations are available? What are their characteristics and differences?
A: There are two types: tween animation and frame animation. Tween animation, which allows view components to move, zoom in, or zoom out, and change transparency. Frame Animation, a traditional animation method, is achieved through sequential playback of arranged images, similar to movies.
3. handler hexadecimal principle:
A: android provides handler and logoff to implement inter-thread communication. Handler first-in-first-out principle. Logoff 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 messagequeue, or receive messages sent by logoff (extracted from messagequeue.
3) messagequeue: used to store messages placed by threads.
4) thread: the UI thread is usually the main thread, and a message queue will be created for the android Startup Program.
4. Refresh android view:
A: There are many ways to update the View in Android, so you must distinguish between different application scenarios. I think the most important thing is to clarify the usage of multithreading and double buffering.
1). multithreading and double buffering are not used.
This is the simplest case. Generally, you only want to re-paint the UI when the View changes. You only need to explicitly call the invalidate () method in the View object in the Activity. The system automatically calls the onDraw () method of View.
2). multithreading and no dual-buffering
In this case, a new thread needs to be enabled, and the newly opened thread cannot access the View object. If you force access, the following error will be reported: android. view. ViewRoot $ CalledFromWrongThreadException: Only the originalthread that created a view hierarchy can touch its views.
In this case, you need to create a subclass that inherits android. OS. Handler and override the handleMessage (Messagemsg) method. Android. OS. handler can send and process messages. You need to send a message to update the UI in the Activity, and then your Handler (you can use an anonymous internal class) (because the anonymous internal class can access the parent class variable, you can directly call the invalidate () method in the View object ). That is, a Message is created and sent in a new thread, and then captured and processed in the main thread.
3). multithreading and dual Buffering
In Android, SurfaceView is a subclass of View. It also implements dual buffering. You can define a subclass and implement the SurfaceHolder. Callback interface. Because the SurfaceHolder. Callback interface is implemented, the new thread does not need the help of android. OS. Handler. The lockCanvas () method in SurfaceHolder can lock the canvas. It is more convenient to draw a new image and call unlockCanvasAndPost (canvas) to unlock (Display.
5. Let's talk about the principles of the mvc model, which is used in android:
A: android officially recommends that the mvc mode be used for application development. What is mvc?
Mvc is short for model, view, and controller. mvc consists of three parts:
L model object: it is the main part of an application. All business logic should be written in this layer.
2. view object: the part of the application that generates the user interface. It is also the only layer that users can see in the entire mvc Architecture. It receives user input and displays processing results.
3. Controller objects: controls the display of user interface data and updates the status of model Objects Based on user input. A more important navigation function of Controller, if you want to use user-related events, you can submit them to m for handling.
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, you can think of using javascript + html as the view layer in android. 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 this is that the response time of acitivity in android is 5 s. 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.
6. Activity lifecycle:
A: onCreate: Create an interface to initialize data.
OnStart: In this step, the user can see and cannot interact with each other.
OnResume: it becomes interactive with the user. (The activity stack system manages the top of these activities through stacks. After the stack is run, it returns to the previous Activity)
OnPause: This step is visible but not interactive. The system will stop animation and other CPU-consuming tasks. As you can see from the above description, you should save some of your data here, at this time, your program has a lower priority and may be reclaimed by the system. The data stored here should be stored in
Onstop: becomes invisible and overwritten by the next activity
OnDestroy: This is the last method called before the activity is killed. It may be the external class that calls the finish method or the system temporarily kills the method to save space.
7. Change the Activity to a window:
A: Activity attribute setting: Sometimes an application is floating on the mobile phone's main interface. In this case, you only need to set the theme of the Activity, that is, add a sentence where Manifest. xml defines the Activity:
Android: theme = "@ android: style/Theme. Dialog"
For translucent effect:
Android: theme = "@ android: style/Theme. Translucent"
8. Five la s commonly used in Android:
Answer: LinearLayout linear layout; AbsoluteLayout absolute layout; TableLayout table layout; RelativeLayout relative layout; FrameLayout frame layout;
9. Five data storage methods for Android:
A: sharedPreferences; file; SQLite; contentProvider; Network
10. Explain the relationships among Message, Handler, Message Queue, and logoff in the single-thread model:
A: Handler gets the logoff object in the current thread. logoff is used to retrieve the Message from the Message Queue containing the message, and then Handler distributes and processes the message.
11. What is the full name of AIDL? How to work? What types of data can be processed?
A: AIDL (AndroidInterface Definition Language) android Interface Description Language
12. multiple browsers are installed on the system. Can you specify a browser to access a specified page?? Please explain the reason:
A: Send the Uri directly to pass the parameter, or use the data attribute in intentfilter in manifest. The Code is as follows:
Intent intent = new Intent ();
Intent. setAction ("android. intent. action. View ");
Uri uriBrowsers = Uri. parse ('http://www.sina.com.cn ");
Intent. setData (uriBrowsers );
// Package name, activity to be opened
Intent. setClassName ("com. android. browser", "com. android. browser. BrowserActivity ");
StartActivity (intent );
13. What is ANR and how to avoid it?
A: ANR definition:
On android, if your application has a responsive response for a period of time, the system will prompt you the ANR: application Not Responding dialog box. Therefore, the design of response performance in the program is very important, so that the system will not display ANR to the user.
How to avoid:
First, we will study why it occurs in android applications and how to best build applications to avoid ANR.
Android applications usually run in a separate thread (for example, main). This means that if your application is doing things for a long time in the main thread, the ANR dialog box is triggered because your application does not have the opportunity to handle input events or Intent broadcasts.
Therefore, do as few requests as possible in the main thread. In particular, an activity should be created as little as possible in its key lifecycle methods (onCreate () and onResume. Potential time-consuming operations, such as network or database operations, or high-time computing such as bitmap size change, should be in the Child thread (or take database operations as an example, through asynchronous request). However, it does not mean that your main Thread is blocked and waits for the completion of the sub-Thread-or it does not call Thread. wait () or Thread. sleep (). The alternative method is that the main thread should provide a Handler for the sub-thread so that the Handler can be submitted to the main thread upon completion. Designing your application in this way will ensure that your main thread is responsive to the input and avoid the ANR dialog box triggered by the 5-second input event timeout. This approach should be followed in other display UI threads because they are all affected by the same timeout.
The Special execution time limit of IntentReceiver means that it should do small and trivial work in the background, such as saving settings or registering a Notification. Like other methods called in the main thread, applications should avoid time-consuming operations or computations in BroadcastReceiver, instead of doing these tasks in the Child thread (because BroadcastReceiver has a short life cycle), the alternative is that if you need to perform a time-consuming action in response to the Intent broadcast, the application should start a Service. By the way, you should also avoid starting an Activity in the Intent Receiver because it creates a new screen and grabs the focus from the program that the current user is running. If your application needs to show users what they want to respond to Intent broadcast, you should use Notification Manager.
In general, 100 to MS is the time threshold for the user to perceive the block in the application. Below are some tips to avoid ANR and help make your application look responsive.
If your application is working in the background for the response user input, the progress of the work can be displayed (ProgressBar and ProgressDialog are useful in this case ). Especially for games, mobile computing is performed in sub-threads. If your program has a time-consuming initialization process, you can display a Splash Screen or quickly display the main Screen and asynchronously fill in the information. In both cases, you should display the progress in progress to avoid freezing the program.
14. What will cause Force Close? How to avoid it? Can I capture exceptions that cause them?
A: for example, a null pointer can cause ForceClose. You can check Logcat and find the corresponding program code to solve the error.
15. lifecycle of the activity during screen switching:
A:
1) Create an activity and print the lifecycle of the activity.
2) run the activity and obtain the following information:
OnCreate () à
OnStart () à
OnResume () à
3) press ctrl + F12 to switch to landscape Screen
OnSaveInstanceState () à
OnPause () à
OnStop () à
OnDestroy () à
OnCreate () à
OnStart () à
OnRestoreInstanceState () à
OnResume () à
4) When you press ctrl + f12 to switch to the portrait screen, the same Log is printed twice.
OnSaveInstanceState () à
OnPause () à
OnStop () à
OnDestroy à
OnCreate () à
OnStart () à
OnRestoreInstanceState () à
OnResume () à
OnSaveInstanceState () à
OnPause () à
OnStop () à
OnDestroy à
OnCreate () à
OnStart () à
OnRestoreInstanceState () à
OnResume () à
5) Modify AndroidManifest. xml, add android: configChanges = "orientation" to the Activity, and execute step 3.
OnSaveInstanceState () à
OnPause () à
OnStop () à
OnDestroy () à
OnCreate () à
OnStart () à
OnRestoreInstanceState () à
OnResume () à
6) Modify AndroidManifest. xml, add android: configChanges = "orientation" to the Activity, and execute Step 4. The same information will not be printed, but an onConfigChanged line will be printed.
OnSaveInstanceState () à
OnPause () à
OnStop () à
OnDestroy () à
OnCreate () à
OnStart () à
OnRestoreInstanceState () à
OnResume () à
OnConfigurationChanged () à
7) Change android: configChanges = "orientation" in step 5
Android: configChanges = "orientation | keyboradHidden". After step 3 is executed, only onConfigChanged is printed.
OnConfigurationChanged () à
8) Change android: configChanges = "orientation" in step 5
Android: configChanges = "orientation | keyboradHidden", step 4
OnConfigurationChanged () à
OnConfigurationChanged () à
Summary:
1) if you do not set activity android: configChanges, screen switching will re-call the life cycle of each activity, and will be executed once during horizontal screen switching and twice during landscape screen switching.
2) When setting the activity's android: configChanges = "orientation", the screen will be re-called for each life cycle, and the screen will be executed only once when the screen is landscape or landscape is switched, however, an onConfigurationChanged () is printed at the end of the portrait screen ()
3) when setting the activity's android: configChanges = "orientation | keyboardHidden", the split screen will not re-call each lifecycle, but will only execute onConfigurationChanged (), landscape screen once, landscape screen twice
Summarize the lifecycle of the entire activity:
1) When Toast and AlertDialog are displayed in the event generated by the current activity, the lifecycle of the Activity will not change.
2) press the HOME key when the Activity is running (the same as being completely overwritten)
OnSavaInstanceState à
OnPause à
OnStop à
OnRestart à
OnStart à
OnResume à
3) Not fully covered, but the focus is lost:
OnPause à
OnResume à
16. How to publish the SQLite database (. db file) with the apk file?
A: You can copy the. 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. Copy the. db file to the res aw directory.
17. 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 in the memory or SD card of your mobile phone 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. You can use SQLiteDatabase. openOrCreateDatabase In the Android SDK to open SQLite database files in any directory.
18. Which of the following types of xml parsing classes does android support? Which one is officially recommended? And their principles and differences:
A: There are three ways to parse XML: SAX, DOM, and PULL. It is relatively easy to use Dom for general development on PC, but some performance-sensitive databases or mobile phones still use the SAX method. The SAX reading method is one-way and has advantages: it is not convenient to occupy memory space and parse attributes, but the disadvantage is that it is not convenient to process multiple branches. The DOM method loads the entire XML file into the memory. Here, the Android Development Network reminds you that this method can be used with XPath in search. If the data volume is not large, it is recommended to use it, while PULL is often used in j2s for better processing of nodes. Similar to the SAX method, PULL also saves much memory. We often use the KXML library for parsing in j2s.
19. What is the difference between DDMS and TraceView?
A: DDMS is a program execution viewer in which thread and stack information can be seen. TraceView is a Program Performance Analyzer.
20. Talk about the Android IPC Mechanism:
A: IPC is short for internal process communication. It is a resource sharing "named Pipeline. The IPC Mechanism in Android is used to allow interaction between Activity and Service at any time. Therefore, in Android, this mechanism is only applicable to communication between Activity and Service, similar to remote method calls, similar to access in C/S mode. Define the IPC interface by defining the AIDL interface file. The Servier side implements the IPC interface, and the Client side calls the IPC interface as a local proxy.
21. What is NDK:
A: NDK is a collection of tools.
NDK provides a series of tools to help developers quickly develop C/C ++ dynamic libraries and automatically compress so and java applications into apk packages.
NDK integrates the cross compiler and provides mk files and isolates the differences between cpu and platform. Developers only need to modify the mk file to create the so
22. Describe the android system architecture:
A: The android system architecture is divided from the bottom to the Linux kernel layer, Runtime Library, application framework layer, and application layer.
Linux kernel layer: Responsible for hardware drivers, networks, power supplies, system security, and memory management.
Runtime Library and androidruntion: Runtime Library: c/c ++ function library. Most of them are open-source function libraries, such as webkit. This function library is responsible for running android web browsers; for example, the standard c function library libc, openssl, and sqlite also include 2dsgl and 3 dopengles that support game development, mediaframework framework is available in multimedia to support playback and display of various audio and video files, such as mpeg4 and h. 264, mp3, aac, amr, jpg, png, and many other multimedia file formats. Androidruntion is responsible for interpreting and executing the generated dalvik format bytecode.
Application Software Architecture: java application developers use APIs encapsulated at this layer for rapid development.
Application Layer: This layer is the java application layer. android's built-in googlemaps, email, IM, and browsers are all at this layer, the java developer-defined program is also at this layer, and is equal to the built-in application. It can call or replace the built-in application.
23. What are the startup modes of Activity and Task? What are their meanings?
A: In an activity, you call startActivity multiple times to start another activity. To generate only one activity instance, you can set the startup mode.
An activity has four startup modes: standed, signleTop, singleTask, and singleInstance.
Standed: standard mode. A new instance is generated when the startActivity () method 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, and no other instances
24. Role of the Application class:
A: The first sentence in the API is:
Base class for those who need to maintain global application state
If you want to use global variables in the entire application, static variables and public variables are generally used in java. If you use such global variables in android, they do not conform to the framework architecture of Android, however, you can use Application context in a more elegant way.
First, you must override the Application. The onCreate method is used to override the value of the variable during creation. Then the variable can be operated on in each file of the entire application.
When the Application is started, the system creates a PID, that is, the process ID, and all the activities will run on this process. Then we initialize the global variables when the Application is created. All the activities of the same Application can obtain the values of these global variables. In other words, we changed the values of these global variables in an Activity, so the values of other activities in the same application will change.
25. Description of when onSaveInstanceState () and onRestoreInstanceState () are called:
A: The onSaveInstanceState () and onRestoreInstanceState () of an Activity are not life cycle methods. They are not necessarily triggered because they are different from the Life Cycle methods such as onCreate () and onPause. OnSaveInstanceState () is called only when an Activity is destroyed by the system when the application encounters an unexpected situation (such as insufficient memory or the user directly presses the Home key. However, when a user actively destroys an Activity, for example, pressing the return key in the application, onSaveInstanceState () will not be called. In this case, the user's behavior determines that the Activity status does not need to be saved. Generally, onSaveInstanceState () is only suitable for saving some temporary states, while onPause () is suitable for persistent data storage.
In addition, when the screen direction changes, the Activity will be destroyed and re-created. If you want to cache some data before the Activity is destroyed, the cached data is restored after the Activity is re-created. You can override the onSaveInstanceState () and onRestoreInstanceState () Methods of the Activity.
26. What is the lifecycle of the android service? Which method can be called multiple times:
Answer: 1) lifecycle methods related to starting a service using the Context. startService () method
OnCreate ()-> onStart ()-> onDestroy ()
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.
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.
OnDestroy () is called when the service is terminated.
2) lifecycle methods related to starting a service using the Context. bindService () method
OnCreate ()-> onBind ()-> onUnbind ()-> onDestroy ()
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.
If you use the startService () method to start the service, then call the bindService () method to bind to the service, then call the unbindService () method to unbind, and finally call the bindService () method to bind to the service again, the method for triggering the lifecycle is as follows:
OnCreate ()-> onStart ()-> onBind ()-> onUnbind () [true must be returned for the overloaded method]-> onRebind ()
27. Life Cycle of android broadcast:
Answer: 1) There is only one callback method in the life cycle of the Broadcast receiver:
Void onReceive (Context curContext, Intent broadcastMsg)
When the receiver receives a broadcast message, Android will call oncaster Er () and pass it to an Intent object, which carries the broadcast message. In our opinion, only when this method is executed, the Broadcast receiver is active; when this method is returned, it is terminated. This is the life cycle of the Broadcast receiver.
2) due to the short life cycle of the Broadcast receiver, an active Broadcast receiver process is protected to avoid being killed, android will kill processes that carry components that are no longer active at any time, so this problem may occur.
3) a Service is used to solve the problem. Android considers that there are still active components in the process where the Service is located.
28. Differences between android view, surfaceview, and glsurfaceview:
A: 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.
The most essential difference between SurfaceView and View is that surfaceView can be re-painted in a new separate thread, and View must be updated in the main thread of the UI.
Updating the screen in the main UI thread may cause problems. For example, if you update the screen too long, your main UI thread will be blocked by the function you are painting. Then, messages such as buttons and touch screens cannot be responded.
When surfaceView is used to update the screen in a new thread, it will not block your main UI thread. But this also brings about another problem, that is, event synchronization. For example, if you touch the screen, you need to process the thread in surfaceView. Generally, you need an event queue design to save the touch event. This is a little more complicated because it involves thread synchronization.
Based on the above, the game features are generally divided into two categories.
1) passively update the image. For example, you can use view for chess. Because image update relies on onTouch for update, you can use invalidate directly. In this case, this Touch and the next Touch take a longer time and will not be affected.
2) Actively update. For example, a person is always running. This requires a separate thread to repeatedly repaint the state of the person, to avoid blocking the main UI thread. Obviously, the view is not suitable and needs surfaceView for control.