Getting started with Android development: Application basics and components

Source: Internet
Author: User

1. Application Basics

Android applications are written in Java programming language. Compiled Java code, including any data and resource files required by the application, is bundled into an Android package using the aapt tool, and the archive file is suffixed with .apk. 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 scripts and IDE plug-ins 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 to assume that these applications allow it ).

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, the system can instantiate and run several necessary components. There are four types of components:

  • Activity Activities)
  • Services)
  • Broadcast receiver Broadcast receivers)
  • 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. For a brief introduction to AndroidManifest. xml 1.6 and AndroidManifest. xml in the directory structure of the Android project, see.

2.1 activity Activities)

An activity represents a visual user interface and focuses on the events that a user is engaged in. 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 Class: because almost all activities of activities are interactive with users, you can use setContentView (View) to add your UI to the creation window. 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:

OnCreate (Bundle): initializes your Activity. For example, you can draw some images. Most importantly, in this method, you usually use the layout resource) to call the setContentView (int) method to define your UI, and use findViewById (int) retrieve the widgets you need to interact programmatically in your UI ). SetContentView specifies the file by which the layout is main. xml), this interface can be displayed, and then we perform relevant operations, our operations will be packaged into an Intent), and then this Intent will process the relevant activity.

OnPause (): process what to do when you leave your activity. Most importantly, all changes made by the user should be submitted here. Usually ContentProvider stores 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 leaf view is on the bottom layer of the hierarchy. The rectangle is drawn to 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 button buttons, text field text fields), scroll bar scroll bars), menu item menu items), check box boxes, and so on. You can use Activity. setContentView () to place a view hierarchy in an Activity window. Content view) is 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 Page Based on the layout resource. Resources will be exaggerated. add all the top-level views in the layout resource file to the activity.

2.2. Service 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 something else, or it may obtain 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 has a corresponding <service> declaration 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. This player application may have one or more activity 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. Can be bound to) a continuous service and start the service if it has not been run ).

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 the active activities) and other components, service services run in the main thread of the application process. Therefore, they will not block other components or user interfaces, and 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 in the electric pool, pictures taken, and language preferences changed by users.

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 that accepts intents sent by sendBroadcast. You can use Context. registerReceiver () to dynamically register the instance of this class, or use the <Cycler> label 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:

Normal broadcast is sent by Context. sendBroadcast) 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.

Ordered broadcast is sent by Context. sendOrderedBroadcast) to a receiver at a time. Since each receiver executes in sequence, it can be propagated to the next receiver or completely terminated so that it will not be passed to other receivers. The running sequence of the receiver can be controlled by the android: priority attribute of the matched intent filter intent-filter.

The broadcast receiver does not display a user interface. However, they initiate an activity to respond to received information, or they may use icationicationmanager to notify users. Notifications can be noticed in multiple ways-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)

Content provider) provides 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. 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) returns data to the caller

Insert (Uri, ContentValues) insert data to the content provider

Update (Uri, ContentValues, String, String []) updates existing data of the content provider

Delete (Uri, String, String []) deletes data from the content provider

GetType (Uri) returns the MIME type data in 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.