Android interview questions

Source: Internet
Author: User
Tags map data structure

1. Describe the lifecycle of an Activity.
2. If the background Activity is recycled by the system for some reason, How can I save the current status before being recycled by the system?
3. Set an Activity as a window style. (Edited by Sodino)
4. How to exit the Activity? How can I safely exit the Application that has called multiple activities?
5. Introduce the five la s commonly used in Android.
6. Describe how to store Android data. (Edited by Sodino)
7. introduce how ContentProvider achieves data sharing. (Edited by Sodino)
8. How to enable and disable the Service. (Edited by Sodino)
9. There are several ways to register broadcast. What are the advantages and disadvantages of these methods? Let's talk about the intention of introducing the broadcast mechanism to Android.
10. Explain the relationships among Message, Handler, Message Queue, and logoff in the single-thread model.
11. What is the full name of AIDL? How to work? What types of data can be processed?
12. Please explain the differences between the permissions for running Android programs and those for file systems. (Edited by Sodino)
13. multiple browsers are installed on the system. Can I specify a browser to access a specified page? Describe the reason.
14. A one-dimensional integer array int [] data stores the pixel value of an image with the width and height. Please write one

Algorithm to adjust the transparency of all the white (0 xffffffff) pixels in the image to 50%.
15. How do you evaluate the Android system? Advantages and disadvantages.

1. Describe the lifecycle of an Activity at

In several ways, what the system is doing and what we should do:
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. (in the activity stack system, you can manage these
At the top of the Activity, after running the pop-up stack, return to the previous Activity)

OnPause: This step is visible but interactive, and the system will stop animation and other CPU-consuming tasks.
We know from the description above that some of your data should be saved here, because at this time
Your program has a lower priority and may be withdrawn by the system. The data stored here should be stored in

OnResume is read out. Note: This method takes a short time because the next
Activities will not be started until this method is completed

Onstop: becomes invisible and overwritten by the next activity

OnDestroy: This is the last method called before the activity is killed. It may be that the external class calls the finish party.
Method or the system can use isFinishing () to temporarily kill it to save space.
Break it. If you have a Progress Dialog online rotation, please go to onDestroy
Drop the cancel. Otherwise, when the thread ends, the cancel method called by Dialog will be discarded.

OnPause, onstop, and onDestroy, all activities may be killed by the system in three states.
To ensure the correctness of the program, you need to write the code for the persistent layer operation in onPause () and save the edited content to the storage media.

(Usually databases ). In actual work, there are also many problems due to changes in the life cycle. For example, your application is new.

The thread is running. At this time, the thread is interrupted. You need to maintain the thread, whether it is paused or killed or data rollback, right? Because

Activity may be killed, so you must pay attention to the variables and some interface elements used in the thread. Generally, I use Android

The Message mechanism [Handler, Message] is used to handle the problem of multithreading and interface interaction. I will talk about this later, because of these things recently.

The header is very big. I will share it with you when I clear my thoughts.

2. If the background Activity is recycled by the system for some reason, How can I save the current status before being recycled by the system? When your program

When Activity A actively or passively runs another new Activity B during running, Activity A will execute
Java code


