Android Four Components--activity

Source: Internet
Author: User

Activity is one of the four components of Android and one of the most important components. As a component that interacts with the user, we can compare activity to a folder window on a Windows system, an interface that interacts with the user. Further, when we pick up the android to turn on the dial function, the interface that shows the dial is actually an activity, and of course, to a larger extent, any interface displayed on the mobile phone screen is activity.

Official description of the activity

Activity is a component of an application that provides an area on the screen that allows users to do interactive actions, such as making a phone call, taking a photo, sending an email, or displaying a map! Activity can be interpreted as a window that draws the user interface, which fills the entire screen or is smaller or floats above the other windows!

From the above paragraph, we can get the following information:

    1. Activity is used to display the user interface and the user interacts with the activity to complete the action
    2. An app allows multiple activity

RELATED links:

    • Activity Beginners First Practice
    • Activity first glimpse of the doorway
    • Activity presenting illegal weapons
    • Activity of four components

The concept of 1.Activity and the life cycle diagram of the activity:

Precautions:

1. OnPause () and OnStop () are invoked on the premise that a new activity! is opened The former is the state of the old activity, and the latter is invisible to the old activity!
2. In addition, the pro-test: Alertdialog and Popwindow will not trigger the above two callback methods ~

There are a total of seven life cycle methods for activity. The so-called life cycle, is the activity between the various state transitions, the system will be a callback of its various life cycle functions, but also let us according to business needs, rewrite the various life cycle methods to implement software in the various state of business logic.

Start activity to run State:

OnCreate (), OnStart (), Onresume (), the interface is fully displayed

Run state to paused state:

Interface full Display---onPause () interface is partially obscured

Suspend state to run state:

Interface is partially obscured---onresume () interface fully displayed

Run state to stop state:

Interface full display, OnPause (), OnStop (), fully covered

Stop state to run state:

Interface complete Coverage--onrestart (), OnStart (), Onresume (), fully display

Exit activity:

Interface full display, OnPause (), OnStop (), interface full cover, OnDestroy (), Activity end life cycle

PS: When the system memory is tight, the system can release the activity to obtain the resources, priority to release the inactive activity, the second is the activity of the temporary state, and the running state of the acitivity is generally impossible to be forcibly released, Unless there is an extreme lack of resources (this time directly crashes ...) ), when the activity is released, directly into the extinction, it is important to note that OnDestroy () will not be executed, so it is inappropriate to save the data in OnDestroy processing, can be in onsaveinstancestate () The important data are processed accordingly.

Activity three states:

    • Running status : When the activity is at the forefront of the screen, when the actiivity is fully displayed in the user's interface and can get the focus, it can respond to events such as the user's touch screen, which is now running. The user is visible and can be interactively
    • paused state : When activity is obscured by other activity, but still partially visible, it is paused, and when it is paused, the activity still updates the UI, but at this point it cannot get the focus, that is, it will not respond to events such as user touch, back, etc. user visible, non-interactive
    • Stop State : When the activity is completely obscured by another activity, the stop state does not mean that the activity is stopped and is understood to be running in the background. However, if the system needs memory, the activity releasing resources will take precedence over the stopped state, so the important data should be saved when the activity goes to a stopped state. The user is not visible, nor is it interactive

In addition, the life cycle of a screen cut call is as follows:

Portrait screen, horizontal screen (call once life cycle)

OnPause (), OnStop (), OnDestroy (), OnCreate (), OnStart (), Onresume ()

Vertical screen, horizontal screen (call two life cycle)

If you do not want to invoke the life cycle method when you switch the screen, you can do the following:

1, do not set the activity of the android:configchanges, the screen will recall the various life cycle, cut across the screen will be executed once, cut the vertical screen will be executed twice

2, set the activity android:configchanges= "orientation", the screen will recall the various life cycle, cut horizontal, vertical screen will only be executed once

3, set the activity android:configchanges= "Orientation|keyboardhidden", the screen will not recall the various life cycle, will only execute onconfigurationchanged method

The difference between 2.activity/actionbaractivity/appcompatactivity:

Before you start to talk about creating an activity, say one of these three differences: activity doesn't have to be said, the latter two are proposed for the sake of the low version compatibility, they are under the V7 package, Actionbaractivity has been discarded, from the name to know, Actionbar~, and after 5.0, was deprecated by Google, now with ToolBar ... And we are now creating an activity in Android studio The default inheritance will be: appcompatactivity! Of course you can write only activity, but Appcompatactivity offers us something new! Two select one, Just you like~

The 3.Activity creation process

the four components of Android, as long as you define, no matter what you use, you have to declare this component in the Androidmanifest.xml, otherwise the runtime program will exit directly, the report classnotfindexception ...

4. Several ways to start an activity

in Android We can start a new activity in the following two ways, notice how this is started, not the boot mode!! Divided into display start and implicit start!

1. Explicit start: Start with the package name, as follows:

① the most common:

