1,Talk about your Activity?
The best way to return to this interview question "What Do you understand" is to use your own understanding, which involves some technical terms and occasionally speaks a few English letters. Of course, if you are a good guy, you can say it in depth, as long as you don't want to say anything without purpose. Around a main line. In this case, if you are proficient in one aspect, you should be directed towards your proficiency. The interviewer may follow your ideas. However, I have a lot of questions about Android in interviews. I have a lot of questions about java.
In layman's terms, Activity is the facade of an application. It can also be understood as a page in a WEB program. Of course, unlike pages in a web program, A page in the web may be a pure display page without any interaction with the user, and almost all the activities will interact with the user. Of course, there are essential differences between the two in architecture. The interaction between the Activity and the user is completed by triggering different events of the UI. Web programs interact with each other through requests and responses. There are also many general ideas in android, such as opening another Activity in an Activity that is not in the same application. This is unimaginable in other programs. Of course, the starting point of this design is to save system resources. From the View layer perspective, Activity carries different controls for user interaction. From the control layer, that is, the internal logic, the Activity needs to maintain the status of each interface, and there will be a lot of persistent operations behind it. Including proper management of various stages of the lifecycle. (If the lifecycle is introduced, you may be asked about this ).
The following is a documented answer: (the best way to answer is to combine the two)
Activity is one of the four android components. It is independent and serves as a carrier for user-program interaction. Almost all activities interact with users. Activity creates a window. You can use setContentView to place the required UI in the window. Any application can call a separate Activity.
Secondly, the inheritance relationship between Activity → ContextThemeWrapper → ContextWrapper → Context
In the end, the subclass of most activities must implement the following two interfaces:
The onCreate (Bundle savedInstanceState) interface is the place where the activity is initialized. you can call setContentView (int) to set the UI defined in the resource file, and use findViewById (int) to obtain the window defined in the UI.
The onPause () interface is the place where the user is about to leave the activity. Here, any modifications should be submitted (usually used for ContentProvider to save data ).
All activities must be registered in the list file before they can be used.
2,Activity?
Activities in the system are managed by an Activity stack. When a new Activity is started, it will be placed on the top of the stack to become a running Activity. The previous Activity will be kept in the stack and will not be placed on the foreground until the new Activity exits.
Activity has four essential differences:
1) In the front-end of the screen (the top of the Activity stack), it is called the active or running status)
2) If an Activity loses focus, but it is still visible (a new non-full-screen Activity or a transparent Activity is placed on the top of the stack), it is called a Paused ). A paused Activity remains alive (maintains all States, member information, and connections with the window manager), but is killed when the system memory is extremely low.
3) If an Activity is completely overwritten by another Activity, it is called the Stop State (Stopped ). It still maintains all States and member information, but it is no longer visible, so its window is hidden. When the system memory needs to be used elsewhere, the Stopped Activity will be killed.
4) if an Activity is in the Paused or Stopped status, the system can delete the Activity from the memory. The Android system deletes the Activity in two ways or requires the Activity to end, or directly kill the process. When the Activity is displayed to the user again, it must start and reset the previous status.
Activity provides seven life cycle methods:
OnCreate (), onStart (), onResume (), onPause (), onStop (), onDestory (), onRestart (). There are three key loops in these seven lifecycle methods. In fact, the official picture is very clear, but it is estimated that few people can patiently try to figure it out. In other words, you can use a different way. See the figure below:
1) The following figure shows the complete lifecycle of an Activity, from onCreate (Bundle) to onDestroy. Activity sets all the "Global" statuses in onCreate () and releases all resources in onDestory.
First, we run the program. This is to open MainActivity and call onCreate-> onStart-> onResume in turn. At this time, MainActivity is at the top of the stack and the Activity that interacts with us is at the top of the stack. Then, when I press the return key, onPause-> onStop-> onDestory will be called in sequence. This is a complete life cycle.
2) Visible lifecycle, starting from onStart () to onStop. To put it bluntly, one Activity is completely overwritten by another activity and then returned to the foreground. This process is called a visible life cycle.
First, open the OtherActivity window. In this case, the MainActivity will be overwritten. OnPause-> onStop is called in sequence. When the memory is insufficient, the system will also kill the MainActivity process.
Then, press the return key and MainActivity will call onRestart-> onStart-> onResume when it returns to the foreground.
3) the life cycle of the front-end, from onResume () to onPause. During this period, the Activity is at the top of all activities and interacts with users. The Activity can regularly switch between the resumed and paused states. To put it bluntly, one Activity overwrites the other Activity, but it is not completely overwritten.
First, open OtherActivity, which is opened in dialog box mode and suspended on MainActivity. OnPause () called directly ().
Then we press the return key to call onResume. For a State that is not completely overwritten, it will only switch between the onPause and onResume methods.
Note:What is the life cycle when the screen changes? For example, the vertical screen is changed to a horizontal screen. Use onPause-> onStop-> onDestroy-> onCreate-> onStart-> onResume in sequence. This process. It will destroy the original activity and recreate it.
3,AcitvityStartup Mode?
For such a question, I will write an example myself. I will observe it to understand it.
Activty supports four startup modes. LaunchMode:
Standard: each time a new activity window is started (new Operation)
SingleTop: if it is a target activity at the top of the stack, It will be opened directly. Otherwise, a new activity window (new) will be opened ).
SingleTask and singleInstance are basically the same. The difference is that if the root activity is set to singleTask, the enabled activity is also in the same task, that is, the taskId is the same .. If the root activity is set to singleInstance, the activated activity is in the new task, that is, there is only one activity in the stack, and the taskid is different .. The rest is the same.
4,In onCreateBundle savedInstanceState in MethodWhat is the role of this parameter?
The onCreate method has the saveInstanceState parameter. In fact, this parameter corresponds to two methods.
Void onSaveInstanceState (Bundle outState); void onRestoreInstanceState (Bundle savedInstanceState ). When an activity becomes "easy" to be destroyed by the system, this method is called when the system destroys your Activity in the case of insufficient memory or other exceptions. Note that it is called by the system and your Activity is passively destroyed. You can save the data during destruction. Then take it out in the onCreate method. Under what circumstances can these two methods be triggered?
1) when the user presses the HOME Key.
This is obvious. The system does not know how many other programs you want to run after you press HOME, and naturally does not know whether activity A will be destroyed. Therefore, the system will call onSaveInstanceState, this gives users the opportunity to save some non-permanent data. This principle is applicable to the following situations:
2) press the HOME Key and select to run other programs.
3) press the power button (close the screen.
4) when you start A new activity from activity.
5) when switching the screen direction, for example, switching from the portrait screen to the landscape screen.
Before the screen switch, activity A is destroyed, and activity A is automatically created after the screen switch. Therefore, onSaveInstanceState will be executed.
All in all, onSaveInstanceState calls follow an important principle, that is, when the system destroys your activity "without your permission", the onSaveInstanceState will be called by the system, which is the responsibility of the system, because it must provide an opportunity for you to save your data (of course, if you do not save it, you just need ).
As for the onRestoreInstanceState method, it should be noted that the onSaveInstanceState method and the onRestoreInstanceState method are not necessarily called in pairs, and the onRestoreInstanceState is called on the premise that, activity A is indeed destroyed by the system. If it is only possible to stay there, the method will not be called. For example, when activity A is being displayed, the user presses the HOME Key to return to the main interface, and then the user returns to activity A. In this case, activity A is generally not destroyed by the system because of memory, so the onRestoreInstanceState method of activity A will not be executed.
In addition, the bundle parameter of onRestoreInstanceState will be passed to the onCreate method. You can also choose to restore data in the onCreate method.
5,About BroadCastRceiver?
Broadcast receiver, one of the four android components, is also the only component that can be dynamically registered.
1) The broadcast receiver is a component that focuses on receiving and processing broadcast notifications. Many broadcasts are derived from systems-such as notifying time zone changes, low battery, taking a picture, or changing language options. Applications can also be broadcast-for example, to notify other applications that some data has been downloaded and is available.
2) an application can have any number of broadcast recipients to respond to all notifications that interest it. All receivers inherit from the BroadcastReceiver base class.
3) The broadcast receiver does not have a user interface. However, they can start an activity to respond to the information they receive, or use icationicationmanager to notify users. Notifications can be used in many ways to attract users' attention-flashing back lights, vibrations, and playing sounds. In general, a persistent icon is placed on the status bar. You can open it and get the message.
6,What are broadcast types? What are their differences?
Broadcast is divided into two different types: Normal broadcast (Normal broadcasts) and Ordered broadcast (Ordered broadcasts )". Normal broadcast is completely asynchronous and can be received by all receivers at the same time (logically). The efficiency of message transmission is relatively high, but the disadvantage is: the receiver cannot pass the processing result to the next receiver, and cannot terminate the broadcast Intent propagation.
However, ordered broadcast is based on the priority level stated by the receiver, and the receiver receives the broadcast in sequence. For example, if the level of A is higher than that of B and the level of B is higher than that of C, broadcast is first transmitted to A, then to B, and finally to C. Priority Level Declaration is in the android: priority attribute of intent-filter element. The higher the number, the higher the priority level. value range:-1000 to 1000. You can also call setPriority () of the IntentFilter object at the priority level (). The receiver of an ordered broadcast can terminate the spread of the broadcast Intent. Once the spread of the broadcast Intent is terminated, the subsequent receiver cannot receive the broadcast.
In addition, the receiver of ordered broadcast can pass the data to the next receiver. For example, after A gets the broadcast, it can store the data in its result object. When broadcast is sent to B, B can obtain the data stored by A from the result object of.
Context. sendBroadcast ()
A normal broadcast is sent, and all subscribers have the opportunity to obtain and process it.
Context. sendOrderedBroadcast ()
An ordered broadcast is sent, and the system will execute the receiver one by one based on the priority level stated by the receiver,
The previous receiver has the right to terminate the broadcast (BroadcastReceiver. abortBroadcast (). If the broadcast is terminated by the previous receiver, the subsequent receiver will no longer be able to obtain the broadcast. For ordered broadcast, the previous receiver can store the data in the result object through the setResultExtras (Bundle) method, and then pass it to the next receiver. The next receiver uses the code: Bundle bundle = getResultExtras (true )) you can obtain the data stored by the previous receiver in the result object.
7,Broadcast lifecycle?
The broadcast life cycle is very short. After sending, intent will be sent to AndroidManifest. check whether there are matched actions in the xml file. If there is a matched action, it will call the Receiver, obtain the Receiver object, and then execute the onReceive method. At this time, the Receiver object will be useless, when we click the button again, we will obtain the object again, which is the life cycle of BroadcastReceiver.
You cannot perform some time-consuming operations in BroadcastReceiver. the ANR (Application No
Response) dialog box.
If you need to complete a time-consuming task, you should send Intent to the Service, which is done by the Service. subthreads cannot be used here, because the life cycle of BroadcastReceiver is very short, and the subthread may not end yet, And BroadcastReceiver will end first. once BroadcastReceiver ends, the process where BroadcastReceiver is located is easily killed first when the system requires memory because it is a blank process (process without any active components ). if its host process is killed, the working sub-thread is also killed. therefore, it is unreliable to use sub-threads.
8,Two types of registration BroadcastReceiver?
Use the method registered in manifest to register BroadcastReceiver. Even if your application is not started or has been disabled, the BroadcastReceiver will continue to run, such a running mechanism may cause problems for software users. As a program developer, we hope to have a flexible mechanism to bind and unbind BroadcastReceiver. Android has also considered these issues. Therefore, the Context class provides the following two functions that can be registered in the Code:
I. registerReceiver (receiver, filter );
This function registers a BroadcastReceiver to an application. This function receives two parameters. The first parameter is the BroadcastReceiver object to be registered, and the second parameter is an IntentFilter. The first parameter is very easy to understand. The second parameter defines which Intent can trigger the registered BroadcastReceiver object.
Ii. unregisterReceiver (receiver );
This method is very simple and used to unbind BroadcastReceiver. Once the release is complete, the response BroadcastReceiver will no longer receive the Intent broadcast by the system.
Two Methods for registering BroadcastReceiver
1. Register in the application code
Register BroadcastReceiver
RegisterReceiver (receiver, filter );
Cancel BroadcastReceiver Registration
UnregisterReceiver (receiver );
2. Register in AndroidManifest. xml
<Cycler android: name = "SMSReceiver">
<Intent-filter>
<Action android: name = "android. provider. Telephony. SMS_RECEIVED"/>
</Intent-filter>
</Cycler>
Comparison of the two methods for registering BroadcastReceiver:
Now that we have learned two ways to register BroadcastReceiver, consider the applicable scenarios of the two methods:
I. the first method of registration ensures that after the application is installed, BroadcastReceiver is always active and is usually used to listen for changes in the system status, such as cell phone power and wifi Nic status (of course, monitoring these things also depends on the needs of the software ). For such BroadcastReceiver, operations are usually performed after a specific system event is generated. For example, when a Wi-Fi network card is opened, a prompt is given to the user;
Ii. The second method of registration is more flexible than the first method, so the registered BroadcastReceiver is usually used to update the UI status. Generally, you can use this method to register BroadcastReceiver when an Activity is started. Once a broadcast event is received, you can update the control of the current Activity in the onReceive method. However, if the Activity is invisible, you should call the unregisterReceiver method to cancel registration.
9,What is the role of sticky broadcast? How to use it?
Sticky broadcast is mainly used to solve the problem. After the broadcast is sent, the dynamically registered receiver can also receive the broadcast. For example, first send a broadcast, and my receiver dynamically registers through a button in the program. If it is not a sticky broadcast, the receiver cannot receive the broadcast after I register it. This means that by sending a sticky broadcast, you can receive the broadcast after I dynamically register the receiver.
Usage:
// Send sticky Broadcast
Public void sendStickyBroadCast (){
Intent intent = new Intent ();
Intent. setAction ("com. iteye. myreceiver. action ");
Intent. putExtra ("name", "tom ");
This. sendStickyBroadCast (intent );
}
The permission to send sticky broadcasts is also required: <uses-permission android: name = "android. permission. BROADCAST_STICKY"/>
// Dynamically register the broadcast Receiver
MyReceiver mr = new MyReceiver ();
IntentFilter filter = new IntentFilter ();
Filter. addAction ("com. iteye. myreceiver. action ");
Filter. addCategory (Intent. CATEGORY_DEFAULT );
Intent ii = this. registerReceiver (mr, filter );
String n = ii. getStringExtra ("name ");
Toast. makeText (this, "the dynamically registered receiver is complete and the consumer receives the sticky broadcast. name =" + n, 1). show ();
10, How to control the permissions of the recipient or sender?
1)What if the Broadcast Sender requires the receiver to have a certain permission to receive the broadcast?
/**
* Send broadcast, specifying the recipient's permission
* SendBroadcast (I, "com. iteye. permission. assumer"); // specify the recipient's permissions.
*/
Public void sendBroadcast (){
// Send broadcast with implicit intent
Intent I = new Intent ();
I. setAction ("com. iteye. Er er. action ");
I. putExtra ("name", "tom ");
This. sendBroadcast (I, "com. iteye. permission. Cycler ");
Log. I ("Other", ". send OK! ");
}
In the configuration file, the receiver must have this permission to receive broadcasts.
First, define the permission: <permission android: name = "com. iteye. permission. Cycler"/>
Then, declare the permission: <uses-permission android: name = "com. iteye. permission. policer"/>
Then the receiver can receive the sent broadcast.
2)What if the receiver requires the sender to have a certain permission before receiving your broadcast?
<! -- Register the broadcast Receiver
Android: permission: the sender must have the specified permission to receive the broadcast.
-->
<Cycler android: name = ". mypolicer" android: permission = "com. permission. sender">
<Intent-filter android: priority = "100">
<Action android: name = "com. iteye. Er er. action"/>
<Category android: name = "android. intent. category. DEFAULT"/>
</Intent-filter>
</Cycler>
Even if the filter matches, if the sender does not have the corresponding permissions, the receiver will not receive its broadcast.
From: sweat for perfection, with experience!