Android development: Application basics and components

Source: Internet
Author: User

-- Success is a person who can withstand loneliness. The following articles will describe the principles and terminologies of the android application, which may be boring. If you can calm down, I believe that success will belong to you.

Introduction

To prepare for the following examples, this article and the next few articles will introduce the principles and terminologies of Android applications. These are also things that Android Developers must understand and understand deeply. The topic of this article is as follows:

  • 1. Application Basics
  • 2. Application Components
    • 2.1 Activity)
    • 2.2. Services)
    • 2.3 broadcast receiver (broadcast receivers)
    • 2.4 content providers)

This is because the content is more theoretical and not illustrated by examples. It looks boring. I will write these articles for a short time, so that they can be easily absorbed.

1. Application Basics

Android applications are written in Java programming language. Suffix. This file is an intermediary or tool that distributes applications and installs them on mobile devices. Users download this file to their devices. All the code in a .apk file is considered as an application.

Aapt:

Aapt is the abbreviation of Android asset packaging tool, which is included in the tools/directory of the SDK. View, create, and update zip-compatible archive files (ZIP, jar, and APK ). It can also compile resource files into binary packages.

Although you may not use the APPT frequently, the build script and IDE plug-in use this tool to package the APK file to form an Android Application.

For more detailed usage, open a terminal, go to the tools/directory, and run the following command:

  • Linux or Mac OS:./aapt
  • Windows: aapt.exe

Note: The tools/directory is/platforms/Android-x/tools/Under the android SDK directory/

In many ways, every Android app lives in its own world:

  • By default, each application runs in its own Linux Process. When any code in the application needs to be executed, Android starts the process. When it does not need to be requested by other applications, Android closes the process.
  • Each application has its own Java Virtual Machine (VM), so the application code runs independently of the code of all other applications.
  • By default, each application is assigned a unique Linux User ID. Set permissions to files for each application to be visible only to users and applications themselves-although there are some ways to expose them to other applications.

It is possible to set two applications to share a user ID, in which case they can see the other party's file. To save system resources, applications with the same ID can share the same VM in the same Linux Process.

2. Application Components

One of the main features of Android is that an application can use the elements of other applications (assuming these applications allow ). For example, if your application needs to display a scroll list of images, and other applications have developed a suitable scroll bar that can be used by other applications, you can call this scroll bar to work without having to develop one by yourself. Your application does not need to be incorporated into or linked to other application code. On the contrary, when the demand arises, it only starts other application blocks.

For this operation, when any part of the application is requested, the system must be able to start the process of an application and instantiate the Java object of this part. Therefore, unlike most applications in other systems, Android applications do not have a single entry point (for example, there is no main () function ). On the contrary,Several necessary components are required for system instantiation and operation.. There are four types of components:

  1. Activity (activities)
  2. Services)
  3. Broadcast receivers)
  4. Content Providers)

However, not all applications must contain the above four parts. Your applications can be built by one or more of the above. When you decide which components are used to build Android applications, you should list them in androidmanifest. in XML files, you can declare application components and their features and requirements. About androidmanifest. XML Development in Android: A Brief Introduction to directory structure 1.6 and androidmanifest. xml of the helloworld project. You can refer to it and introduce it in the next article.

2.1 Activity)

An activity represents a visual user interface and focuses on a user's events. For example, an activity may represent a list of menu items that a user can select, or a picture along with its title may be displayed. A text message application may have an activity that displays the list of contacts for sending messages. For the second activity, write information to the selected contacts. For other activities, re-view the old information or change the settings. Although they work together to form an overall user interface, each activity is independent of other activities. Each is implemented as a subclass of the activity base class.

Android. App. Activity: because almost all activities (activities) interact with users, the activity class follows the creation window and you can use the methodsetContentView(View)Put your UI in it. However, activities are usually displayed to users in full screen mode. They can also be displayed in floating windows or embedded in another activity. There are two methods that are implemented by almost all activity subclasses:

  1. Oncreate (bundle): initialize your activity, such as drawing some images. Most importantly, in this method, you usually callThe setcontentview (INT) method defines your UI and usesFindviewbyid (INT) in your UIRetrieve the widgets that you need to interact programmatically (widgets ).setContentViewSpecifies the file to which the layout (main. XML), this interface can be displayed, and then we perform relevant operations. Our operations will be encapsulated into an intent (intent), and then this intent will process relevant activities.
  2. onPause(): Process what you want to do when you leave your activity. Most importantly, all changes made by users should be submitted here (normallyContentProviderSave data ).

An application may only contain one activity, or, as mentioned earlier, a text message application may contain several activities. What these activities are and how much they are, of course, depends on its application and design. Generally, when an application is started, the activity marked as the first should be displayed to the user. Moving from one activity to another starts from the completion of the current activity.

Each activity has a default window. Generally, a window fills up the whole screen, but it may be smaller than the screen or floating on another window. An activity can also use an additional window, such as a pop-up dialog box, or a window that displays important information to the user when a user selects a specific item on the screen.

