Android: four basic components

Source: Internet
Author: User

The four basic components of Android are Activity, Service, Content Provider, and BroadcastReceiver.

I. Understand four basic components

Activity:

In an application, an Activity is usually a single screen, which can display some controls or listen to and process user events to respond.

An Activity is usually displayed as a visual user interface. For example, an activity may be displayed as a list of menu items that a user can select or as the title of some images and images. A message service application may contain an activity that displays the contact list, an activity that writes information, and other activities that view information and modify application settings. Although these activities work together to form an application, each activity is relatively independent. Every activity is a subclass of Activity (android. app. Activity.

An application may only contain one activity, or there are multiple activities, just as the messageservice program mentioned above. An application contains several activities and the functions of each activity depend entirely on the application and its design. Generally, each application contains an activity that is first presented to the user after the application starts. Enable a new activity in the activity currently presented to the user, which can be converted from one activity to another.

Each activity has a window for drawing the user interface. Normally, such a window will fill the entire screen. Of course, this window can be smaller than the screen and floating above other windows. Activity can also use some additional windows, such as a pop-up dialog box that requires a user to respond, or a window that shows some important information to the user when the user selects an entry on the screen.

The visible content area of the activity window is a number of views with hierarchies (similar to the tree in the data structure), and the View is represented by a subclass of the Class View. A rectangular area in each view control window. The parent view contains child views and manages the layout of child views. The view on the leaf node directly controls and responds to user actions. Therefore, a view is the interface between the activity and the user. For example, when a user clicks an image view, it may start an action. Android has many views that developers can use directly, including buttons, text fields, scroll bars, menus, and check boxes.

Call Activity. setContentView () to set the view of the window displaying the activity. The content view is the root node view in the view hierarchy.

Service:

The service does not have a user interface, but it will always run in the background. For example, the service may play background music when the user is processing other things, or obtain data from the network, or perform some operations, and provide the Operation structure to the activity for display to the user. Each service is extended from the class Serivce.

The service can be used in multiple applications. For example, when the user starts other activities during multimedia playback, the program must continue playing the video in the background, for example, detecting file changes on the SD card, or record the changes in your geographic information location in the background. In short, the service is always hidden in the back.

Playing music on a multimedia player is a good example of the Application service. The multimedia player program may contain one or more activities through which the user selects and plays music. However, music playback does not require an activity, because you may want the music to be played continuously, even if you quit the player to execute other programs. To keep the music playing, the multimedia player activity may start a service to play music in the background. The Android system keeps the music playback service running, even after the activity of the service is started and exited.

An application can connect to a running service. After connecting to a service, you can use the interface exposed by the service to communicate with the service. For the service for playing music mentioned above, this interface may allow users to pause, stop or play music again.

A Service has a long life cycle and has no user interface. It can be used to develop programs such as monitoring programs. A better example is a media player that is playing a song from the playlist. In a media player application, there should be multiple activities that allow users to select and play songs. However, the music replay function does not have a corresponding activity, because the user will certainly think that the music should still be played when navigation to other screens. In this example, the activity of the Media Player uses Context. startService () to start a service, so that the music can be played in the background. At the same time, the system will keep the service running until the service stops running. In addition, we can connect to a service by using the Context. bindService () method (if the service is not running, it will be started ). After connecting to a service, we can also communicate with the interface provided by the service. In the media player example, we can also pause, replay, and other operations.

Like activity and other components, service also runs in the main thread of the application process. Therefore, they cannot block other components or user interfaces. Generally, a thread needs to be derived from these services to execute time-consuming tasks.

Like other components, a Service runs in the main thread, so it cannot be used for time-consuming operations. If time-consuming operations are required, you should enable another thread in the service and operate in another thread.

Like other application components, the Service runs in the main process. This means that if the service requires a lot of time-consuming or congested operations, it needs to be implemented in its subthread.

There are two types of services:

1. Local Service: the Local Service is used inside the application.

Local Service is used inside the application. In Service, you can call Context. startService () to start and call Context. stopService () to end. You can call Service. stopSelf () or Service. stopSelfResult () internally to stop the Service. No matter how many times startService () is called, you only need to call stopService () once to stop.

It can be started and run until someone stops it or it stops it. In this way, it starts by calling Context. startService () and ends by calling Context. stopService. It can call Service. stopSelf () or Service. stopSelfResult () to stop itself. No matter how many times the startService () method is called, you only need to call stopService () once to stop the service.

It is used to implement some time-consuming tasks of the application itself, such as querying the upgrade information. It does not occupy the application, such as the thread to which the Activity belongs, but is executed in the single-thread background, so that the user experience is better.

2. remote services: Remote Service is used between applications in the android system.

Remote Service is used between applications in the android system. You can define an interface and expose it for other applications to perform operations. The client establishes a connection to the service object and calls the service through that connection. Call the Context. bindService () method to establish a connection and start it to call Context. unbindService () to close the connection. Multiple clients can be bound to the same service. If the service is not loaded yet, bindService () loads it first.

It can perform program operations through APIS defined and exposed by itself. The client establishes a connection to the service object and calls the service through that connection. Connection to call the Context. bindService () method to establish, to call Context. unbindService () to close. Multiple clients can be bound to the same service. If the service is not loaded yet, bindService () loads it first.

It can be reused by other applications, such as the weather forecast service. Other applications do not need to write such services and can call existing services.

BroadcastReceive broadcast receiver:

Broadcase aggreger does not execute any tasks. It is only a type of component that receives and responds to broadcast notifications. Most broadcast notifications are generated by the system, such as changing the time zone and low battery usage. You have chosen an image or changed your language preferences. Applications can also send broadcast notifications, such as notifying other applications that some data has been downloaded to the device.

An application can contain any number of boradcase reveiver to respond to notifications that it deems important. All broadcast receivers are extended from the class BroadcastReceiver.

Broadcast receiver does not contain any user interfaces. However, they can start an activity to respond to received information or notify users through icationicationmanager. You can use multiple methods to notify users of new notifications: flashing background lights, vibrating devices, and making sounds. Generally, a program will place a persistent icon on the status bar. You can open this icon and read the notification information.

Your application can use it to filter external events and only receive and respond to external events that interest you (for example, when calls are made, or when data networks are available. The broadcast receiver has no user interface. However, they can start an activity or serice to respond to the information they receive, or use icationicationmanager to notify users. Notifications can be used in many ways to attract users' attention-flashing back lights, vibrations, and playing sounds. In general, a persistent icon is placed on the status bar. You can open it and get the message.

Broadcast type:

Normal Broadcast,Sent by Context. sendBroadcast (Intent myIntent)

Ordered Broadcast,Use Context. sent by sendOrderedBroadcast (intent, receiverPermission). The 2nd parameters of this method determine the broadcast level. The value range is-1000 to 1000. The higher the value, the higher the sending priority; the level at which the broadcast receiver receives the broadcast (the highest priority can be set through the priority in intentfilter to 2147483647). The same level of receipt is random, when the broadcast is received at a lower level, if the broadcast is received at a higher level or at the same level, the broadcast can be intercepted by the abortBroadcast () method to prevent other receivers from receiving the broadcast. There are other constructors, the so-called order means that each worker can be propagated to the next worker after execution, or the propagation can be completely aborted without being propagated to other worker workers. The sequence of worker er running can be controlled by android: priority in matched intent-filter. When priority has the same priority, worker er runs in any order.

Asynchronous Broadcast,Use Context. sendStickyBroadcast (Intent myIntent) is also sent by sendStickyOrderedBroadcast (intent, resultReceiver, schedcast, initialCode, initialData, and initialExtras). This method has the ordered broadcast and asynchronous broadcast features; to send an asynchronous broadcast: "Android. permission. BROADCAST_STICKY"/> Permission. After receiving and processing the Intent, the broadcast still exists until you call removeStickyBroadcast (intent) to remove it. They all run in an undefined order, usually at the same time. This will be more effective, but it means that the consumer cannot contain the results to be used or the APIs to be aborted.

Note that, even in Normal broadcasts, the system may resume one transmission to a receiver in some cases. In particular, a worker er may need to create a process. To avoid system overload, only one worker er can be run at a time.

Broadcast Receiver does not provide a visual interface for displaying Broadcast information. Notification and Notification Manager can be used to display the broadcast information content, icons, and vibration information.

Note: The intent parameter when sending the broadcast and Contex. startActivity () starts up with a different Intent. The former can be called by multiple broadcast receivers that subscribe to it, and the latter can only be called by one (Activity or service ).

Content Provider:

ContentProvider is one of the four main components in Android. It is mainly used for external data sharing, that is, using ContentProvider to share the data in the application to other applications for access. Other applications can use ContentProvider to operate on the data in the specified application. ContentProvider is divided into system and custom data, such as contacts and images.
The data operation package in android contains:
The first three data operations of file, sqlite3, Preferences, ContectResolver, and ContentProvider are only for data in the current application. The program cannot use these three methods to operate on data in other applications. In android, ContectResolver and ContentProvider are provided to operate data of other applications.

Applications can access some private data of other applications through contentprovider, which is a standard data sharing mechanism provided by Android. Shared data can be stored in a file system, SQLite database, or other media. Content provider extends from the ContentProvider class. By implementing a set of standard interfaces of this class, other applications can access the data controlled by it. However, the application does not directly call the methods in ContentProvider, but uses the ContentResolver class. ContentResolver can communicate with any ContentProvider, which cooperates with ContentProvider to manage communication between processes.

When the Android system receives a request that requires processing by a component, Android ensures that the host process of the component that processes the request is already running. If not, start the process immediately. When the host process of the requested component is already running, it will continue to check whether the requested component can be used. If not, it creates an instance of the requested component to respond to the request.

ContentProvider is an interface mechanism for sharing data between applications. It allows other applications to save or read various data types of this ContentProvider.

ContentProvider provides more advanced data sharing methods. Applications can specify the data to be shared, while other applications can, without knowing the data source and path, provides interfaces for querying, adding, deleting, and updating shared data. The built-in data of many Android systems is also provided to users through ContentProvider, such as Address Book, audio and video files, and image files.

The data mode of ContentProvider is similar to that of a database data table. Each row is a piece of data, and each column has the same data type. Each record has a long-type field _ ID, which uniquely identifies each record. ContentProvider can provide multiple datasets, and callers use URIs to operate data in different datasets.

The android platform provides Content Provider to provide a specified dataset of an application to other applications. The data can be stored in a file system, in an SQLite database, or in any other reasonable way. Other applications can use the ContentResolver class (see the ContentProviderAccessApp example) obtain or store data from the content provider. (equivalent to outsourcing a shell in an application), the content provider is required only when data is shared among multiple applications. For example, the address book data is used by multiple applications and must be stored in a content provider. Its Benefits: unified data access. Content Providers provided by the android system (top-level database names, but not top-level 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 number

Contact. People. Phones: storage phone number

Setting. System: System settings and preference settings


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.