It's a real fucking comprehensive solution.
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. Write an 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.
Http://weizhulin.blog.51cto.com/1556324/311495
The following describes in detail 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.
Abnormal.
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 all the edited content to the storage medium (generally databases ). In actual work, there are also many problems due to changes in the life cycle. For example, if your application starts to run a new thread and the thread is interrupted, you need to maintain the thread, pause, kill, or roll back data, right? Because the activity may be killed, pay attention to the variables and some interface elements used in the thread. Generally, I use the android message mechanism [handler, message] to handle the problem of multithreading and interface interaction. I will talk about this later, because these things are already very big recently, and I will share them 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 one activity a in your program is running, it actively or passively runs another activity B
At this time, a will execute
Java code
Public
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. 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, then, you can extract the note according to the ID, and the program will be complete. This also shows that your application does not need to be saved. For example, if your interface is to read a list, you do not 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"
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.
4. How to exit the activity
For a single activity application, it is easy to exit. 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.
Yes, but the problem to be solved is how to end the program without the force close window.
2. Record the opened activity:
Every time an activity is opened, it is recorded. When you need to exit, close every activity.
3. Send specific broadcasts:
Send a specific broadcast when you need to end the application. After each activity receives the broadcast, close it.
4. Recursive exit
Use startactivityforresult when opening a new activity, add a flag on your own, process it in onactivityresult, and disable it recursively.
Except for the first one, we try to end every activity and achieve the goal indirectly.
However, this is not perfect.
If your application sets nosensor for each activity, the sensor may be valid during the gap between the two activities.
But at least, our goal has been achieved without affecting user usage.
For programming convenience, it is best to define an activity base class to deal with these common problems.
5. Introduce the five commonly used la s in Android
Android layout is an important part of application interface development. There are five layout methods in Android: framelayout
Bureau), linearlayout
(Linear layout), absolutelayout (absolute layout), relativelayout (relative layout), 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 attribute Android: layout_weight = "1". In vertical layout, this weight represents the line spacing; in horizontal layout, it represents the column width; the larger the weight value, the larger the value.
Iii. absolutelayout
The absolute layout is like that DIV specifies the absolute attribute, and uses the X and Y coordinates to specify the element location. Android: layout_x = "20px"
Android: layout_y = "12px" is a simple layout method. However, when you switch between the two elements vertically, problems often occur. In addition, computing is troublesome when multiple elements are involved.
Iv. 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" align left of the parent Element
Android: layout_alignparentright = "true" align 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.
6. Introduce the data storage method of Android
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 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 ).
Context. files generated by openfileoutput (string filename, int mode) are automatically stored in the/data/package name/Files directory, the full path is/data/package name/files/filename. Note that the filename parameter here cannot contain path delimiters (such "/").
Generally, files generated in this way can only be accessed in this APK. However, this conclusion refers to the use of context. openfileinput (string filename. In this way, each APK can only access files in ITS/data/package name/Files directory. The reason is very simple. The filename parameter cannot contain path delimiters, android will automatically search for a file named filename in the/data/package name/Files directory.
I. Use sharedpreferences to store data
First, describe the sharedpreferences storage method. It is a mechanism provided by Android to store some simple configuration information, such as the username and password of the login user. It uses the map data structure to store data, and stores data in key-value mode, which can be read and written in a simple way. The specific example 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: First call edit () to make it edit, then you can modify the data, and finally use commit () submit the modified data. In fact, sharedpreferences stores data to the device in XML format, under/data/<package name>/shares_prefs in file explorer of ddms. The preceding data storage result is used as an example. After opening the file, you can see the user_info.xml file. After opening the file, you can see:
<? XML version = "1.0" encoding = "UTF-8"?>
<Map>
<String name = "name"> moandroid </string>
<String name = "password"> sharedpreferences </string>
</Map>
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 commonly used method. The method for reading/writing files in Android is exactly the same as that in Java for implementing I/O. It provides openfileinput () and openfileoutput () to read files on the device. Filterinputstream and 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 which packages are referenced by the android SDK ?.
Iv. contentprovider
1. Introduction to contentprovider
When an application inherits the contentprovider class and overwrites the class to provide and store data, it can share its data with other applications. Although data can be shared externally using other methods, the data access method varies depending on the data storage method. For example, if data is shared externally using the file method, you need to perform file operations to read and write data; to use sharedpreferences 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 the data access mode .?
2. Uri class Introduction
Uri indicates the data to be operated. Uri contains two parts: 1. contentprovider, 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: 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 = new urimatcher (urimatcher. no_match );
// If the match () method matches the content: // com. Changcheng. SQLite. provider. contactprovider/contact path, 1 is returned.
Urimatcher. adduri ("com. Changcheng. SQLite. provider. contactprovider", "contact", 1); // Add a URI that needs to be matched. If yes, a matching code is returned.
// If the match () method matches the content: // com. Changcheng. SQLite. provider. contactprovider/contact/230 path, the return matching code is 2.
Urimatcher. adduri ("com. Changcheng. SQLite. provider. contactprovider", "contact/#", 2); // # It is a wildcard
2. after registering the URI to be matched, you can use urimatcher. the match (URI) method matches the input URI. If it matches, the matching code is returned. The matching code is the third parameter passed in by calling the adduri () method. Assume that it matches the 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 the getcontentresolver () method provided by activity. Contentresolver uses insert, delete, update, and query methods to operate data.
V. Summary
In the above five storage methods, we will 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 the data shared by other applications is obtained through contentresolver. To share data with external users by using files, you need to perform file operations to read and write data. To use sharedpreferences to share data, you need to use the sharedpreferences API to read and write data. The advantage of using contentprovider to share data is to unify the data access mode.
8. 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 in the <Application> node of 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. The bindservice () method is used to enable the Service. When the caller and the service are bound together, the service is terminated once the caller exits. 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 to the startservice () method will not create the service multiple times, but the onstart () method will be called multiple times. For a service started using startservice (), you can only call the context. stopservice () method to end the service. 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 () method is not called multiple times ). If the caller wants to unbind from the service being bound
You 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 the context. startservice () method
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.
Life Cycle methods 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
}});
}
}