The visible content of a window is provided by a hierarchical view-object inherited from the view base class. Each view control is a specific rectangular space in the window. The parent view contains and organizes the layout of the Child view. The rectangles drawn by the leaf view (at the bottom layer of the hierarchy) directly control and respond to user operations. Therefore, a view is where activities interact with users. For example, a view may display a small image and initiate an action when a user clicks an image. Android has some ready-made views that you can use, including buttons, text fields, scroll bars, menu items, and check boxes) and so on.

You can use activity. setcontentview () to place a view hierarchy in an activity window. Content view (Content ViewIs the root view object of the hierarchy. Shows the hierarchy:

Figure 1. View hierarchy

Activity. setcontentview () method: Public void setcontentview (INT layoutresid): sets the activity interface according to the layout resource. Resources will be exaggerated. add all the top-level views in the layout resource file to the activity.
2.2. Services)

A Service does not have a visual user interface, but runs without deadline in the background. For example, a service may play background music while a user does other things, or it may expand data from the network, or compute something and provide the result to the desired activity (activities ). Each service is inherited from the service base class.

Each service class is declared in androidmanifest. xml. Services can be started through context. startservice () and context. bindservice.

A typical example is that a media player plays a song in a playlist. The player app may have one or more activities, allowing users to select songs and start playing. However, music playback is not processed by an activity because the user wants to keep the music playing, and when the user leaves the player to do other things. To keep the music playing, a media player activity can start a service running on the background. The system will keep the music playing service running, even when the media player leaves the screen.

You can connect to (bind to) a continuously running service (and start the service if it is not yet running ). After the connection, you can communicate with the service through the interface exposed by the Service. For music services, this interface allows users to pause, rewind, stop, and replay.

Like activities and other components, services run in the main thread of the application process. Therefore, they will not block other components or user interfaces. They often generate other time-consuming tasks (such as playing music ).

2.3 broadcast receiver (broadcast receivers)

A broadcast receiver is a component that does nothing but accepts broadcast announcements and responds accordingly. Many broadcasts are derived from system code, such as announcement time zone changes, low battery usage, pictures taken, and user-changed language preferences. An application can also initiate a broadcast, for example, for other programs to know that some data has been downloaded to the device and they can use the data.

An application can have any number of broadcast recipients to reflect any announcements that it deems important. All receivers inherit from the broadcastreceiver base class.

Broadcastreceiver class:

Is the base class of the intent (intents) sent by sendbroadcast. You can use context. registerreceiver () to dynamically register instances of this class, or use tags in androidmanifest. XML for static release.Note: If you register a receiver in activity. onresume (), you should log out of the receiver in activity. onpause. Because you do not receive an intent when paused, canceling it will cut unnecessary system overhead. Do not log out of activity. onsaveinstancestate () because it will not be called if the user moves to the previous stack.

There are two main acceptable broadcast types:

  1. Normal Broadcast(Sent by context. sendbroadcast) is completely asynchronous. All broadcast receivers run in disorder and are often received at the same time. This is more efficient, but it means that the receiver cannot use the results or terminate broadcast data transmission.
  2. Ordered Broadcast(Sent by context. sendorderedbroadcast. Since each receiver executes in sequence, it can be propagated to the next receiver, or it can completely terminate the propagation so that it will not be transmitted to other receivers. The running sequence of the receiver can be determined by the intent-Filterandroid:priorityProperty Control.

The broadcast receiver does not display a user interface. However, they initiate an activity to respond to received information, or they may useNotificationManagerTo notify the user. Notifications can be used in many ways to get users' attention-flashing backlights, vibrating devices, and playing sounds. It is typically placed on a persistent icon in the status bar. You can open it to obtain information.

2.4 content providers)

The content provider provides the 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. The content provider inherits from the contentprovider base class and implements a standard method set so that other applications can retrieve and store data. However, applications do not directly call these methods. Instead, they use a contentresolver object and call its method. Contentresolver can communicate with any content provider. It cooperates with the provider to manage the communication between participating processes.

Content Providers are one of the main components of Android applications and provide content to applications. They encapsulate data and provide it to applications through a single contentresolver interface. Content Providers are only required to share data among multiple applications. For example, the address book data is used by multiple applications and must be stored in a content provider. If you do not need to share data among multiple applications, you can directly use sqlitedatabase.

When contentresolver sends a request, the system checks the permissions of the given Uri and sends the request to the content provider for registration. The content provider can understand what the URI wants. The urimatcher class is used to help groups parse Uris.

The main implementation methods are as follows:

  • query(Uri, String[], String, String[], String)Return data to the caller
  • insert(Uri, ContentValues)Insert data to the content provider
  • update(Uri, ContentValues, String, String[])Update existing data of the content provider
  • delete(Uri, String, String[])Delete data from the content provider
  • getType(Uri)Returns mime-type data from the content provider.

For more information about contentresolver, see related documents.

Every time there is a request that should be processed by a specific component, android can ensure that the application of this component is running, if not, start it, and an appropriate component instance is available, if not, create it.

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.