Briefly explain activity, intent, intent filter, service, broadcast, broadcasereceiver

Source: Internet
Author: User
Tags home screen

 

Activity
In Android, activity is the foundation of all programs, and the processes of all programs run in the activity. activity has its own life cycle (the life cycle is controlled by the system, and the program cannot be changed, however, you can use onsaveinstancestate to save its status ).
The key to an activity is its life cycle (for example, the classic Life Cycle Graph =. =), followed by onsaveinstancestate onrestoreinstancestate, and inter-activity redirection and data transmission (intent ).

Common functions in activity include setcontentview () findviewbyid () finish () startactivity (). The following are the functions involved in the lifecycle:
Void oncreate (bundle savedinstancestate)
Void onstart ()
Void onrestart ()
Void onresume ()
Void onpause ()
Void onstop ()
Void ondestroy ()
Note that you must add the corresponding <activity> in the manifest file and set its attributes and intent-filter to use the activity.

 

 

 

Intent
Android provides an intent mechanism to assist in interaction and communication between applications. Intent describes the actions, actions involving data, and additional data of an application, android finds the corresponding component based on the description of the intent, passes the intent to the called component, and calls the component. Intent can be used not only between applications, but also between activities/services within the application. Therefore, intent acts as a media intermediary here, providing information about component calls to each other to decouple callers from callers. The function of intent is shown in the SDK as follows:

· Start an activity through context. startactivity () javastivity. startactivityforresult;

· Start a service through context. startservice () or use context. bindservice () to interact with background services;