StartActivity(newIntent(current Act).  Thisis the Act to start.  Class));           
② through Intent's componentname:
ComponentNamecn= New componentname("The fully qualified class name of the current Act","Starting the fully qualified class name of Act") ;  Intent Intent = new Intent() ;  Intent.  SetComponent(cn) ;  StartActivity(intent) ;             
Specify package name when initializing intent:
Intent=newIntent("Android.intent.action.MAIN");  Intent.  Setclassname("The fully qualified class name of the current Act","Starting the fully qualified class name of act");  StartActivity(intent);              

2. Implicit start: Through the Intent-filter action,category or data to achieve this is through the intent intent-filter** to achieve, this intent chapter will be explained in detail! You know, here's a guess!

3. There is another one that launches the APK directly through the package name:

Intent= getpackagemanager().  Getlaunchintentforpackage("apk first activated activity's fully qualified class name");  if(=null) startactivity(intent);
5, data transfer between the activity:

For the application, it is not enough to start another activity from one activity, and sometimes it is necessary to compare the data information exchange. The Android system provides a number of methods for data communication, and naturally provides a simple way to communicate between activity, see the following code:

Firstactivity transmitting data to otheractivity <data, "transmitted data" >

1  new Intent (This, otheractivity.  Class); 2         3        intent.putextra ("Data", "transmitted");  Data is a key//         Another method, loaded with / /     Bundle bundle = new Bundle ( ); //      bundle.putstring ("Data", "transmitted"); //      Intent.putextras (bundle); 8         9        startactivity (intent);

There are two methods of representation, the first method used in the scenario is to transmit a small amount of simple data, the latter method is to transfer more and more complex data used. But from the bottom up, the first method is the encapsulation of the latter, which still creates a bundle inside intent and puts the data (such as "passed data") into it.

Otheractivity get transferred data <data, "passed data" >

1         Intent Intent = getintent (); //         Get method 3         String data = Intent.getstringextra ("Data"); // The value of data is "passed", which is passed in by the last activity //       Another method /      Bundle bundle = Intent.getextras (); //       String data = bundle.getstring ("data");

The method obtained is usually to obtain the bundle intent carry, and then get the data stored in it through the Get method, and the previous method does not explicitly obtain the bundle code, because Intent.getstringextra (key) In the function is already the first to obtain good bundle and the corresponding key data parsed out, so the two methods are essentially the same, but if a large number of data proposed to use the latter method, because the data from the bundle to obtain more data than from the intent efficiency improved, compared to the mobile era, Efficiency is a very important thing to pay attention to.

Fristactivity starts Otheractivity and obtains the data returned by otheractivity at the end of the

If the business needs to start another activity to return data to the original activity, when the activity is started is called startactivity (intent), but should call Startactivityforresult (intent , Requestcode), Requestcode is an identifier for the activation activity, which is a positive integer value that can be used to represent the data returned by the activity with different identifiers when there are multiple startup activity and different processing. Processing the return data in fristactivity is handled in Onactivityresult (Requestcode, ResultCode, data), while the first parameter, Requestcode, is the identification code entered at startup. See Code

New Intent (This, otheractivity.  Class); 2 Startactivityforresult (Intent, 0); // set ID of 0

This is the code to start the activity, but we need to rewrite the Onactivityresult (Requestcode, ResultCode, data) in fristactivity for the returned data.

1 @Overrideprotectedvoid onactivityresult (intint  ResultCode, Intent data) {3 Super. Onactivityresult (Requestcode, ResultCode, data); 4 If(Requestcode = = 0) {// According to requestcode the value is really which activity returned bundle5 Bundle bundle = D Ata.getextras (); 6 String GetData = bundle.getstring ("name"); 7 }8 } copy code

Then, in the startup otheractivity, rewrite the method that returns the data

    New Intent ();    Intent.putextra ("name", "returned data");    Setresult (1, intent); // Set the intent    to return data Finish (); // end the current activity    

After the general Setresult call finish () to end the current activity, the data is returned to the fristactivity, and the data returned is the time that the Onactivityresult call was called before finish.

Here is the implementation-specific code:

Mainactivity

 PackageCn.com.qiang.buttondemo;ImportAndroid.os.Bundle;Importandroid.app.Activity;Importandroid.content.Intent;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button; Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main); Button button1=(Button) Findviewbyid (R.id.button1); Button1.setonclicklistener (NewMyliston ()); }        classMylistonImplementsonclicklistener{@Override Public voidOnClick (View v) {//TODO auto-generated Method StubIntent Intent =NewIntent (); Intent.setclass (mainactivity. This, Secondactivity.class); Intent.putextra ("Key", "send you a beautiful picture");        StartActivity (Intent); }    }   }

Secondactivity

 PackageCn.com.qiang.buttondemo;Importandroid.app.Activity;Importandroid.content.Intent;ImportAndroid.os.Bundle;ImportAndroid.widget.TextView; Public classSecondactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method Stub        Super. OnCreate (savedinstancestate);            Setcontentview (R.layout.activity_second); Intent Intent=getintent (); String s= Intent.getstringextra ("Key"); TextView TV=(TextView) Findviewbyid (r.id.tv);    Tv.settext (s); }}

Android Four Components--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.