important Android interview questions

0
What are the four components of Android and what are their functions?

A: Activity: Activity is the window between the Android program and the user. It is the most basic one in the Android building block. It needs to do a lot of persistence to maintain the state of each interface, properly manage the life cycle and some jump logic.

Service: The background service is in the Activity, and the package has a complete functional logic implementation. It accepts the upper-level instructions, completes related things, and defines the Intents that need to be accepted to provide synchronous and asynchronous interfaces.

Content Provider: is an access solution for third-party application data provided by Android. It can derive the Content Provider class and provide external data. It can sort and sort like a database, shield the storage details of internal data, and provide a unified excuse model to greatly simplify. Upper-layer applications provide a more convenient way to integrate data

BroadCast Receiver: accepts one or more Intents as trigger events, accepts related messages, does some simple processing, converts them into a Notification, and unifies the Android event broadcast model.

Please introduce the five layouts commonly used in Android.

There are five layout methods commonly used: FrameLayout, LinearLayout, AbsoluteLayout, RelativeLayout, and TableLayout.

First, FrameLayout: All things are placed in the upper left corner in turn, will overlap, this layout is relatively simple, and can only put a little simpler things. Second, LinearLayout: Linear layout, each LinearLayout can be divided into vertical layout (android: orientation = vertical) and horizontal layout (android: orientation = “horizontal”). When vertical layout, each row has only one element, and multiple elements are vertically downward; in horizontal layout, there is only one row, and each element is arranged to the right. AbsoluteLayout: Absolute layout uses X, Y coordinates to specify the position of the element. This layout is also relatively simple, but when the screen is rotated, there is often a problem, and when multiple elements are used, the calculation is more troublesome. Fourth, RelativeLayout: Relative layout can be understood as a layout of a certain element as a reference. The main attributes are: relative to an element android: layout_below, android: layout_toLeftOf relative to the parent element android: layout_alignParentLeft, android: layout_alignParentRigh; five, TableLayout: table layout, each TableLayout has a table row TableRow, TableRow can be specific Define each element. Each layout has its own suitable way. These five layout elements can be nested and applied to each other to create a beautiful interface.

What are the types of animation in android, what are their characteristics and differences?

A: Two, one is Tween animation, and the other is Frame animation. Tween animation, this implementation can make the view component move, zoom in, zoom out and produce transparency changes; another Frame animation, the traditional animation method, is achieved by sequentially playing the arranged images, similar to movies.

What kinds of xml classes are parsed in android? What is the official recommendation? And their principles and differences.

A: There are three main ways of XML parsing, SAX, DOM, and PULL. Conventional development on the PC We use Dom relatively easy, but some performance sensitive databases or mobile phones still mainly use SAX mode, SAX read is one-way, advantages: not occupy memory space, analytical properties are convenient, but the disadvantage is that It is not very convenient to process multiple branches. The DOM method will load the entire XML file into memory. Here, the Android development network reminds everyone that this method can be well combined with XPath in terms of lookup. If the amount of data is not very recommended, PULL is often used in J2ME for node processing. Better, similar to the SAX method, it also saves memory. In the J2ME we often use the KXML library to parse.

ListView optimization program

Answer: 1. If you customize the adapter, then in the getView method, you should consider whether the parameter contentView passed in by the method is null. If it is null, create a contentView and return it. If it is not null, use it directly. Create views as little as possible in this method.

2. Set the tag(setTag()) to the contentView, and pass in a viewHolder object to cache the data to be displayed, which can achieve the effect of asynchronous loading of image data.

3, if the listview needs to display a lot of items, we must consider paging loading. For example, if you want to display 100 or more in total, we can consider loading 20 first, and then loading the next 20 when the user pulls to the bottom of the list.

please introduce the data storage method of Android.

A: Use SharedPreferences to store data; file to store data; SQLite database to store data; use ContentProvider to store data; network to store data;

The corresponding directories of Preference, File, and DataBase are /data/data/Package Name/Shared_Pref, /data/data/Package Name/files, /data/data/Package Name/database.

One: use SharedPreferences to store data

First, the SharedPreferences storage method is described. It is a mechanism provided by Android to store some simple configuration information, such as the user name and password of the login user. It uses the Map data structure to store data, stored in the form of key values, and can be easily read and written. The specific examples are as follows:

void ReadSharedPreferences(){

String strName,strPassword;

SharedPreferences user = getSharedPreferences(“user_info”,0);

strName = user.getString(“NAME”,””);

strPassword = user getString(“PASSWORD”,””);

}

void WriteSharedPreferences(String strName,String strPassword){

SharedPreferences user = getSharedPreferences(“user_info”,0);

uer.edit();

user.putString(“NAME”, strName);

user.putString(“PASSWORD” ,strPassword);

user.commit();

}