· Send the broadcast method (such as context. sendbroadcast (), context. sendorderedbroadcast (), and context. sendstickybroadcast () to broadcast receivers.

Intent attribute settings include the following: (The following are definitions in XML, and can also be obtained and set using the intent class method)
(1) action, that is, the action to be executed
The SDK defines some standard actions, including

Onstant

Target component

Action

Action_call

Activity

Initiate a phone call.

Action_edit

Activity

Display data for the user to edit.

Action_main

Activity

Start up as the initial activity of a task, with no data input and no returned output.

Action_sync

Activity

Synchronize data on a server with data on the mobile device.

Action_battery_low

Broadcast receiver er

A warning that the battery is low.

Action_headset_plug

Broadcast receiver er

A headset has been plugged into the device, or unplugged from it.

Action_screen_on

Broadcast receiver er

The screen has been turned on.

Action_timezone_changed

Broadcast receiver er

The setting for the time zone has changed.

Of course, you can also customize the action (when using a custom action, you need to add the package name as the prefix, such as "com. example. project. show_color), and you can define the corresponding activity to process our custom actions.
(2) data, that is, the data to be operated by the execution action
Android uses a URI pointing to data. For example, in a contact application, a URI pointing to a contact may be: Content: // contacts/1. For different actions, the URI data type is different (you can set the type attribute to specify a specific type of data). For example, action_edit specifies that data is the file URI and calls Tel: URI, the access network is http: URI, while the data provided by the content provider is content: Uris.
(3) type (data type), explicitly specifying the intent data type (MIME ). Generally, the intent data type can be determined based on the data itself. However, by setting this attribute, You can forcibly use the explicitly specified type instead of derivation.
(4) category (category): additional information about the executed action. For example, launcher_category indicates that the receiver of intent should appear as a top-level application in launcher, while alternative_category indicates that the current intent is one of a series of optional actions that can be executed on the same piece of data. There are other

Constant

Meaning

Category_browsable

The target activity can be safely invoked by the browser to display data referenced by a link-for example, an image or an e-mail message.

Category_gadget

The activity can be embedded inside of another activity that hosts gadgets.

Category_home

The activity displays the home screen, the first screen the user sees when the device is turned on or when the home key is pressed.

Category_launcher

The activity can be the initial activity of a task and is listed in the top-level application launcher.

Category_preference

The target activity is a preference panel.

(5) component: Specifies the Class Name of the intent's target component. Generally, Android searches for other attributes in intent, such as action, data/type, and category, and finds a matched target component. However, if this attribute of component is specified, the component specified by component will be used directly without executing the above search process. After this attribute is specified, all other intent attributes are optional.
(6) extras (additional information) is a collection of all other additional information. You can use extras to provide extended information for components. For example, if you want to perform the "send email" action, you can save the email title and body in extras, send to the email sending component.
One of the keys to understanding intent is to understand the two basic usage of intent: an explicit intent, that is, specifying the receiver when constructing the intent object; the other is an implicit intent, that is, when the intent sender constructs an intent object, it does not know or care about who the receiver is. This helps reduce the coupling between the sender and the receiver.
Android does not need to parse explicit intent because the target component is clear. Android needs to parse implicit intent, map intent to the activity, intentreceiver, or service that can process the intent.
The intent parsing mechanism mainly finds the matching intent by finding all intentfilters registered in androidmanifest. XML and the intent defined in them. In this parsing process, Android uses the intent action, type, and category attributes to determine the attributes. The judgment method is as follows:

· If intent specifies an action, the action must be included in the action list of the intentfilter of the target component; otherwise, the action cannot be matched;

· If the intent does not provide the type, the system will obtain the data type from the data. Like action, the Data Type list of the target component must contain the intent data type. Otherwise, the data type does not match.

· If the data in the intent is not a content: Type Uri and the intent does not explicitly specify its type, it will match according to the scheme (such as http: or mailto :) of the data in the intent. Similarly, the scheme of intent must appear in the scheme list of the target component.

· If intent specifies one or more category categories, all these categories must appear in the Set category list. For example, intent contains two categories: launcher_category and alternative_category. The parsed target component must contain at least these two categories.

 

 

 

Intent-filter Definition
Examples of setting attributes:
<Action Android: Name = "com. example. Project. show_current"/>
<Category Android: Name = "android. Intent. Category. Default"/>
<Data Android: mimetype = "Video/MPEG" Android: Scheme = "HTTP".../>
<Data Android: mimetype = "image/*"/>
<Data Android: Scheme = "HTTP" Android: TYPE = "Video/*"/>
Complete instance
<Activity Android: Name = "noteslist" Android: Label = "@ string/title_notes_list">
<Intent-filter>
<Action Android: Name = "android. Intent. Action. Main"/>
<Category Android: Name = "android. Intent. Category. launcher"/>
</Intent-filter>
<Intent-filter>
<Action Android: Name = "android. Intent. Action. View"/>
<Action Android: Name = "android. Intent. Action. Edit"/>
<Action Android: Name = "android. Intent. Action. Pick"/>
<Category Android: Name = "android. Intent. Category. Default"/>
<Data Android: mimetype = "Vnd. Android. cursor. DIR/vnd. Google. Note"/>
</Intent-filter>
<Intent-filter>
<Action Android: Name = "android. Intent. Action. get_content"/>
<Category Android: Name = "android. Intent. Category. Default"/>
<Data Android: mimetype = "Vnd. Android. cursor. Item/vnd. Google. Note"/>
</Intent-filter>
</Activity>
Intent usage instance
1. No parameter for activity jump
Intent it = new intent (activity. Main. This, activity2.class );
Startactivity (it );
2. pass data to the next activity (use bundle and intent. putextras)
Intent it = new intent (activity. Main. This, activity2.class );
Bundle bundle = new bundle ();
Bundle. putstring ("name", "this is from mainactivity! ");
It. putextras (bundle); // it. putextra ("test", "shuju ");
Startactivity (it); // startactivityforresult (it, request_code );
You can use the following methods to obtain data:
Bundle bundle = getintent (). getextras (); string name = bundle. getstring ("name ");
3. Return the result to the previous activity (use setresult to start the activity for startactivityforresult (it, request_code)
Intent intent = getintent ();
Bundle bundle2 = new bundle ();
Bundle2.putstring ("name", "this is from showmsg! ");
Intent. putextras (bundle2 );
Setresult (result_ OK, intent );
4. Call back the result processing function (onactivityresult) of the previous activity)
@ Override protected void onactivityresult (INT requestcode, int resultcode, intent data ){
// Todo auto-generated method stub
Super. onactivityresult (requestcode, resultcode, data );
If (requestcode = request_code ){
If (resultcode = result_canceled)
Settitle ("cancle ");
Else if (resultcode = result_ OK ){
String temp = NULL;
Bundle bundle = data. getextras ();
If (bundle! = NULL) temp = bundle. getstring ("name ");
Settitle (temp );
}
}
}
The following are some other intent usage examples (from javaeye)
Display webpage
1. Uri uri = URI. parse ("http://google.com ");
2. Intent it = new intent (intent. action_view, Uri );
3. startactivity (it );
Show Map
1. Uri uri = URI. parse ("Geo: 38.899533,-77.036476 ");
2. Intent it = new intent (intent. action_view, Uri );
3. startactivity (it );
4. // other geo uri examples
5. // GEO: latitude, longpolling
6. // GEO: latitude, longpolling? Z = zoom
7. // GEO: 0, 0? Q = My + street + address
8. // GEO: 0, 0? Q = business + near + city
9. // Google. Streetview: cbll = Lat, LNG & white = 1, yaw, pitch, zoom & MZ = mapzoom
Route Planning
1. Uri uri = URI. parse ("http://maps.google.com/maps? F = D & saddr = startlat % 20 startlng & daddr = endlat % 20 endlng & HL = EN ");
2. Intent it = new intent (intent. action_view, Uri );
3. startactivity (it );
4. // Where startlat, startlng, endlat, endlng are a long with 6 decimals like: 50.123456
Call
1. // call the dialing program
2. Uri uri = URI. parse ("Tel: 0800000123 ");
3. Intent it = new intent (intent. action_dial, Uri );
4. startactivity (it );
1. // directly call
2. Uri uri = URI. parse ("Tel: 0800000123 ");
3. Intent it = new intent (intent. action_call, Uri );
4. startactivity (it );
5. // use this file, which must be added to androidmanifest. xml.
6. // <uses-Permission id = "android. Permission. call_phone"/>
Send SMS/MMS
1. // call the SMS Program
2. Intent it = new intent (intent. action_view, Uri );
3. It. putextra ("sms_body", "the SMS text ");
4. It. settype ("Vnd. Android-DIR/MMS-SMS ");
5. startactivity (it );
1. // send messages
2. Uri uri = URI. parse ("smsto: // 0800000123 ");
3. Intent it = new intent (intent. action_sendto, Uri );
4. It. putextra ("sms_body", "the SMS text ");
5. startactivity (it );
1. // send MMS
2. Uri uri = URI. parse ("content: // media/external/images/Media/23 ");
3. Intent it = new intent (intent. action_send );
4. It. putextra ("sms_body", "some text ");
5. It. putextra (intent. extra_stream, Uri );
6. It. settype ("image/PNG ");
7. startactivity (it );
Send email
1. Uri uri = URI. parse ("mailto: xxx@abc.com ");
2. Intent it = new intent (intent. action_sendto, Uri );
3. startactivity (it );
1. Intent it = new intent (intent. action_send );
2. it. putextra (intent. extra_email, "me@abc.com ");
3. It. putextra (intent. extra_text, "the email body text ");
4. It. settype ("text/plain ");
5. startactivity (intent. createchooser (IT, "Choose email client "));
1. Intent it = new intent (intent. action_send );
2. String [] TOS = {"me@abc.com "};
3. String [] CCS = {"you@abc.com "};
4. It. putextra (intent. extra_email, TOS );
5. It. putextra (intent. extra_cc, CCS );
6. It. putextra (intent. extra_text, "the email body text ");
7. It. putextra (intent. extra_subject, "the email subject text ");
8. It. settype ("message/rfc822 ");
9. startactivity (intent. createchooser (IT, "Choose email client "));
1. // transfer the attachment
2. Intent it = new intent (intent. action_send );
3. It. putextra (intent. extra_subject, "the email subject text ");
4. It. putextra (intent. extra_stream, "file: // sdcard/mysong.mp3 ");
5. sendintent. settype ("audio/MP3 ");
6. startactivity (intent. createchooser (IT, "Choose email client "));
Play multimedia
Uri uri = URI. parse ("file: // sdcard/song.mp3 ");
Intent it = new intent (intent. action_view, Uri );
It. settype ("audio/MP3 ");
Startactivity (it );
Uri uri = URI. withappendedpath (mediastore. Audio. Media. internal_content_uri, "1 ");
Intent it = new intent (intent. action_view, Uri );
Startactivity (it );
Market Problems
1. // search for an application
2. Uri uri = URI. parse ("Market: // search? Q = pname: pkg_name ");
3. Intent it = new intent (intent. action_view, Uri );
4. startactivity (it );
5. // Where pkg_name is the full package path for an application
1. // display information about an application
2. Uri uri = URI. parse ("Market: // details? Id = app_id ");
3. Intent it = new intent (intent. action_view, Uri );
4. startactivity (it );
5. // Where app_id is the Application ID, find the ID
6. // by clicking on your application on market Home
7. // page, and notice the ID from the address bar
Uninstall Application
1. Uri uri = URI. fromparts ("package", strpackagename, null );
2. Intent it = new intent (intent. action_delete, Uri );
3. startactivity (it );

 

 

Service

 

 

 

Service is a code without a long life cycle interface. A good example is that the media player plays songs from the list. In a media player program, there may be one or more activities for you to select a song and play it. However, the activity cannot be used for music playback, because the user wants the music to continue playing when the user wishes to navigate to other interfaces. In this case, the Media Player activity starts a service using context. startservice () to maintain the playing of music in the background. The system will keep this music playback service running until it ends. Note that you must use the context. bindservice () method to connect to the Service (if it is not running, start it first ). After you connect to a service, you can communicate with it through an interface exposed by the Service. For music services, it allows you to pause, rewind, and so on.

 

 

 

 

 

Broadcast and broadcasereceiver

 

 

Overview of Android broadcastreceiver
Use activity, service, broadcast, broadcastreceiver in Android
Activity-used to present functions
Service-equivalent to the activity running in the background
Broadcast-used to send broadcasts
Broadcastreceiver-used to receive broadcasts
Intent-used to connect the above components and transmit messages during the process

Broadcastreceiver
In Android, broadcast is a widely used mechanism for transmitting information between applications. Broadcastreceiver is a type of component that filters and accepts and responds to broadcast. The following describes in detail how to send broadcast and use broadcastreceiver

Filter receiving process:
First, load the information to be sent and the information to be filtered (such as action and category) into an intent object, and then call context. the sendbroadcast (), sendorderbroadcast (), or sendstickybroadcast () Methods send intent objects in broadcast mode.
After an intent is sent, all registered broadcastreceiver checks whether the intentfilter at registration matches the sent intent. If yes, the broadcastreceiver onreceive () method is called. So when we define a broadcastreceiver, we need to implement the onreceive () method.

You can register broadcastreceiver in either of the following ways:
One way is to use the <receiver ER> tag to register the lifecycle in androidmanifest. xml statically, and use the <intent-filter> tag to set the filter in the tag.

Another way is to dynamically define and set an intentfilter object in the code, and then call context where you need to register the object. the registerreceiver () method. If it is canceled, the context is called. unregisterreceiver () method.

Whether registered in XML or in code, you do not have to log out when the program exits. Otherwise, the program may have multiple broadcastreceiver instances at the next startup.

In addition, if the sendbroadcast () method is used to specify the receiving permission, only the androidmanifest. in XML, the <uses-Permission> label declares the broascastreceiver with this permission to receive the broadcast sent.

Similarly, if the broadcast permission is specified when you register broadcastreceiver, only androidmanifest in the package is allowed. the <uses-Permission> label is used in XML to declare that the broadcast sent by the context object with this permission can be received by the broadcastreceiver.

Dynamic Registration:
Intentfilter = new intentfilter ();
Intentfilter. addaction (string); -- specify the action for broadcastreceiver to receive the broadcast registerreceiver (broadcastreceiver, intentfilter) of the same action );
GENERAL: Register in onstart and cancel unregisterreceiver in onstop

Send broadcast message: extends Service
Specify the broadcast target action: intent = new intent (action-string)
-- The operator with the specified action will receive the Broadcast
You need to pass the parameter (optional) putextra ();
Send: sendbroadcast (intent );

 

Reference:

Http://ycl248.blog.163.com/blog/static/3634280620106239617577/

Http://litonggang.javaeye.com/blog/519574

Http://lhc966.javaeye.com/blog/803647

 

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.