Android Four components (Activity, Service, Broadcastreceiver, ContentProvider)

Source: Internet
Author: User
Tags sqlite database

Reproduced in: http://blog.csdn.net/byxdaz/article/details/9708491

http://blog.csdn.net/q876266464/article/details/19641251

The four basic components of Android are Activity,service services, content provider contents provider, broadcast receiver broadcast receiver.

First, understand the four basic components

Activity:

In an application, an activity is usually a separate screen that shows some controls that can also listen and handle the user's events to respond .

The activity communicates through intent. In the description structure of intent, there are two most important parts: the data corresponding to the action and the action.

Typical types of actions are: MAIN (activity Portal), VIEW, PICK, EDIT, and so on. The data corresponding to the action is represented in the form of a URI. For example, to see a person's contact, you need to create a intent with the action type view and a URI that represents the person.

A class that has a relationship with it is called Intentfilter. As opposed to intent is a valid request to do something, a intentfilter is used to describe which intent an activity (or intentreceiver) can manipulate. An activity if you want to display a person's contact information, you need to declare a intentfilter, this intentfilter to know how to handle the view action and the URI that represents a person. Intentfilter needs to be defined in Androidmanifest.xml. By parsing various intent, navigating from one screen to another is simple. When navigating forward, the activity invokes the StartActivity (Intent myintent) method. The system then looks in the Intentfilter defined in all installed applications to find the activity that best matches myintent's intent. After the new activity receives the MYINTENT notification, it starts to run. This mechanism provides two key benefits when the StartActivity method is invoked to trigger an action that parses the myintent:

A, activities is able to reuse a request from other components in the form of intent;

B, activities can be replaced at any time by a new activity with the same intentfilter.

The activity component that contains the filter in the Androidmanifest file is the default startup class that the system calls automatically when the program starts:

< Intent-filter >       <  android:name= "Android.intent.action.MAIN"/>       <   android:name= "Android.intent.category.LAUNCHER"/></ Intent-filter >

Broadcastreceive Broadcast receivers:

Your app can use it to filter external events only to receive and respond to an external event of interest, such as when the phone is being called, or when the data network is available. The broadcast receiver does not have a user interface. However, they can start an activity or serice to respond to the information they receive, or use Notificationmanager to notify the user. Notifications can be used in a variety of ways to attract users ' attention-flashing back lights, shaking, playing sounds, and more. In general, a persistent icon is placed on the status bar, and the user can open it and get the message.

Broadcast type:

    • General broadcast, sent via Context.sendbroadcast (Intent myintent)
    • Ordered broadcast, sent through Context.sendorderedbroadcast (intent, Receiverpermission), the 2nd parameter of the method determines the level of the broadcast, the level value is between 1000 to 1000, the greater the value, The higher the priority of the transmission, the level at which the broadcast receiver receives the broadcast (which can be set to 2147483647 by priority in the Intentfilter), the order received at the same level is random, and then to the low level of the broadcast, A high level or the same level of first-time broadcasts can be truncated by the Abortbroadcast () method so that other receivers cannot receive the broadcast, and other constructors
    • Asynchronous broadcasts, sent through Context.sendstickybroadcast (intentmyintent), and Sendstickyorderedbroadcast (intent, Resultreceiver, Scheduler, Initialcode,initialdata, Initialextras) method, the method has the characteristics of the ordered broadcast and the characteristics of asynchronous broadcasting; Send an asynchronous broadcast to: <uses-permission Android: Name= "Android.permission.BROADCAST_STICKY"/> permission, after receiving and processing intent, the broadcast still exists until you call Removestickybroadcast (intent) Take the initiative to remove it

Note: The intent parameter when sending a broadcast differs from the intent that contex.startactivity () initiates, which can be called by multiple broadcast receivers that subscribe to it, which can only be called by one (activity or service)

To listen to the broadcast intent steps:

1> writes a class that inherits Broadcastreceiver, overrides the OnReceive () method, and the broadcast sink is active only when it executes the method. When OnReceive () returns, it is inactive, note: In order to ensure the smooth user interaction process, some time-consuming operations to be placed in the thread, such as the class name Smsbroadcastreceiver

2> Register the broadcast receiver, register there are two methods for the dynamic registration of the program and the static registration in the Androidmanifest file (can be understood as registered in the system) as follows:

Static registration, registered broadcast, the following priority indicates that the receiving broadcast level "2147483647" is the highest precedence

<receiverAndroid:name=". Smsbroadcastreceiver ">    <Intent-filterandroid:priority= "2147483647">        <ActionAndroid:name= "Android.provider.Telephony.SMS_RECEIVED"/>    </Intent-filter></receiver>

Dynamic registration, typically registered Broadcastreceiver in Onresume () when activity is interactive:

Intentfilter intentfilter=newintentfilter ("Android.provider.Telephony.SMS_RECEIVED"// anti-registration Unregisterreceiver (receiver);

Attention:

1. The life cycle is only about 10 seconds, if within onreceive () do more than 10 seconds of things, will report the ANR (Application no Response) program unresponsive error message, if you need to complete a more time-consuming work, should be sent Intent to Service, which is done by the service. It is not possible to use a child thread here because the Broadcastreceiver life cycle is short, and the child thread may not have finished broadcastreceiver before it ends. Once the broadcastreceiver is over, the broadcastreceiver process can easily be killed when the system needs memory because it belongs to the empty process (the process without any active components). If its host process is killed, then the working child thread will be killed. So using sub-threading to solve is unreliable

2. The dynamic registration of the broadcast receiver also has a feature, that is, when the activity used to register is turned off, the broadcast will expire. Static registration does not need to worry about whether the broadcast receiver is turned off, as long as the device is turned on and the broadcast receiver is open. This means that even if the app itself doesn't start, the app's subscription broadcast will work on it when triggered.

System common broadcast intent, such as start-up, battery power changes, time changes and other broadcasts.

Service Services :

A service is a long life cycle, without a user-interface program that can be used to develop programs such as monitoring classes.

A good example is a media player that is playing songs from a playlist. In a media player application, there should be multiple activity, allowing the user to select songs and play songs. However, there is no activity associated with the music replay because the user will of course think that the music should still be playing when navigating to other screens. In this example, the Media Player activity uses context.startservice () to start a service so that it can keep the music playing in the background. At the same time, the system will keep the service running until the end of the service run. In addition, we can also connect to a service by using the Context.bindservice () method (if the service is not running it will start it). When connected to a service, we can also communicate with it by the interface provided by the service. Take the Media Player example, we can also pause, replay and other operations.

Service usage steps are as follows

1> inheriting the service class

Configure the service in the <application> node in the 2>androidmanifast.xml configuration manifest file

<servicename= ". SMSService "/>

Service does not run on its own and needs to be started by Contex.startservice () or Contex.bindservice ()

The service started by the StartService () method has no relationship with the caller, even if the caller shuts down and the service is still running to stop the service to call Context.stopservice (), at which point the system calls Ondestory (), when started with this method, The first time the service starts the system calls the service's OnCreate ()-->onstart (), and if the service has started again the call will only trigger the OnStart () method

Services that are started with bindservice () are bound to the caller as long as the caller shuts down the service, and when started using this method, the first time the service starts the system calls the service's OnCreate ()-->onbind (), and if the service has started again, the call will no longer trigger these 2 methods , when the caller exits, the system invokes the service's Onunbind ()-->ondestory (), and the system calls Onunbind ()-->ondestory () in order to actively unbind the binding contex.unbindservice ();

Content Provider Contents provider:

The Android platform provides content provider to make the specified data set for an application available to other applications. This data can be stored in a file system, in a SQLite database, or in any other reasonable way,

Other applications can obtain or deposit data from the content provider through the Contentresolver class (see contentprovideraccessapp example). (equivalent to outsourcing a shell in the application),

You need content providers only if you need to share data among multiple applications. For example, Address book data is used by multiple applications and must be stored in a content provider

Its benefits: Unified access to data.

The content providers that come with the Android system (top-level representations of database names, non-top-level are table names) are described in the Android.provider Java package in the SDK documentation. See: http://developer.android.com/reference/android/provider/package-summary.html

├ ———— Browser

├ ———— Calllog

├ ———— Contacts

├ ———— Groups

├ ———— People

├ ———— Phones

│└ ———— Photos

├ ———— Images

│└ ———— Thumbnails

├ ———— Mediastore

├ ———— Albums

├ ———— Artists

├ ———— Audio

├ ———— Genres

│└ ———— Playlists

├ ———— Settings

└ ———— Video

Calllog: Address and received phone information

Contact.People.Phones: Store Phone number

Setting.system: System settings and preferences

To share data externally using content provider

1> inherits the ContentProvider class and overrides the following methods as required:

Publicboolean onCreate ();//Handling Initialization Operations       /*** Insert data into content provider (override when other apps are allowed to insert data into your app) *@paramURI *@paraminitialvalues Data Inserted *@return        */        Publicuri insert (URI Uri, contentvaluesinitialvalues); /*** Delete data from content providers (overrides when other apps are allowed to delete data from your app) *@paramURI *@paramselection Conditional statement *@paramSelectionargs Parameters *@return        */publicint Delete (Uri Uri, String selection, String[]selectionargs); /*** Update the data that the content provider already exists (override if other apps update your app's data) *@paramURI *@paramvalues updated data *@paramselection Conditional statement *@paramSelectionargs Parameters *@return        */publicint Update (URI Uri, contentvalues values, String selection, string[] selectionargs); /*** Return data to callers (override when other apps are allowed to fetch data from your app) *@paramURI *@paramProjection Column name *@paramselection Conditional statement *@paramSelectionargs Parameters *@paramSortOrder Sort *@return        */        PublicCursor query (Uri URI, string[] projection,string selection, string[] selectionargs,string Sortord               ER); /*** Used to return the MIME type of the data represented by the current URI * If the operation's data is of the collection type (multiple data), then the returned type string should start with vnd.android.cursor.dir/* For example to get all pers The URI for the on record is content://com.bravestarr.provider.personprovider/person,* then the MIME type string returned should be "vnd.android.cursor.dir/ Person "* If the data for the operation is single data, then the returned type string should start with vnd.android.cursor.item/* For example to get the ID 10 of the person record the URI is Content://com.brave Starr.provider.personprovider/person/10,* then the MIME type string returned should be "Vnd.android.cursor.item/person" *@paramURI*/        PublicString GetType (URI uri)

Android Four components (Activity, Service, Broadcastreceiver, ContentProvider)

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.