Android Notes (ii) Android core---Activity

Source: Internet
Author: User

What is activity

Activity is the most basic of Android application core components, is the user and Program interaction window, an activity usually corresponds to a separate view, an app is composed of one or more activity, activity is used to display information to the user, And can jump between each other, the jump between the activity has a return value.

Each activity is defined as a separate class, He inherits Android.app.Activity from Android, and in the Activity class uses the Setcontentview method to display the user interface composed of view controls and respond to the time the user departs from those view controls.

Four states of activity

1) Activation status, when activity runs on screen foreground

2) Pause state, the activity loses focus, but the user can still see (for example, this activity covers a transparent or non-full-screen activity)

3) Stop state, when activity is completely covered by other activity

4) Destroy the state, at which time the activity will be cleared out of memory by the system

Activity's callback function

The Android system calls the corresponding callback function to execute the code according to the different stages of the life cycle, from booting to destroying an activity with an orderly set of callback functions.

OnCreate () is created, the activity is called when it is first created, and some static settings are generally made in this method.

OnStart () Run, activity is called when the user is about to be visible

Onresume () Gets the focus, which is called when the activity is about to interact with the user

OnPause () loses focus when the system wants to start an additional activity call (called before other activity displays)

OnStop () pauses when another activity resumes and obscures the current activity, causing it to be called when it is not visible to the user.

OnDestroy () Destroy, the last method called before the activity is destroyed

Onrestart () restart

These seven methods run through the life cycle of the activity.

A picture to show

Activation and destruction of activity

Most apps contain multiple activities, whether the activity is a primary activity or a new one in response to user behavior, and the system invokes the OnCreate () method in the new activity instance, usually in the case of OnCreate () Methods to declare some UI elements or to define some of the basic operations such as member variables, but the OnCreate () method to do less effort to avoid the program start too long to see the interface.

Once the OnCreate () operation is completed, the OnStart () method and the Onresume () method of the activity are executed immediately, eventually allowing the activity to remain in the resumed state until some factors change to adapt the state. For example, switch to another activity or quit a program.

Once we exit the software, the system executes the activity's OnDestroy () method to completely remove the activity from the system, and we usually call OnDestroy () after executing the onPause () and OnStop ().

Suspension and recovery of activity

In the process of using the app, the activity will often be blocked by other components, such as the prompt for low battery, etc., activity is visible but not operational, this time the activity calls the OnPause () method to go into the pause state, This method stops the current activity and saves the information that may need to be persisted for a long time, and if the user returns to the activity from the paused state, the system recovers that data and executes the Onresume () method.

Stop and restart of activity

When we switch from app-a to App-b, App-a calls the OnStop () method, and in the OnStop () method We generally release some resources that we no longer need.

When we return from the stop state to the foreground, the Onrestart () method is called, and the system calls the OnStart () method,

Life cycle of activity

The life cycle of activity can be divided into full life cycle, visible life cycle and foreground life cycle according to different criteria.

The entire process from the activity's initial invocation of the OnCreate () method to the final call to the OnDestroy () method is called the full life cycle , setting the global state in the OnCreate () method and freeing all resources in the OnDestroy () method.

The process of calling the OnStart () method from activity to calling the corresponding OnStop () method is called the visible life cycle , in which the activity is visible to the user (but not necessarily actionable)

The entire process from activity invocation onresume () to calling OnPause () is called the foreground life cycle, during which the activity is in front of all other activity and can be interacted with by the user.

Demonstrate

We create an Android project, and then rewrite those methods.

Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem; Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); System.out.println ("Perform oncreate ..."); } @Overrideprotected voidOnStart () {//TODO auto-generated Method Stub        Super. OnStart (); System.out.println ("Perform onstart ..."); } @Overrideprotected voidOnresume () {//TODO auto-generated Method Stub        Super. Onresume (); System.out.println ("Perform onresume ..."); } @Overrideprotected voidOnPause () {//TODO auto-generated Method Stub        Super. OnPause (); System.out.println ("Perform onpause ..."); } @Overrideprotected voidOnStop () {//TODO auto-generated Method Stub        Super. OnStop (); System.out.println ("Perform onstop ..."); } @Overrideprotected voidOnDestroy () {//TODO auto-generated Method Stub        Super. OnDestroy (); System.out.println ("Perform OnDestroy ..."); } @Overrideprotected voidOnrestart () {//TODO auto-generated Method Stub        Super. Onrestart (); System.out.println ("Perform Onrestart ..."); }}

Running in the emulator, viewing the log

Then we press home to return to the desktop

Press the menu key to select back to just the interface

Press the back key to exit activity

How to create an activity

Create a new activity step as follows

1) Create a new class in src to inherit the activity and rewrite its oncreate () method

Myactivity.java


Importandroid.app.Activity;ImportAndroid.os.Bundle; Public classMyActivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method Stub Super. OnCreate (savedinstancestate); Setcontentview (r.layout.my_activity_layout);//display a layout file using the Setcontentview method }}

2) Create a layout file in the Res---layout to display the interface content

My_activity_layout.xml


<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical" > <TextViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "This is a TextView" /></LinearLayout>

3) Register this activity in the Androidmanifest.xml

Androidmanifest.xml


<Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.example.activitytest"Android:versioncode= "1"Android:versionname= "1.0" > <USES-SDKandroid:minsdkversion= "+"android:targetsdkversion= "+" /> <ApplicationAndroid:allowbackup= "true"Android:icon= "@drawable/ic_launcher"Android:label= "@string/app_name"Android:theme= "@style/apptheme" > <!--Register an activity - <ActivityAndroid:name= "Com.example.activitytest.MyActivity" > <!--if it is the main activity, you need to add a filter like below to tell the system this is the entrance - <Intent-filter> <ActionAndroid:name= "Android.intent.action.MAIN" /> <categoryAndroid:name= "Android.intent.category.LAUNCHER" /> </Intent-filter> </Activity> </Application></Manifest>

In this way, an activity is created successfully.

How to close an activity

You can destroy the current activity by pressing the return key, but if we want to destroy the activity in code, you can do so using the finish () method provided by the activity class.

Modify the code above

Myactivity.javaImportandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button; Public classMyActivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method Stub        Super. OnCreate (savedinstancestate); Setcontentview (r.layout.my_activity_layout);//display a layout file using the Setcontentview methodbutton Button= (Button) Findviewbyid (r.id.finishactivity);//Find this buttonButton.setonclicklistener (NewOnclicklistener () {//Add a Click event to this button@Override Public voidOnClick (View v) {finish ();//when the button is clicked, destroy the activity            }        }); } @Overrideprotected voidOnDestroy () {//TODO auto-generated Method Stub        Super. OnDestroy (); System.out.println ("The OnDestroy method is called"); }}

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical" >    <TextViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "This is a TextView" />    <ButtonAndroid:id= "@+id/finishactivity"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Close this activity" /></LinearLayout>

When you run the program, click the button and the activity will be closed.

What is the difference between finish () and OnDestroy ()

From the results of the above code operation, the console output "OnDestroy method is called", it is shown that the execution of the OnDestroy () method at Finish ().

In fact, the difference is that OnDestroy () is the life cycle approach, which is called by the Android system at the end of your activity, and you can't call OnDestroy () to end your activity, the general practice is to call finish ()

Android Notes (ii) Android core---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.