The methods of reading and writing data are very simple, but there are some differences when writing: first call edit() to make it edited, then modify the data, and finally use commit() to submit the modified data. In fact, SharedPreferences uses XML format to store data in the device, under /data/data/<package name>/shares_prefs in the File Explorer in DDMS. There are some limitations to using SharedPreferences: they can only be used within the same package and cannot be used between different packages.

Two: file storage data

The file storage method is a more common method. The method of reading/writing files in Android is exactly the same as the program that implements I/O in Java. The openFileInput() and openFileOutput() methods are provided to read. The file on the device. Specific examples are as follows:

String fn = “moandroid.log”;

FileInputStream fis = openFileInput(fn);

FileOutputStream fos = openFileOutput(fn,Context.MODE_PRIVATE);

Three: network storage data

Network storage, you need to deal with Android network packets, for a detailed description of Android network packets, please read which packages of the Java SDK is referenced by the Android SDK? .

Four: ContentProvider

1, Introduction to ContentProvider

When an application inherits from the ContentProvider class and overrides the methods that the class uses to provide data and store data, it can share its data with other applications. Although other methods can also share data externally, the data access method will be different depending on the way the data is stored. For example, file sharing is used to share data, and file operations are required to read and write data. Shared data is shared using sharedpreferences API. Write data. The benefit of using ContentProvider to share data is to unify the way data is accessed.

2, Uri class introduction

Uri represents the data to be manipulated. Uri mainly contains two parts of information: 1. ContentProvider that needs to operate, 2. What data is manipulated in ContentProvider, a Uri consists of the following parts:

1.scheme: The ContentProvider (content provider) scheme has been specified by Android as: content://…

2. Hostname (or Authority): Used to uniquely identify this ContentProvider, which the external caller can find based on this identifier.

3. Path: It can be used to represent the data we want to operate. The construction of the path should be based on the business, as follows:

To manipulate a record with an id of 10 in the contact table, you can build a path like this: /contact/10

To operate the name field of the record with id 10 in the contact table, contact/10/name

To manipulate all the records in the contact table, you can build a path like this: /contact?

The data to be operated does not necessarily come from the database, but it can also be a file and other storage methods, as follows:

To manipulate the name node under the contact node in the xml file, you can build a path like this: /contact/name

If you want to convert a string to Uri, you can use the parse() method in the Uri class, as follows:

Uri uri = Uri.parse(“content://com.changcheng.provider.contactprovider/contact”)

3. Introduction to UriMatcher, ContentUrist and ContentResolver

Because Uri represents the data to be manipulated, we often need to parse the Uri and get the data from the Uri. The Android system provides two utility classes for working with Uri, UriMatcher and ContentUris. Mastering their use will make our development work easier.

What are the startup modes of the activity? What does it mean?

A: In android, there are 4 kinds of activity startup modes, namely:

“standard” (default)

“singleTop”

“singleTask”

“singleInstance”

They mainly have the following differences:

1. How to decide which task to belong to

The target task of the “standard” and “singleTop” activities is in the same task as the sender of the received Intent, unless the intent includes the parameter FLAG_ACTIVITY_NEW_TASK.

If the FLAG_ACTIVITY_NEW_TASK parameter is provided, it will be launched into another task.

“singleTask” and “singleInstance” always use activity as the root element of a task, they will not be launched into a different task.

2. Whether to allow multiple instances

“standard” and “singleTop” can be instantiated multiple times and exist in different tasks, and a task can include multiple instances of an activity;

“singleTask” and “singleInstance” restrict the generation of only one instance and are the root element of the task. singleTop requires that if an instance of the Activity to be created is already in the top of the stack when the intent is created, the intent is sent to the instance and not sent to the new instance.

3. Whether other activities are allowed to exist in this task

“singleInstance” monopolizes a task, other activities cannot exist in the task; if it starts a new activity, regardless of the launch mode of the new activity, the new activity will run in other tasks (like adding FLAG_ACTIVITY_NEW_TASK) parameter).

The other three modes can coexist with other activities.

4. Whether to generate a new instance every time

“standard” will generate a new instance of the activity for not starting an Intent;

If the activity of “singleTop” is at the top of the stack of the task, then no new instance of the activity is generated, and the instance of the top of the stack is directly used. Otherwise, an instance of the activity is generated.

For example, now the task stack element is ABCD (D is at the top of the stack). At this time, a startup intent is sent to D. If D is “standard”, a new instance of D is generated, and the stack becomes A-B-C-D- D.

If D is singleTop, then a new instance of D will not be produced, the stack state is still ABCD

If you send an Intent to B at this time, regardless of whether B’s launchmode is “standard” or “singleTop”, a new instance of B is generated, and the stack status changes to ABCDB.

“singleInstance” is the only activity on its stack, which is reused every time.

“singleTask” accepts an intent if it is at the top of the stack. Otherwise, the intent will be discarded, but the task will still return to the foreground.

