Android (6) activity, request code and result code, intent, broadcast, and service

Source: Internet
Author: User

1. Create a NewActivity

During desktop development, we can open another new window through a control event in a window. During web application development, we can also open a new page through a connection. By adding a new window to improve or enhance the software functions, how should we open a new activity in Android Application Development?

1.Add a new activity (create an android project: mainactivity)

1) create a newactivity class that inherits from the activity class

PackageCom. Changcheng. activity;

ImportAndroid. App. activity;

ImportAndroid. OS. Bundle;

ImportAndroid. View. view;

ImportAndroid. widget. Button;

Public ClassNewactivityExtendsActivity {

@ Override

Protected VoidOncreate (bundle savedinstancestate ){

Super. Oncreate (savedinstancestate );

Setcontentview (R. layout.New_activity);

// The get button does not have a button to add events

Button button = (button)This. Findviewbyid (R. Id.Newa_bt_close);

Button. setonclicklistener (NewView. onclicklistener (){

@ Override

Public VoidOnclick (view v ){

Newactivity.This. Finish ();

}

});

}

}

2) Add the following content to the androidmanifest. xml file:

& Quot; 1.0 & quot; encoding ="UTF-8"?>

Http://schemas.android.com/apk/res/android"

Package ="Com. Changcheng. Activity"

Android: versioncode ="1"

Android: versionname ="1.0">

"@ Drawable/icon" Android: Label ="@ String/app_name">

". Mainactivity"

Android: Label ="@ String/app_name">

 

"Android. Intent. Action. Main"/>

"Android. Intent. Category. launcher"/>

 

 

". Newactivity"

Android: Label ="@ String/new_activity"/>

 

"7"/>

 

3). newactivity. xml

& Quot; 1.0 & quot; encoding ="UTF-8"?>

Http://schemas.android.com/apk/res/android"

Android: Orientation ="Vertical"Android: layout_width ="Fill_parent"Android: layout_height ="Fill_parent">

"Fill_parent"

Android: layout_height ="Wrap_content"Android: text ="@ String/newa_activity"/>

 

"Fill_parent"

Android: layout_height ="Wrap_content"Android: text ="@ String/newa_bt_close"

Android: Id ="@ + ID/newa_bt_close"/>

 

4). Strings. xml

& Quot; 1.0 & quot; encoding ="UTF-8"?>

 

"Hello"> Hello world, mainactivity!

"App_name"> Create a new activity

"Bt_open_new_activity"> open a new activity

"New_activity"> New Activity

"Newa_activity"> New Activity

"Newa_bt_close"> close

 

5). mainactivity. Java

PackageCom. Changcheng. activity;

ImportAndroid. App. activity;

ImportAndroid. content. intent;

ImportAndroid. OS. Bundle;

ImportAndroid. View. view;

ImportAndroid. widget. Button;

Public ClassMainactivityExtendsActivity {

/** Called when the activity is first created .*/

@ Override

Public VoidOncreate (bundle savedinstancestate ){

Super. Oncreate (savedinstancestate );

Setcontentview (R. layout.Main);

// Obtain the button and add the clicked event for the button

Button button = (button)This. Findviewbyid (R. Id.Bte_open_new_activity);

Button. setonclicklistener (NewView. onclicklistener (){

@ Override

Public VoidOnclick (view v ){

// Create an explicit intent

Intent intent =NewIntent (mainactivity.This, Newactivity.Class);

// Open a new activity

Startactivity (intent );

}

});

}

}

II,ActivityBetween Parameters

