Android App Components

Source: Internet
Author: User
Tags sqlite database

Introduction

To prepare for the following examples, this and the next few will describe the principles and terminology of Android applications, something that developers of Android must understand and understand deeply. The topics in this article are as follows:

    • 1. Application Basics
    • 2. Application Components
      • 2.1. Activities (Activities)
      • 2.2, Service (services)
      • 2.3, Intent
      • 2.4. Broadcast recipient (broadcast receivers)
      • 2.5, Notification
      • 2.6. Content provider (contents providers)

Because these content comparison theory, and did not use the example to illustrate, looks will be more boring, I will write these several relatively short, convenient for everyone to absorb.

1. Application Basics

Android applications are written in the Java programming language. The compiled Java code-including any data and resource files required by the application, is bundled into an Android package via the aapt tool, and the archive file is suffixed with an. apk. This file is an intermediary or tool for distributing applications and installing to mobile devices, and users download this file onto their devices. All the code in an. apk file is considered an application.

AAPT:

AAPT is the acronym for the Android Asset Packaging tool, which is included in the tools/directory of the SDK. View, create, and update zip-compatible archive files (zip, jar, apk). It can also compile the resource file into a binary package.

Although you may not often use appt directly, the build script (build scripts) and IDE plugin will use this tool to package the APK file to form an Android application.

For more detailed use of the details, open a terminal, enter the tools/directory, run the command:

  • Linux or Mac operating system:./aapt
  • Windows:aapt.exe

Note: The tools/directory refers to the /platforms/android-x/tools/ in 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. Android will start the process when any code in the application needs to be executed, and Android will close the process when it is not needed and the system resources are requested by other applications.
    • Each application has his 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. The permissions set for each application's files are visible only to the user and the application itself-although there are also ways to expose them to other applications.

It is possible to set up two applications to share a user ID, in which case they can see each other's files. To conserve system resources, applications with the same ID can also be scheduled to share the same VM in the same Linux process.

2. Application Components

One of the main features of Android is that an application can take advantage of the elements of other applications (assuming these applications allow it). For example, if your application needs to display a scrolling list of images, and other applications have developed a suitable scroll bar that can be provided to other applications, you can call this scroll bar to work without having to develop one yourself. Your application does not have to be incorporated into other application code or linked to it. Instead, it just launches other application blocks when the demand is generated.

For this job, 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 for that part. Therefore, unlike most other system applications, Android applications do not have a single entry point (for example, no main () function). Instead, the system is able to instantiate and run several necessary components . There are four types of components:

    1. Activities (Activities)
    2. Service (services)
    3. Broadcast recipient (broadcast receivers)
    4. Content provider (contents providers)

However, not all applications must contain the four sections above, and your application can be organized by one or more of the above. When you decide which of these components to use to build Android apps, you should list them in the Androidmanifest.xml file, where you can declare application components and their features and requirements. About Androidmanifest.xml on Android development tour: The directory structure of the HelloWorld project 1.6, Androidmanifest.xml A brief introduction, you can refer to the next article will also introduce it.

2.1. Activity (activities)--the presentation layer of the application

An activity represents a visual user interface that focuses on the events that a user is engaged in. For example, an activity might represent a list of menu items that a user can select, or it might display a photo along with its caption. A text messaging application may have an activity that displays a list of contacts to send messages, a second activity that writes messages to selected contacts, other activities, re-viewing old information, or changing settings. While they work together to form a holistic user interface, each activity is independent of other activities. Each is implemented as a subclass of the Activity base class.

android.app.Activity class: Because almost all activities (activities) interact with the user, the Activity class focuses on creating windows, and you can use the method to setContentView(View) put your own UI inside. However, activities are usually presented to the user in full-screen mode, or in a floating window or embedded in another activity. There are two methods that are implemented by almost all Activity subclasses:

    1. onCreate(Bundle):初始化你的活动(Activity),比如完成一些图形的绘制。最重要的是,在这个方法里你通常将用布局资源(layout resource)调用setContentView(int)方法定义你的UI,和用findViewById(int)在你的UI中检索你需要编程地交互的小部件(widgets)。setContentView指定由哪个文件指定布局(main.xml),可以将这个界面显示出来,然后我们进行相关操作,我们的操作会被包装成为一个意图(Intent),然后这个意图对应有相关的activity进行处理。
    2. onPause(): Deal with what you have to do when you leave your activity. Most importantly, all changes made by the user should be committed here (usually ContentProvider saving the data).

An application may contain only one activity, or, like the SMS app just mentioned, it may contain several activities. What these activities are, and how much, of course, depends on its application and design. In general, when an application is started, the activity that is marked as the first should be displayed to the user. Moving from one activity to another activity is done by the current activity next.

Each activity has a default window. In general, the window fills the entire screen, but it may be smaller or floating on other windows than the screen. An activity can also use additional Windows-such as pop-up dialogs, or when a user selects a particular item on the screen-a window displays important information to the user.

