Four components of Android basics---Activity

Source: Internet
Author: User

Android Basics Four Components-activity
    • 1. What is activity
    • 2.Activity life cycle
    • 3.Activity Life Cycle Demo
    • Communication between the 4.Activity
    • 5.Activity Load Mode
    • 6.Activity on-the-stack management
1. What is activity?

Activity is the user interface program, it is the basic function unit of Android application, its main function is to provide interface. Activity is the core class of Android, and the full name of the class is android.app.Activity. Activity is equivalent to the form (from) or Web program's page in the C/S program. Each activity provides a visual area. In this area, you can place various Android components, such as buttons, images, text boxes, and so on.
There is a OnCreate event method in the Activity class, which is typically initialized for acticity in this method. The Setcontentview method lets you set the view component to be displayed on the activity.
An Android app with an interface can consist of one or more activity. As for how these activities work, the dependencies between them depend entirely on the business logic between applications.

2.Activity life cycle

The 7 life cycle methods need to be invoked at different stages during activity building to destroy. These seven lifecycles are defined as follows:

    protected void onCreate(Bundle savedinstancestate) {}//Create the interface here, do some data initialization work;    protected void OnStart() {}//To this step becomes "user visible non-interactive" state;    protected void Onresume() {}//become and User-interactive, (in the activity stack system to manage these activity through the stack, that is, the current activity at the top of the stack, run out of pop-up stack, then back to the previous activity);    protected void OnPause() {}//To this step is visible but not interactive, the system will stop the animation and other CPU-consuming things. As you know from the above description, you should save some of your data here, because your program's priority is reduced and may be withdrawn by the system. The data that is stored here should be read in the Onresume.     protected void OnStop() {}//becomes invisible and is covered by the next activity    protected void Onrestart() {}protected void OnDestroy() {}//activity was wiped out.

The above 7 life cycles are called in a sequence of 4 stages, respectively,

    • Start Activity:oncreate, OnStart, and Onresume methods
    • Activity loses focus: OnPause and OnStop methods
    • Activity regain focus: Onrestart, OnStart, and Onresume methods
    • Close activity: The system executes 3 life cycle methods-onpause, OnStop, and Ondestory methods when activity is turned off

      The activity's life cycle is as shown

      You can see that activity consists of two loops, the first layer is onpause->onresume->onpause, and the second loop is onstop->onrestart->onstart->onresume- >onpause->onstop. We can talk about a two-layer cycle as a sub-lifecycle in the entire activity life cycle. The first layer becomes the focus life cycle, and the second layer is the visual life cycle. In other words, the first loop loops through the process of acquiring and losing the acitvity focus, and the activity is visible in this process. The second layer loops through the process of visible and invisible activity.
      Therefore, activity has the following three life cycles:

    • Overall life cycle: Oncreate->......->ondestroy.

    • Visual life cycle: Onstart->......->onstop.
    • Focus life cycle: Onresume->onpause.
3. Life Cycle Demo

The sample code is as follows:

 PackageCom.hlh.activitydemo;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.util.Log; Public  class mainactivity extends appcompatactivity {    Private StaticString TAG ="Mainactivity";@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); LOG.D (TAG,"OnCreate:"); }@Override    protected void OnStart() {Super. OnStart (); LOG.D (TAG,"OnStart:"); }@Override    protected void Onresume() {Super. Onresume (); LOG.D (TAG,"Onresume:"); }@Override    protected void OnPause() {Super. OnPause (); LOG.D (TAG,"OnPause:"); }@Override    protected void OnStop() {Super. OnStop (); LOG.D (TAG,"OnStop:"); }@Override    protected void Onrestart() {Super. Onrestart (); LOG.D (TAG,"Onrestart:"); }@Override    protected void OnDestroy() {Super. OnDestroy (); LOG.D (TAG,"OnDestroy:"); }}

Follow these steps to manipulate the application:
(1) Launch the application
(2) Press the home button on the phone to enter the main interface and then re-enter the application interface
(3) Close the application
After following the steps above, DDMS's logcat prints the following information:

From this example, we can clearly see the entire life cycle of the activity process.

Communication between the 4.Activity

In Android, different Activity instances may run in a process, or they may run in different processes. So we need a special mechanism to help us deliver messages between the Activity. In Android, a message is represented by a Intent object, a Intent object that contains not only the destination of the message, but also the content of the message, which is like an email, which should include not only the address of the recipient, but also the specific content. For a Intent object, the message "destination" is required, while the content is optional.
Intent is responsible for the operation of the action, the action involved in data, additional data description, Android based on this intent description, is responsible for finding the corresponding component, the intent passed to the calling component, and complete the call of the component. As a result, intent plays a role as a media intermediary, specifically providing information about the components that are called to each other, and decoupling the caller from the callee.
Through the following example we can well understand the communication between the activity, in the main interface click the button to jump to another activity, while the data to otheractivity, binding in TextView.
Mainactivity.java

 Public  class mainactivity extends appcompatactivity {    Private StaticString TAG ="Mainactivity";@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Button BT = (button) Findviewbyid (R.id.toother); Bt.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Intent Intent =NewIntent (mainactivity. This, Otheractivity.class); Intent.putextra ("MSG","Hello Activity");            StartActivity (Intent);    }        }); }}

Otheractivity.java

publicclass OtherActivity extends Activity{    @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_other);        TextView tv = (TextView) findViewById(R.id.tv);        Intent intent = getIntent();        //设置文本        tv.setText(intent.getStringExtra("msg"));    }}

Note: After you have created a new actvity, you must register the actvity in the tags in the androidmanifest.xml manifest file.

<activity android:name=".OtherActivity"/>

Application:

5.Activity Load Mode

Activity has four loading modes (Launchmode). Launchmode plays an important role in the process of multiple activity jumps, it can decide whether to generate new activity instances, whether to reuse existing instances, and whether to share a task with other activity. A brief introduction to a Task,task is an object with a stack structure, a task that manages multiple activity, launches an application, and creates a corresponding task.
The four loading modes of activity are as follows:
1.standard
2.singleTop
3.singleTask
4.singleInstance
We can configure the Android:launchmode property in Androidmanifest.xml for one of the above four kinds.
Here we combine examples to introduce these four kinds of lanchmode:
  1.standard
Standard mode is the default way to start, not to configure the Android:launchmode property, or you can specify a value of. We create an activity, named Firstactivity, to demonstrate the standard startup mode. The firstactivity code is as follows:

 Public  class firstactivity extends appcompatactivity {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_first);        TextView TextView = (TextView) Findviewbyid (r.id.tv); Textview.settext ( This. toString ());        Button button = (button) Findviewbyid (R.id.start); Button.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Intent Intent =NewIntent (firstactivity. This, Firstactivity.class);            StartActivity (Intent);    }        }); }}

The TextView in the Firstactivity interface is used to display the serial number of the current activity instance, and the button jumps to the next interface
Clicking on several button buttons in succession will cause the following behavior:



We found all firstactivity instances but the serial number is different, and we need to press the back key two times to return to the first firstactivity. Each jump system generates a new Firstactivity instance in the task and puts it on top of the stack, so we can see the original firstactivity instance when we press the back key.
Therefore, the standard startup mode is summed up, and a new instance is generated, regardless of whether there are any existing instances.
  2.singleTop
We android:launchmode= "Singletop" on the above basis for the specified attribute, and the system will handle the jump behavior according to the Singletop startup mode. We repeat the above several actions, will appear the following phenomenon:



We see this is different from standard results, three serial numbers are the same, that is, using the same firstactivity instance. If you press the back key, the program exits immediately. Jump when the system will first look in the stack structure to see if there is a firstactivity instance is at the top of the stack, if there is no longer generate new, but directly use. Perhaps some people will have doubts, I only see the stack only one activity, if it is a number of activity what to do, if not at the top of the stack? We will then pass an example to confirm the question.
Then create a new activity named Secondactivity, the code is as follows:

 Public  class secondactivity extends Activity{    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_second);        TextView TV = (TextView) Findviewbyid (r.id.tv); Tv.settext ( This. toString ());        Button button = (button) Findviewbyid (R.id.start); Button.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Intent Intent =NewIntent (secondactivity. This, Firstactivity.class);            StartActivity (Intent);    }        }); }}