In a desktop program, we can transmit data between windows by constructing parameters or global variables. In a web application, we can transmit data between pages through the domain (Request/response/session. So how can we pass parameters between Android activities?

You can use the intent. putextra method to add parameters for the intent. After opening a new activity, you can use this. getintent (). getstringextra () and other methods to obtain parameters.

Iii. Request Code and result code

In the above program, we open a new activity through startactivity (intent). In order to reduce coupling between components, Android uses intent (intent will be introduced below ). Therefore, the new activity opened in The onclick event is not in the same thread as the main activity. However, when a new activity is disabled, the onactivityresult event of the main activity is triggered.

1. Request Code

In a business, the same activity may be opened in the event where two buttons are clicked. But in the onactivityresult event, how can we determine which button opened the new activity? The request code solves this problem. When opening a new activity, we should use startactivityforresult (intent, 1 );. The second parameter is the request code.

Onactivityresult event:

@ Override

Protected VoidOnactivityresult (IntRequestcode,IntResultcode, intent data ){

//TodoAuto-generated method stub

Super. Onactivityresult (requestcode, resultcode, data );

}

In the onactivityresult event, you can determine the position where the disabled activity is opened by determining the requestcode.

2.Result code

In a business, multiple different activities may be opened. How do we know which activity is closed in the onactivityresult event when the activity is closed? The result code is used to solve this problem. When opening a new activity, we should use setresult (2, intent); or call activityobj. setresult (2) Before closing the activity );. The first parameter is the result code.

In the onactivityresult event, you can determine which activity is disabled by judging the resultcode.

III,IntentIntention

The basic design concept of Android is to encourage the reduction of coupling between components. Therefore, Android provides intent (intent) and intent provides a general message system, it allows you to pass intent between your application and other applications to execute actions and generate events. Using intent, You can activate three core components of the Android app: Activity, service, and broadcast receiver.

Intent can be divided into explicit intent and implicit intent:

1 ). explicit intent: Call intent. setcomponent () or intent. the setclass () method specifies the component name or the intent of the class object as the explicit intent, and the explicit intent specifies the component to which the intent should be passed. For example, we open a new activity program above.

2). Implicit intent: The intent. setcomponent () or intent. setclass () method is not called to specify the intent of the component name or Class Object as the implicit intent. The Android system will find the most suitable component to process the intent based on the action, category, and data (Uri and data type) set in the implicit intent. Open a new activity with an implicit intent:

Androidmanifest. xml:

". Newactivity" Android: Label ="@ String/new_activity">

 

"Com. Changcheng. activity. newactivity"/>

"Android. Intent. Category. Default"/>

 

 

Mainactivity:

@ Override

Public VoidOnclick (view v ){

// Create an explicit intent

Intent intent =NewIntent ("com. Changcheng. activity. newactivity ");

// Intent = new intent (mainactivity. This, newactivity. Class );

// Open a new activity

Startactivity (intent); // when sending intent, there is a category in the intent: Android. Intent. Category. Default

}

You can add multiple actions and category in the intent filter, and add data. The specific usage will not be summarized here. You can view the relevant information or help documentation.

3) application scenarios of explicit and implicit intentions:

Explicit intent is recommended within the project.

Only implicit intent can be used between an application and an application.

IV,ActivityLifecycle

Activity has three states:

When it is at the front-end of the screen (at the top of the current job stack), it is active or running. It is the activity that responds to user operations.

When it loses focus but is still visible to users, it is paused. That is, there is another activity on it. This activity may be transparent or not fully covered in full screen, so the paused activity is still visible to the user. The paused activity is still alive (it retains all the status and member information and maintains the connection with the window manager), but the activity can still be killed when the system is in very low memory.

If it is completely overwritten by another activity, it is in the stopped state. It retains all status and member information. However, it is invisible to users, so its window will be hidden. If memory is needed elsewhere, the system will often kill this activity.

When an activity changes from one state to another, the following protection methods are called to notify the activity of this change:

Void oncreate (bundle savedinstancestate)

Void onstart ()

Void onrestart ()

Void onresume ()

Void onpause ()

Void onstop ()

Void ondestroy ()


These seven events define the full lifecycle of the activity. Implementing these event methods helps us monitor three nested lifecycles:

1) the full life cycle of the activity starts from the first oncreate () call until ondestroy () is called. Activity sets all "Global" states in oncreate () to complete initialization, and releases all system resources in ondestroy. For example, if a thread of the activity is running in the background to download data from the network, it will create a thread in oncreate () and destroy the thread in ondestroy.

2) The visible life cycle of the activity starts from onstart () until the end of the corresponding onstop () call. During this period, the user can see the activity on the screen, although it may not be at the front-end or does not interact with the user. Between the two methods, we can reserve the resources required to display the activity to users. For example, if you no longer see what we display, you can register a broadcastreceiver in onstart () to monitor the changes that will affect the UI, but ignore it in onstop. The onstart () and onstop () methods can be called multiple times as the application is visible to the user.

3) the foreground life cycle of the activity starts from onresume () and ends with the onpause () call. During this period, the activity is located at the top of the foreground and interacts with the user. The activity changes the status frequently between pause and resume. For example, the onpause () method is called when the device is in sleep state or a new activity is started. The onresume () method is called when the activity gets the result or receives a new intent. For an example of the foreground life cycle, see the remarks column below the PPT.

5. Broadcast Receiver

The broadcast receiver (broadcastreceiver) is used to asynchronously receive the broadcast intent. The broadcast intent is sent by calling context. sendbroadcast (), context. sendorderedbroadcast (), or context. sendstickybroadcast. Generally, a broadcast intent can be received by multiple broadcast recipients subscribed to this intent. The broadcast receiver is similar to the topic Message Receiver in JMS. The method to implement a broadcast receiver is as follows:

1) inherit from broadcastreceiver and override the onreceive () method.

2). subscribe to the broadcast intent you are interested in. There are two subscription methods:

· Subscribe using code:

Intentfilter filter = new intentfilter ("android. provider. telephony. sms_received ");

Incomingsmsreceiver extends ER = new incomingsmsreceiver ();

Registerreceiver (receiver, filter );

· Subscribe to the node in the androidmanifest. xml file:

 

 

 

 

 

Generally, the life cycle of a broadcastreceiver object cannot exceed 5 seconds, so some time-consuming operations cannot be performed in broadcastreceiver. If you need to complete a time-consuming task, you can send an intent message to an activity or service, which is completed by activity or service.

Vi. Services

Services in Android and windows are similar. services generally do not have user operation interfaces. They run in a system and are not easily noticed by users. You can use them to develop programs such as monitoring. Service development is relatively simple, as follows:

1. inherit the service class

Public class smsservice extends Service {}

2. Configure the service in the node in the androidmanifest. xml file:

 

The service cannot run on its own. You must call the context. startservice () or context. bindservice () method to start the service. Both methods can start the service, but their usage is different. The startservice () method is used to enable the service. There is no relation between the caller and the service. Even if the caller exits, the Service continues to run. The bindservice () method is used to enable the Service. When the caller and the service are bound together, the service is terminated once the caller exits.

If you plan to use the context. startservice () method to start the service, when the service is not created, the system will first call the oncreate () method of the service and then call the onstart () method. If the service has been created before the startservice () method is called, multiple call of the startservice () method will not lead to multiple creation of the service, but will lead to multiple calls of the onstart () method. A service started using the startservice () method can only end the service by calling the context. stopservice () method. The ondestroy () method is called when the service ends.

If you plan to use the context. bindservice () method to start the service, when the service is not created, the system will first call the oncreate () method of the service and then call the onbind () method. At this time, the caller and the service are bound together. After the caller exits, the system will first call the onunbind () method of the service and then call the ondestroy () method. If the service has been bound before the bindservice () method is called, multiple calls to the bindservice () method will not result in multiple service creation and binding (that is, oncreate () and onbind () method is not called multiple times ). If the caller wants to unbind from the service being bound, he can call the unbindservice () method. Calling this method also causes the system to call the onunbind () --> ondestroy () method of the service.

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.