Android four basic components (1) activity and Broadcastreceive broadcast receivers

Source: Internet
Author: User

The four basic components of Android are Activity,service services, content provider contents providers, Broadcastreceiver broadcast receivers.

First, Activity

(1) In an application, an activity is usually a separate screen that shows some controls that can also listen and handle the user's events to respond.

(2) Communication between activity through intent. In the description structure of intent, there are two most important parts: the data corresponding to the action and the action.

(3) Typical action types are: M AIN (Activity Portal), VIEW, PICK, EDIT, etc. The data corresponding to the action is represented in the form of a URI. For example, to see a person's contact, you need to create a intent with the action type view and a URI that represents the person.

(4) A class related to it is called Intentfilter. As opposed to intent is a valid request to do something, a intentfilter is used to describe which intent an activity (or intentreceiver) can manipulate. An activity if you want to display a person's contact information, you need to declare a intentfilter, this intentfilter to know how to handle the view action and the URI that represents a person. Intentfilter needs to be defined in Androidmanifest.xml. By parsing various intent, navigating from one screen to another is simple. When navigating forward, the activity invokes the StartActivity (Intent myintent) method. The system then looks in the Intentfilter defined in all installed applications to find the activity that best matches myintent's intent. After the new activity receives the MYINTENT notification, it starts to run. This mechanism provides two key benefits when the StartActivity method is invoked to trigger an action that parses the myintent:

A, activities is able to reuse a request from other components in the form of intent;

B, activities can be replaced at any time by a new activity with the same intentfilter.

(5) The activity component containing the filter in the Androidmanifest file is the default startup class when the program starts, the system automatically calls it

<intent-filter>     <action android:name="android.intent.action.MAIN" />     <category android:name="android.intent.category.LAUNCHER" /></intent-filter>

(6) The life cycle of the activty is the life cycle of the process in which it resides.

1).一个Activity的启动顺序:

OnCreate ()-->onstart ()-->onresume ()

2).当另一个Activity启动时:

First activity OnPause ()--second activity onCreate ()-->onstart ()-->onresume ()
--First activity onStop ()

3).当返回到第一个Activity时:

Second activity OnPause ()--First activity Onrestart ()-->onstart ()-->onresume ()
--second activity onStop ()-->ondestroy ()

4).一个Activity的销毁顺序:

(Condition one) onPause ()--
(case two) OnPause ()-->onstop ()--
(Situation III) OnPause ()-->onstop ()-->ondestroy ()

Each activity is in a certain state, and for the developer it is impossible to control its application in one state, which is done by the system.

However, when the state of an activity changes, the developer can obtain the relevant notification information by calling ONXX ().

When implementing the Activity class, these methods can be called by overwriting (override) when you need to process them.
OnCreate: When the activity starts for the first time, the method is triggered, at which time the activity initialization can be completed.
The OnCreate method has a parameter that can be empty (null), or it can be a state information that was previously saved by calling the Onsaveinstancestate () method.
Second, OnStart: The trigger of the method indicates that the activity will be displayed to the user.
Onresume: When an activity interacts with the user, the method is triggered.
Iv. OnPause: Triggers This method when an activity that is running in the foreground is running in the background because other activities require the foreground to run. This is the time to persist the state of the activity, such as the database record being edited.
V. OnStop: Triggers the method when an activity no longer needs to be presented to the user. If the memory is tight, the system will end the activity directly without triggering the OnStop method. So saving state information should be done at onpause time, not onstop. Activities that are not running in the foreground will be stopped or the Linux management process can end these activities at any time in order to reserve enough storage space for the new activity. Therefore, it is important for developers to always keep this principle in mind when designing applications. In some cases, the OnPause method may be the last method of activity triggering, so developers need to save the information at this time.
Onrestart: Triggers the method when an activity in the stopped state needs to be presented to the user again.
Vii. OnDestroy: Triggers the method when the activity is destroyed. As with the OnStop method, if the memory is tight, the system will end the activity directly without triggering the method.
· Onsaveinstancestate: This method is called by the system, allowing the activity to save its previous state, such as where the cursor is located in a string of strings.
Typically, developers do not need to override this method, and in the default implementation, all state information for the user interface components involved in the AutoSave activity has been provided.

Activity stack

The above mentioned that the developer is unable to control the state of the activity, then the state of activity and what logic to operate it? This is about knowing the Activity stack.
The state of each activity is determined by its position in the activity stack, which is a last-in-first-out LIFO, which contains all the queues that are running activity.
When a new activity is started, the activities currently active will be moved to the top of the event stack.
If the user returns using the Back button, or the activity at the foreground ends, the active activities are removed from the stack and the activity on the stack is moved up and active. As shown in the following:

The priority of an application is affected by the activity of the highest priority. When deciding whether an application wants to end the release of resources, Android memory management uses stacks to prioritize activity-based applications.
Activity status
Activity is generally considered to have the following four states:
Active: When an activity is at the top of the stack, it is visible, focused, and acceptable to user input. Android tries to keep it active as much as possible, killing other activities to ensure that the active activity has enough resources to use. When another activity is activated, this will be paused.
Pause: In many cases, your activity is visible but it has no focus, in other words it is paused. A possible reason is that a transparent or non-full-screen activity is activated.
When paused, an activity is still active, but it is not acceptable to user input. In very special cases, Android will kill a suspended activity to provide sufficient resources for active activity. When an activity becomes completely hidden, it will become a stop.
Stop: When an activity is not visible, it "stops". This activity will still save all its status and membership information in memory. However, when memory is needed elsewhere, it will be the most likely to be freed of resources. When an activity is stopped, an important step is to save the data and the current UI state. Once an activity exits or shuts down, it becomes a ready-to-use state.
To be used: After an activity is killed and put in front, it is ready to use. The pending acitivity is removed from the activity stack and needs to be restarted before it is displayed and available.
Four modes of loading for activity
In Android's multi-activity development, jumps between activity may need to be in a variety of ways, sometimes in a normal way to generate a new instance, sometimes to jump to an activity instance instead of generating a large number of repetitive activity. The load mode is the decision to start a jump to an activity instance in the same way.
In Android, there are 4 activation modes for the activity, namely:
Standard: Standard mode, a call to the StartActivity () method produces a new instance.
Singletop: If an instance already exists at the top of the activity stack, it does not produce a new instance, but simply invokes the newinstance () method in activity. 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, which will be used for each subsequent invocation and will not produce a new instance.
SingleInstance: This is basically the same as Singletask, there is only one difference: In this mode the activity instance is in the task, only the activity instance, cannot have other instances.
These startup modes can be set in the feature manifest file Androidmanifest.xml, in the Launchmode property.
There are some flags in the relevant code that can be used, for example, if we want to enable only one instance, then we can use the INTENT.FLAG_ACTIVITY_REORDER_TO_FRONT flag, which means: if this ACTIVITY has been started, Instead of creating new activity, just add the activity instance to the top of the stack.
  

Intent intent = new Intent(ReorderFour.this, ReorderTwo.class);  intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);  startActivity(intent);

The activity's load mode is controlled interactively by the attribute value of the activity element in the flag and manifest files that are set in the intent object that initiates the activity.
Here are some of the features that affect the load pattern
The core intent flag is:
Flag_activity_new_task
Flag_activity_clear_top
flag_activity_reset_task_if_needed
Flag_activity_single_top

The core features are:
Taskaffinity
Launchmode
Allowtaskreparenting
Cleartaskonlaunch
Alwaysretaintaskstate
Finishontasklaunch

The difference between the four loading modes
The difference between the owning task
In general, the target task for the activity of "standard" and "Singletop", and the sender of the received intent in the same task, is the equivalent of who calls it, and who is in the same task.
Unless intent includes parameter flag_activity_new_task. If the Flag_activity_new_task parameter is supplied, it is launched into another task.
"Singletask" and "singleinstance" always use the activity to be started as the root element of a task, and they will not be launched into a different task.
Whether multiple instances are allowed
"Standard" and "singletop" can be instantiated multiple times and can exist in different tasks; A task can include multiple instances of an activity when instantiated;
"Singletask" and "singleinstance" restrict the generation of only one instance, and are the root elements of a task.
Singletop requires that if the stack top already has an instance of the activity to create when the intent is created, the intent is sent to the instance without creating a new instance.
Allow other activity to exist within this task
"SingleInstance" exclusively a task, other activity cannot exist in that task;
If it launches a new activity, regardless of the new activity's launch mode, the new activity will run in another task (as with the Flag_activity_new_task parameter).
The other three modes can coexist with other activity.
Whether to generate a new instance every time
"Standard" will generate a new instance of activity for each boot intent;
The activity of "singletop" if it is at the top of a task's stack, does not generate a new instance of the activity, directly using the instance at the top of the stack, otherwise, generates an instance of the activity.
Like what:
Now the task stack element is a-b-c-d (d at the top of the stack), this time to send a start intent D, if D is "standard", then a new instance of D is generated, the stack becomes a-b-c-d-d.
If D is singletop, a new instance of D will not be produced, and the stack state is still a-b-c-d
If at this time to B hair intent, whether B launchmode is "standard" or "singletop", will generate a new instance of B, the stack status becomes A-b-c-d-b.
"SingleInstance" is the only activity on its stack, which is reused every time.
"Singletask" if at the top of the stack, accept intent, otherwise the intent will be discarded, but the task will still return to the foreground. When the existing activity instance processes the new intent, the Onnewintent () method is called, and if a intent is generated to generate an activity instance, the user can return to the previous state via the back key If an activity already exists to handle the intent, the user cannot return to the previous state by pressing the back key.