When the existing activity instance handles the new intent, the onNewIntent() method is called. If the intent is generated to generate an activity instance, the user can return to the previous state through the back key; if it is an existing activity to process the intent If the user cannot return to the previous state by pressing the back button.

please describe the life cycle of the Activity.

A: The life cycle methods of activity are: onCreate(), onStart(), onReStart(), onResume(), onPause(), onStop(), onDestory();

Visible lifecycle: from onStart() until the system calls onStop()

Frontend lifecycle: from onResume() until the system calls onPause()

the life cycle of the activity when the screen is rotated

A: When you do not set the android:configChanges of the Activity, the cut screen will re-call each life cycle, it will be executed once when cutting the horizontal screen, and will be executed twice when the vertical screen is cut; when setting the android:configChanges=”orientation” of the Activity, cut The screen will still recall each life cycle, only when the horizontal and vertical screens are executed; when the Activity android:configChanges=”orientation|keyboardHidden” is set, the screen will not recall each life cycle, only the onConfigurationChanged method will be executed.

Explain the relationship between Message, Handler, Message Queue, and Looper in the single-threaded model.

A: Simply put, the Handler gets the looper object in the current thread, the looper is used to retrieve the Message from the MessageQueue that stores the Message, and then the Handler is used to distribute and process the Message.

Message Queue (Message Queue): used to store the message published by the Handler, usually attached to a thread that creates it, you can get the message queue of the current thread through Looper.myQueue ()

Handler: can post or process a message or operate a Runnable, publish a message through a Handler, the message will only be sent to the message queue associated with it, but only the message in the message queue can be processed

Looper: is the communication bridge between the Handler and the message queue. The program component first passes the message to the Looper through the Handler, and the Looper puts the message into the queue. Looper also broadcasts the messages in the message queue to all

Handler: Handler receives handle message and calls handleMessage to process

Message: The type of the message, a single message is processed in the handleMessage method in the Handler class.

In the single-threaded model, for the thread communication problem, Android designed a Message Queue, through which the thread can exchange information with the Handler and Looper components. They will be introduced separately below:

Message

Message message, understood as the information exchanged between threads, processing the data background thread needs to update the UI, then send the message contains some data to the UI thread.

2. Handler

The Handler handler is the main handler of the Message, responsible for the sending of the Message and the execution of the Message content. The background thread is the sendMessage(Message) by passing in the Handler object reference. To use Handler, you need to implement the handleMessage(Message) method of this class, which is the operation content of these Messages, such as Update UI. Subclassing Handlers are usually needed to implement the handleMessage method.

3. Message Queue

Message Queue message queue, used to store messages published by Handler, according to the first in first out.

Each message queue will have a corresponding Handler. The Handler will send a message to the message queue in two ways: sendMessage or post. Both messages are inserted at the end of the message queue and executed on a first-in, first-out basis. However, the message sent by these two methods is executed in a slightly different way: a message message sent by sendMessage is handled by the handleMessage() function of the Handler, and a runnable object sent by the post method is executed by itself. .

4. Looper

Looper is the stewards of Message Queue in each thread. Android does not have Global’s Message Queue, and Android automatically creates a Message Queue for the main thread (UI thread), but does not create a Message Queue in the child thread. So the Looper of the main thread obtained by calling Looper.getMainLooper() is not NULL, but calling Looper.myLooper() to get the Looper of the current thread may be NULL. Using Looper for child threads, API Doc provides the correct use: the approximate flow of this Message mechanism:

1. After the Looper.loop() method starts running, it periodically loops out the non-NULL Messages in the Message Queue in the order in which they were received.

2. The Message in the Message Queue is NULL at the beginning. When Handler.sendMessage(Message) is sent to Message Queue, the function that sets the target property of the Message object is the current Handler object. Then Looper takes out the Message and calls the dispatchMessage function of the Hander pointed to by the target of the Message to process the Message. In the dispatchMessage method, how to handle the Message is specified by the user, three judgments, the priority is from high to low:

1) Callback inside the Message, an object that implements the Runnable interface, where the run function does the processing;

2) An object that implements the Callback interface pointed to by mCallback in the Handler is processed by its handleMessage;

3) The class corresponding to the message Handler object inherits and implements the handleMessage function, and the message is processed by the handleMessage function of this implementation.

Thus, the handleMessage method we implemented is the lowest priority!

3. After the Handler has finished processing the Message (update UI), Looper sets the Message to NULL for recycling!

There are a lot of articles on the Internet about how the main thread interacts with other child threads, transferring information, and finally who is going to execute the processing information. Personal understanding is the easiest way to determine which thread the Looper object in the Handler object belongs to. , by the thread to execute!

1. When the argument of the constructor of the Handler object is empty, it is the Looper of the current thread;

2. Looper.getMainLooper() gets the Looper object of the main thread, and Looper.myLooper() gets the Looper object of the current thread.

Leave A Reply