Activity uses fragment and views to lay out and display information. The visual content of a window is provided by a hierarchical view-object that inherits from the view base class. Each view control is a specific rectangular space within the window. The parent view contains and organizes the layout of the child view. The leaf view (at the bottom of the hierarchy) draws a rectangle that directly controls and responds to the user's actions. Therefore, a view is where the activity interacts with the user. For example, a view might show a small picture and initiate a behavior when the user clicks on the picture. Android has some out-of-the-box views you can use, including buttons (buttons), text fields, scroll bars (scroll bars), menu items (menu items), checkboxes (check boxes), and more.

Place a view hierarchy in an active window by using the Activity.setcontentview () method. Content view isThe root View object of the hierarchy. The hierarchy looks like this:

Figure 1, hierarchy of views

Activity.setcontentview () method: public void setcontentview (int layoutresid): Sets the active interface based on the layout resource. The resource will be exaggerated, adding a layout resource file to all the top-level views (top-level view) to the activity.

2.2. Service (services)-workers not visible in the application

The service does not have a visual user interface, but runs in the background with no deadlines. For example, a service may be playing background music while the user is doing something else, or it may fetch data from the network, or calculate something and provide the result to the desired activity (activities). Each of the services inherits from the service base class.

Each service class has a corresponding <service> declaration in Androidmanifest.xml. Services can be started by Context.startservice () and Context.bindservice () .

A typical example is a media player playing a playlist of songs. The player application will likely have one or more activities (activities) that allow the user to select songs and start playing. However, the music playback itself is not handled by an activity because the user wants to keep the music playing and when the user leaves the player to do other things. In order to keep the music playing, the media player activity can start a service running in the background. The system will keep the music playback 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 already running). Once connected, you can communicate with the service through the interfaces exposed by the service. For music services, this interface allows users to pause, rewind, stop, and replay.

Like activities (activities) and other components, the service (services) runs in the main thread of the application process. As a result, they will not block other components or user interfaces, they often produce other time-consuming tasks (such as music playback). They can update data sources and activity, trigger notifications, and broadcast intent.

2.3, intent--powerful application of information transfer between the framework

Android uses a lot of intent. The intent can be used to start and stop activity and service, broadcast messages on a system-wide or target activity, service, or broadcastreceiver, and request a specific piece of data to perform operations.

2.4. Broadcast receiver (broadcast receivers)--intent listener

A broadcast receiver is such a component that it does nothing but receives a broadcast announcement and responds accordingly. Many broadcasts originate from system code, such as the announcement of time zone changes, low battery power, pictures taken, and user-changed language preferences. Applications can also initiate broadcasts, for example, in order for other programs to know that certain data has been downloaded to the device and that they can use the data.

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

Broadcastreceiver class:

is the base class that accepts the intent (intents) sent by the Sendbroadcast () . You can use context.registerreceiver () to dynamically register instances of this class, or to publish statically via the <receiver> tab in Androidmanifest.xml. Note: If you register a recipient in Activity.onresume () , you should unregister it in activity.onpause () . Because when you pause you will not receive the intention to unregister it will reduce unnecessary system overhead. Do not unregister it in 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 broadcasts (sent by Context.sendbroadcast ) are completely asynchronous. All broadcast receivers run in an unordered fashion and are often received at the same time. This is more efficient, but it means that the recipient cannot use the results or terminate broadcast data propagation.
    2. ordered broadcasts (sent by Context.sendorderedbroadcast ) are passed to one recipient at a time. Because each recipient executes sequentially, it can propagate to the next sink, or it can completely terminate the propagation so that he does not pass it on to other receivers. The order in which the receivers are run can be controlled by the properties of the matching intent filter (Intent-filter) android:priority .
2.5. notification--sends the signal to the user

The broadcast recipient does not display a user interface. However, they initiate an activity to respond to received information, or they may use NotificationManager to notify the user. Notifications can be used in a variety of ways to get the user's attention-flashing backlighting, vibrating devices, playing sounds, and more. Typically placed on a persistent icon in the status bar, the user can open the get information.

2.6. Content provider (providers)-workers not visible in the application

Content provider provides the specified dataset for an application to other applications. This data can be stored in a file system, in a SQLite database, or in any other reasonable manner. The content provider inherits from the ContentProvider base class and implements a standard set of methods that enable other applications to retrieve and store data. However, applications do not call these methods directly. Instead, they are replaced by methods that use a contentresolver object and invoke it. Contentresolver can communicate with any content provider, which works with providers to manage communication between participating processes.

Content providers are one of the main components of Android applications that provide content to applications. They encapsulate the data and are available to the application through a single contentresolver interface. 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. If you don't need to share data among multiple applications, you can use Sqlitedatabase directly.

When Contentresolver makes a request, the system checks the permissions of the given URI and passes the request to the content provider for registration. The content provider can understand what the URI wants. The Urimatcher class is used to help group parse URIs.

The main methods to be implemented are as follows:

    • query(Uri, String[], String, String[], String)Returns data to the caller
    • insert(Uri, ContentValues)Inserting data into a content provider
    • update(Uri, ContentValues, String, String[])Update data that the content provider already exists
    • delete(Uri, String, String[])Delete data from the content provider
    • getType(Uri)Returns the MIME type data in the content provider

For more information about Contentresolver , please see the documentation.

Whenever there is a request that should be handled by a particular component, Android can make sure that the component's application is running, and if not, start it, and an appropriate component instance is available if it is not created.

Android App Components

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.