"Go" Android Development Tour: Application Basics and Components

Source: Internet
Author: User
Tags sqlite database

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. Broadcast recipient (broadcast receivers)
      • 2.4. 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. Activities (Activities)

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 Span style= "color: #ff8040;" >activity class is concerned with creating windows, you can use the method setcontentview (View) puts its 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 almost all activity subclasses are implemented:

  1. oncreate (Bundle) : Initializes your activity, such as completing some drawing of the graph. Most importantly, in this method you will typically call findviewbyid (int) in your UI retrieves the widgets (widgets) that you need to interact with programmatically. setcontentview Specifies which file specifies the layout (main.xml), which can be displayed, and then we do the action, and our operation is wrapped up as an intent (Intent), and the intent is to deal with the activity that should be relevant.
  2. onpause () : Deal with what to do when you leave your activity. Most importantly, all changes made by the user should be committed here (usually ContentProvider saves 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.

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 Living Buddha's interface according to 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)

A 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).

2.3. Broadcast recipient (broadcast receivers)

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 .

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.4. Content provider (contents providers)

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.

Go to Android Development tour: Application Basics and Components (cont.)

Introduction

Previous Android Development tour: Application Basics and Components describes the basics of the application and the four components of Android, this article describes how to activate a group shutdown component. The topics in this article are as follows:

    • 1. Activating the component: Intention (Intents)
      • 1.1. Activation of the active (activity) component
      • 1.2. Activation of service Components
      • 1.3. Activation of the broadcast receiver (broadcast receiver) component
    • 2. Turn off the components
    • 3. manifest file
    • 4. Intent Filter
1. Activating the component: Intention (Intents)

When a request is received from the contentresolver , the content provider is activated. The other three components-activity, service, and broadcast receivers-are activated by an asynchronous message called intent (intent) . Intent is a Intent object that holds the content of the message. for activities and services , the intent object indicates the requested action name and the URI and other information that is the data for the action object. For example, it can pass a request to an activity, let it display a picture for the user, or let the user edit some text. for broadcast receivers , the intent object indicates the behavior of the broadcast. For example, when the camera button is pressed, it can broadcast to all objects of interest.

The method of activation is different for each component. The activation methods for the activity, service, and broadcast recipient components are described below.

1.1. Activation of the active (activity) component

An activity is loaded (or assigned a new job) by passing a intent object to context.startactivity () or activity.startactivityforresult () . The corresponding activity can see the initial intent, and this intent is to view the activation activity through the getintent () method. Android calls the active onnewintent () method to pass any subsequent intent.

An activity often starts the next one. If it expects the activity it initiates to return a result, it calls Startactivityforresult () instead of startactivity (). For example, if it launches an activity that lets the user pick a photo, it may return the selected photo. The result is a intent object that passes the Onactivityresult () method that invokes the activity.

1.2. Activation of service Components

Start a service (or give a new instruction to a running service) by passing a intent object to Context.startservice () . Android invokes the OnStart () method of the service and passes the intent object to it.

Similarly, a intent can be passed to Context.bindservice () to establish a continuous connection between the called component and the target service. This service will accept the intent object in the call to the Onbind () method (if the service has not started,Bindservice () will start it first). For example, an activity can connect to the music playback service described earlier and provide the user with an actionable (user interface) to control playback. This activity can call Bindservice () to establish a connection, and then invoke the object defined in the service to control playback.

1.3. Activation of the broadcast receiver (broadcast receiver) component

An application can pass a intent object to the

    • Context.sendbroadcast ()
    • Context.sendorderedbroadcast ()
    • Context.sendstickybroadcast ()

and other similar methods to generate a broadcast. Android passes intent through the onreceive () method to all broadcast recipients who are interested in this broadcast.

2. Turn off the components

The content provider is only activated when responding to Contentresolver requests. A broadcast receiver is activated only when it responds to broadcast messages. Therefore, it is not necessary to explicitly close these components.

The activity is different, it provides the user interface. Session with the user, so as long as the session continues, even if the conversation process is idle, it will remain active. Similarly, the service will remain operational for a long period of time. So Android provides an orderly way to shut down activities and services.

    • You can close an activity by calling its finish () method. An activity can also close another activity (it starts with Startactivityforresult ()) by calling the finishactivity () method.
    • The service can stop by calling its stopself () method, or call Context.stopservice ().

The component may also be shut down by the system when the component is no longer in use or when Android has to reclaim memory for more active components.

3. List (manifest) file

Before Android launches an application component, it must know that the component is present. So, the application declares its component in a manifest (manifest) file, which is packaged in an Android package. this. apk file will also include the application's code, files, and other resources.

This manifest file is an XML-structured file, and all Android applications call it Androidmanifest.xml. To declare an application component, it also does a lot of extra work, such as specifying the name of the library that the application needs to link to (in addition to the default Android library) and declaring the various permissions that the application expects to get.

But the main feature of the manifest file is still the component that declares the application to Android. For example, an activity can be declared as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<manifest ... >
<application ... >
<activity android:name= "Com.example.project.FreneticActivity"
android:icon= "@drawable/small_pic.png"
android:label= "@string/freneticlabel" ... >
</activity>
. . .
</application>
</manifest>

The name attribute of the <activity> element specifies the subclass of the activity class that implements the activities,icon and label Property points to the resource file that contains the icon and label for this activity that is presented to the user.

Other components are also declared in a similar way-the<service> element is used to declare the service, and the<receiver> element is used to declare the broadcast receiver, and <provider> element is used to declare a content provider. Activities, services, and content providers that are not declared in the manifest file will not be visible to the system and thus will not be run. However, broadcast receivers can be declared either in the manifest file or dynamically in code (as BroadcastReceiver objects) and called Context.registerreceiver () to register to the system.

4. Intent Filter

The intent object can explicitly specify the target component. If this designation is made, Android will find the component (according to the declaration in the manifest file) and activate it. But if intent is not explicitly specified, Android must find the component that is most appropriate for intent. This process is done by comparing the intent object with the intent filter for all possible objects . The intent filter for the component tells Android what type of intent it can handle. They are declared in the manifest file, just like other necessary information about the component. Here is an extension of the above example, which includes two intent filter declarations for the activity:

<?xml version= "1.0" encoding= "Utf-8"?>
<manifest ... >
<application ... >
<activity android:name= "Com.example.project.FreneticActivity"
android:icon= "@drawable/small_pic.png"
Android:label= "@string/freneticlabel" ... >
<intent-filter ... >
<action android:name= "Android.intent.action.MAIN"/>
<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter ... >
<action android:name= "Com.example.project.BOUNCE"/>
<data android:mimetype= "Image/jpeg"/>
<category android:name= "Android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
. . .
</application>
</manifest>
The first filter in the example--action: The combination of "Android.intent.action.MAIN" and Category: "Android.intent.category.LAUNCHER" is common. It marks the list of bootable applications that the activity displays in the Application Launcher, which the user sees on the device. In other words, this activity is the portal to the application and is the first activity that the user sees when they choose to run the application. The second filter declares that the activity is for a specific type of data.

A component can have any number of intent filters, each declaring a range of different capabilities. If it does not contain any filters, it will only be explicitly declared with intent activation of the target component name.

For broadcast receivers, it creates and registers a intent filter in code that is instantiated directly as an object of Intentfilter. Other filters are set in the manifest file.

If you're not fully aware of these concepts right now, I'm just going to give you the impression that you know the existence of these concepts or terminology and what they might be doing. I will go back to these things in more detail and combine some examples, and you will know these things clearly by then.

"Go" Android Development Tour: Application Basics and 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.