Second, broadcastreceive broadcast receiver

Your app can use it to filter external events only to receive and respond to an external event of interest, such as when the phone is being called, or when the data network is available. The broadcast receiver does not have a user interface. However, they can start an activity or serice to respond to the information they receive, or use Notificationmanager to notify the user. Notifications can be used in a variety of ways to attract users ' attention-flashing back lights, shaking, playing sounds, and more. In general, a persistent icon is placed on the status bar, and the user can open it and get the message.

Broadcast type:

General broadcast, sent via Context.sendbroadcast (Intent myintent)

Ordered broadcast, sent through Context.sendorderedbroadcast (intent, Receiverpermission), the 2nd parameter of the method determines the level of the broadcast, the level value is between 1000 to 1000, the greater the value, The higher the priority of the transmission, the level at which the broadcast receiver receives the broadcast (which can be set to 2147483647 by priority in the Intentfilter), the order received at the same level is random, and then to the low level of the broadcast, A high level or the same level of first-time broadcasts can be truncated by the Abortbroadcast () method so that other receivers cannot receive the broadcast, and other constructors

Asynchronous broadcasts, sent through Context.sendstickybroadcast (Intent myintent), are also Sendstickyorderedbroadcast (Intent, Resultreceiver, Scheduler, Initialcode, Initialdata, Initialextras) method, the method has the characteristics of an orderly broadcast, and also has the characteristics of asynchronous broadcasting; Send asynchronous broadcast to: permission, receive and process the intent, the broadcast still exists, Until you call Removestickybroadcast (intent) to remove it.

Note: The intent parameter when sending a broadcast differs from the intent that contex.startactivity () initiates, which can be called by multiple broadcast receivers that subscribe to it, which can only be called by one (activity or service)

To listen to the broadcast intent steps:

1> writes a class that inherits Broadcastreceiver, overrides the OnReceive () method, and the broadcast sink is active only when it executes the method. When OnReceive () returns, it is inactive, note: In order to ensure the smooth user interaction process, some time-consuming operations to be placed in the thread, such as the class name Smsbroadcastreceiver

2> Register the broadcast receiver, register there are two methods for the dynamic registration of the program and the static registration in the Androidmanifest file (can be understood as registered in the system) as follows:

    静态注册,注册的广播,下面的priority表示接收广播的级别"2147483647"为最高优先级
<receiver android:name=".SMSBroadcastReceiver" >  <intent-filter android:priority = "2147483647" >    <action android:name="android.provider.Telephony.SMS_RECEIVED" />  </intent-filter></receiver >

Dynamic registration, typically registered within onresume () when activity is interactive broadcastreceiver

IntentFilter intentFilter=new IntentFilter("android.provider.Telephony.SMS_RECEIVED");registerReceiver(mBatteryInfoReceiver ,intentFilter);//反注册unregisterReceiver(receiver);

Attention:

1. The life cycle is only about 10 seconds, if within onreceive () do more than 10 seconds of things, will report the ANR (Application no Response) program unresponsive error message, if you need to complete a more time-consuming work, should be sent Intent to Service, which is done by the service. It is not possible to use a child thread here because the Broadcastreceiver life cycle is short, and the child thread may not have finished broadcastreceiver before it ends. Once the broadcastreceiver is over, the broadcastreceiver process can easily be killed when the system needs memory because it belongs to the empty process (the process without any active components). If its host process is killed, then the working child thread will be killed. So using sub-threading to solve is unreliable

    1. The dynamic registration of the broadcast receiver also has the feature that when the activity used to register is turned off, the broadcast fails. Static registration does not need to worry about whether the broadcast receiver is turned off, as long as the device is turned on and the broadcast receiver is open. This means that even if the app itself doesn't start, the app's subscription broadcast will work on it when triggered.

System common broadcast intent, such as start-up, battery power change, time change and other broadcast

Activity and Broadcastreceive broadcast receivers for Android four basic components (1)

Related Article

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

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.