Then change the previous firstactivity jump code to:

new Intent(FirstActivity.this, SecondActivity.class);  startActivity(intent);  

The demo results are as follows:



We see that the serial numbers of the two firstactivity are different, proving that a new firstactivity instance was generated when jumping from secondactivity to firstactivity.
We see that when jumping from secondactivity to firstactivity, the system discovers that there are firstactivity instances, but not at the top of the stack, and then regenerates an instance.
This is the Singletop startup mode, and if a corresponding activity instance is found to be at the top of the stack, it is reused and no new instances are generated.
   3.singleTask
Based on the above, we modify the properties of the firstactivity android:launchmode= "Singletask". The results of the demo are as follows:




We note that in the above process, the serial number of the firstactivity is constant, but the secondactivity serial number is not unique, indicating that a new instance was not generated when jumping from secondactivity to firstactivity. However, a new instance is generated when jumping from firstactivity to secondactivity.
In this jump process, the system found that there are firstactivity instances, and then no longer generate new instances, but based on the principle of the advanced stack firstactivity all the activity instances above the stack (such as secondactivity), Turns the firstactivity into a top-of-stack object that appears before the screen. If Secondactivity is also set to Singletask mode, can the secondactivity instance be unique? In our example is not possible, because each time from secondactivity jump to firstactivity, secondactivity instances are forced out of the stack, the next time firstactivity jump to Secondactivity, The existing secondactivity instance cannot be found, so a new instance must be generated. But if we have thirdactivity, let secondactivity and thirdactivity jump to each other, then the secondactivity instance can be guaranteed unique.
This is the Singletask mode, if a corresponding activity instance is found, the other activity instances above the activity instance are all out of the stack, so that the activity instance becomes the top of the stack object and appears before the screen.
   4.singleInstance
This startup mode is special because it enables a new stack structure, places the acitvity in the new stack structure, and guarantees that no other activity instances will enter.
We modified Firstactivity's launchmode= "standard", secondactivity launchmode= "SingleInstance", because of the multiple stack structure involved, We need to show the ID of the current stack structure in each activity, so we add the following code for each activity:

TextView textView = (TextView) findViewById(R.id.tv);textView.setText("current task id: " + this.getTaskId());

Then demonstrate this process:


We found that the two activity instances were placed in different stack structures. You can find that when you jump from firstactivity to Secondactivity, you re-enable a new stack structure to place the secondactivity instance, and then press the back key again to return to the original stack structure.

6.Activity on-the-stack management

Android uses stacks for activity management. You may not know what a stack is, now to explain that the stack refers to the data structure of the order of items, only one end (called the top of the stack) to insert and delete data items, an advanced post-out data structure. In Android, tasks are used to store activity. The task is briefly described in section fifth. Here is a detailed introduction
Definition of task on Google's website:

a task is A  Collection of  activities that users interact with  when performing a the certain job. The activities is arranged in  a  Stack (the  back stack), in   The  order in  which each  activity is Opened.  

Simply put, a task is a set of specific sets of activities that are placed in a stack (stack) in the order in which each is opened. The activity stack can consist of one or more tasks.
When an app is started, a task is created for it to place the activity, and by default, when one activity initiates another activity, two activity is placed in the same task, which is pressed into the task stack where the former resides. When the user presses the back key, the latter pops out of the stack, and the former is displayed on the screen. It is important to emphasize that when you start the activity of other applications, two activity seems to belong to the same app for the user, and these two activity all create their own task stacks. The task and task in the system are independent of each other, when we run application A, press the home key to go back to the main screen, launch another application B, when application A's task is transferred to the background, the task of the newly launched application B is transferred to the foreground, and the top activity of the stack is displayed on the screen. When you press the home key again to return to the start of application A, the task stack for a application is transferred to the foreground, and the system retains all the activity instances of the task.
  
  

Four components of Android basics---Activity

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.