Void onSaveInstanceState (Bundle outState ){
Super. onSaveInstanceState (outState );
OutState. putLong ("id", 1234567890 );

Public void onSaveInstanceState (Bundle outState) {super. onSaveInstanceState (outState );

OutState. putLong ("id", 1234567890 );}

B will come to A again after completion. There are two situations at this time: A is recycled, and A is not recycled.
The onCreate () method must be re-called for the received A. It is different from directly starting the onCreate () method with parameters.
SavedInstanceState. If it is not recovered, it will be onResume.

SavedInstanceState is a Bundle object. You can basically regard it as a Map object maintained by the system. In

You may use it in onCreate (). If onCreate () is started normally, it will not be available. Therefore, you need to determine whether it is empty when using it.

Java code

If (savedInstanceState! = Null ){
Long id = savedInstanceState. getLong ("id ");

If (savedInstanceState! = Null) {long id = savedInstanceState. getLong ("id ");}

Just like in the official Notepad tutorial, if you are editing a note that is suddenly interrupted, remember the note id.

You can extract the note according to this id, and the program will be complete. This is also because your application does not need to be saved

For example, if your interface is to read a list, you don't need to remember anything special. Oh, maybe you need to remember the position of the scroll bar...

3. How to set an Activity as a window style
You only need to set the Activity topic to define the Activity in AndroidManifest. xml.
Local sentence:

Xml Code


Android: theme = "@ android: style/Theme. Dialog"

Android: theme = "@ android: style/Theme. Dialog"

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

Xml Code


Android: theme = "@ android: style/Theme. Translucent"

Android: theme = "@ android: style/Theme. Translucent"

The property of a similar activity can be displayed in the android. R. styleable class.

As shown in the AndroidManifestActivity method, you can refer to this class for descriptions of attributes of all elements in AndroidManifest. xml.

Android. R. styleable

The property name is described above. The specific value can be seen in android. R. style. For example

"@ Android: style/Theme. Dialog" corresponds to android. R. style. Theme_Dialog, ('_' to '.' <-- Note:

This is the content of the article, not a smile) can be used in the description file, find the class definition and the corresponding relationship in the description file to understand.

4. How to exit the Activity is simple for a single Activity application. Simply finish. Of course, you can also

Use methods such as killProcess () and System. exit.
Several methods are provided for reference:
1. Throw an exception and Force Exit: This method causes the program to Force Close by throwing an exception. Verification is acceptable. However, the problem to be solved is, such

When the program ends, the Force Close Window does not pop up.

2. Record opened Activity: record every Activity opened. When you need to exit, close every Activity.

3. Send a specific broadcast: Send a specific broadcast when you need to end the application. After each Activity receives the broadcast, close it.

4. recursively exit and use startActivityForResult when opening a new Activity. Then add the flag to the onActivityResult

. Except for the first one, we try to end every Activity and achieve the goal indirectly. But this is the same

Not perfect. If your application sets nosensor for each Activity

Gap, sensor may be valid. But at least, our goal has been achieved without affecting user usage. For programming convenience, it is best to set

Define an Activity base class to solve these common problems.

5. Introduce the five la s commonly used in Android, which are an important part of application interface development. There are five la s in Android.

Layout Method:
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 things. There is a wall foot in the upper left corner of a rectangular square. We put the first thing, and we want to put another one,

Put it on the top of the original place, and place it in sequence to cover the original thing. This layout is relatively simple and can only be put a little bit

Something simple.

2. Linear layout of LinearLayout, which can be understood as a div from the outer frame. First, it is a vertical layout.

Listed on the screen. Each LinearLayout can be divided into vertical layout (android: orientation = "vertical") and water

Horizontal layout (android: orientation = "horizontal "). In vertical layout, each row has only one element, and multiple elements are arranged in sequence.

Vertical Down; horizontal layout, only one row, each element in turn to the right. LinearLayout has an important genus.

Sex android: layout_weight = "1", this weight represents the line spacing in the vertical layout; horizontal represents the column width; weight Value

The larger the value, the larger the value.

3. The absolute layout of AbsoluteLayout is as if div specifies the absolute attribute and uses the X and Y coordinates to specify the element position.

Android: layout_x = "20px" android: layout_y = "12px" is easy to layout, but you can switch

When there are multiple elements, computing is troublesome.

4. Relative layout of RelativeLayout can be understood as the layout of a reference object. Main attributes are:

: Relative to an element android: layout_below = "@ id/aaa", this element is under the id aaa

Android: layout_toLeftOf = "@ id/bbb". The left side of the element is where bbb is relative to the parent element.

Android: layout_alignParentLeft = "true" align left of the parent Element

Android: layout_alignParentRight = "true". You can also specify margins for the right alignparentright of the parent element. For details, see API

5. The TableLayout Table layout is similar to the Table in Html. Each TableLayout contains the TableRow table,

You can define each element in TableRow and set its alignment mode android: gravity = "". Each Layout

They all have their own suitable methods. In addition, these five layout elements can be nested with each other to create beautiful interfaces. 6. Introduction
Android Data Storage
Android provides five data storage methods:
-- Use SharedPreferences to store data;
-- File storage data;
-- SQLite database stores data;
-- Use ContentProvider to store data;
-- Network storage data;
First, Preference, File, and DataBase correspond to/data/Package directories.

Name/Shared_Pref,/data/Package Name/files,/data/Package Name/database.
In Android, the File storage method is usually Context. openFileOutput (String fileName, int mode) and

Context. openFileInput (String fileName ).
The files generated by Context. openFileOutput (String fileName, int mode) are automatically stored in/data/Package.

In the Name/files directory, the full path is/data/Package Name/files/fileName. Note that the parameters here

FileName cannot contain path delimiters (such "/").
Generally, files generated in this way can only be accessed in this apk. However, the conclusion is that Context. openFileInput is used.

(String fileName. In this way, each apk can only access its/data/Package Name/files

The reason is very simple. The fileName parameter cannot contain path delimiters.

Find the file named fileName in the/Package Name/files directory.

I. 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

: Username and password of the logon user. It uses the Map data structure to store data, and stores data in key-value mode, which can be simply read and written.

The instance is 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 Data Reading and writing methods are very simple, but there are some differences when writing: call edit () to make it edit, and then

Before you can modify the data, use commit () to submit the modified data. In fact, SharedPreferences stores data in XML format.

Store it in the device, under/data/<package name>/shares_prefs in File Explorer in DDMS. The above data

The storage result is used as an example. After opening the file, you can see a file named user_info.xml. After opening the file, you can see:
<? Xml version = "1.0" encoding = "UTF-8"?>
<String name = "NAME"> moandroid </string>
<String name = "PASSWORD"> SharedPreferences </string>
SharedPreferences is restricted: it can only be used in the same package and cannot be used between different packages.

Ii. File Storage Data
The file storage method is a common method. The method for reading/writing files in Android is completely different from the Java program for implementing I/O.

The openFileInput () and openFileOutput () methods are provided to read files on the device. FilterInputStream,

FilterOutputStream can be detailed in the Java io package description:
String fn = "moandroid. log ";
FileInputStream FCM = openFileInput (fn );
FileOutputStream fos = openFileOutput (fn, Context. MODE_PRIVATE );
In addition, Android provides other functions to operate files. For more information, see Android SDK.

Iii. Network Storage Data

Network Storage Methods need to deal with Android Network data packets. For more information about Android Network data packets, see Android

Which packages does the SDK reference for Java SDK ?.

Iv. ContentProvider

1. Introduction to ContentProvider

When an application inherits the ContentProvider class and overwrites the class to provide data and store data, it can share its quantity with other applications.

Data. Although data can be shared externally using other methods, the data access method varies depending on the data storage method, for example, using a file

To share data externally, You need to perform file operations to read and write data. To share data with sharedpreferences, you need to use

Read and Write data using the sharedpreferences API. The advantage of using ContentProvider to share data is to unify the data access mode .?

2. Uri class Introduction

Uri indicates the data to be operated. Uri mainly contains two parts: 1. The ContentProvider to be operated, 2.

A Uri consists of the following parts:
1. scheme: the content provider's scheme has been defined by Android as: content ://.

2. Host Name (or Authority): Used to uniquely identify the ContentProvider, which can be found by external callers.


3. path: it can be used to represent the data to be operated. The path construction should be based on the business, as shown below:
? To operate records with the id of 10 in the contact table, you can build the following path:/contact/10.
? Name field of the record whose id is 10 in the contact table, contact/10/name
? To operate all records in the contact table, you can build the path:/contact?
The data to be operated may not necessarily come from the database or be stored in files, as follows:
To operate the name node under the contact node in the xml file, you can build the path:/contact/name
To convert a string to a 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 operated, we often need to parse the Uri and obtain data from the Uri. The Android system provides two

Tool classes for Uri operations, including UriMatcher and ContentUris. Understanding their usage will facilitate our development work

? UriMatcher: Used to match a Uri. Its usage is as follows:

1. First, you need to match all the Uri paths to the registration, as shown below:
// Constant UriMatcher. NO_MATCH indicates the return code (-1) that does not match any path ).
UriMatcher uriMatcher = new UriMatcher (UriMatcher. NO_MATCH );
// If the match () method matches the content: // com. changcheng. sqlite. provider. contactprovider/contact path,

The return matching code is 1.
UriMatcher. addURI ("com. changcheng. sqlite. provider. contactprovider", "contact", 1); // Add

The uri needs to be matched. If matched, the matching code is returned.
// If the match () method matches content: // com. changcheng. sqlite. provider. contactprovider/contact/230

Diameter, returns a matching code of 2
UriMatcher. addURI ("com. changcheng. sqlite. provider. contactprovider", "contact/#", 2 ); // #

As a wildcard

2. After registering the Uri to be matched, you can use the uriMatcher. match (uri) method to match the input Uri.

The return matching code. The matching code is the third parameter passed in by calling the addURI () method.

Content: // com. changcheng. sqlite. provider. contactprovider/contact path. The returned matching code is 1.
ContentUris: used to obtain the ID part after the Uri path. It has two practical methods:
? WithAppendedId (uri, id) is used to add the ID part to the path.
? The parseId (uri) method is used to obtain the ID part from the path.
? ContentResolver: When an external application needs to add, delete, modify, and query data in ContentProvider,

You can use the ContentResolver class to obtain the ContentResolver object. You can use

GetContentResolver () method. ContentResolver uses insert, delete, update, and query methods to operate data.
V. Summary

The storage method in the above 5 is used to find a suitable data storage method based on the design objectives, performance requirements, and space requirements in the future development process.

. Data storage in Android is private and cannot be accessed by other applications, unless other applications are obtained through ContentResolver.

The data shared by the program. To share data externally, you must perform file operations to read and write data. sharedpreferences is used to share data.

You must use the sharedpreferences API to read and write data. The advantage of using ContentProvider to share data is to unify data.

Access Method.

8. How to enable and disable a Service
Services in Android are similar to services in windows. services generally do not have user operation interfaces and it is not easy to run in the system.

Users can use it 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. These two

Services can be started, but their usage is different. Use startService () to enable the Service.

There is no connection between services. Even if the caller exits, the service is still running. Use bindService () to enable services, callers and services

Once the caller is bound together, the service is terminated once the caller exits. This feature features that the caller does not seek to live at the same time and must die at the same time.


If you plan to start the service using the Context. startService () method, the system will first call the onCreate

() Method, and then call the onStart () method. If the service has been created before the startService () method is called

The startService () method does not create a service multiple times, but may call the onStart () method multiple times. Use startService ()

Only the Context. stopService () method can be called to end the service. The onDestroy () method is called when the service ends.


If you plan to start the service using the Context. bindService () method, the system will first call the onCreate () method of the service when the service is not created ()

Method, 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 service.

And then call the onDestroy () method. If the service has been bound before the bindService () method is called

Using the bindService () method does not cause multiple service creation and binding (that is, the onCreate () and onBind () methods will not be created multiple times.

Call ). If the caller wants to unbind from the service being bound, he can call the unbindService () method.

The onUnbind () --> onDestroy () method of the system call 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 startService () or

BindService () method, the service is also 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 used when the service starts running.

Called. 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 used when the caller is bound to the service.

Called. When the caller has been bound to the service, 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 implemented when the caller and the service are released.

Called during binding


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





Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.