Android Development-API Guide-Application Development Basics

Source: Internet
Author: User
Tags least privilege

Application Fundamentals

English Original: http://developer.android.com/guide/components/fundamentals.html
Acquisition Date: 2014-04-16
Moved from the original blog: http://blog.sina.com.cn/s/blog_48d491300101h41p.html

In this article
    1. Application components
      1. Activating components
    2. Manifest file
      1. declaring components
      2. Declaring the application's requirements
    3. Application Resources

Android applications are written in the Java language. The Android SDK tool software compiles the code-along with the data and resource files-into the APK:Android Package , which is a packaged file with a suffix .apk . The APK file contains all the content required by the Android app, as well as the installation files used to install the app on your Android device.

Once the installation is complete, each Android application runs independently in its own security sandbox:

    • The Android operating system is a multi-user Linux system, where each application is a separate user.
    • By default, each application is given a unique Linux user ID (the ID is for system use only and is not visible to the application). The system assigns permissions to all files within the application, and only the user ID that is given to the application can access the files.
    • Each process has its own virtual machine (VM), so the code for different applications runs independently of each other.
    • By default, each application runs in its own Linux process. Whenever a component of the application needs to be run, Android starts the process and shuts down the process when it is no longer needed or when memory must be freed for another application.

In this way, the Android system implements the principle of least privilege . In other words, each application accesses only the necessary components by default. This creates a very secure environment where applications cannot access unauthorized system content.

However, there are many ways an application may share data with other applications or access system services:

    • You can have two applications share the same Linux user ID so that they can access the files from one another. To conserve system overhead, applications with the same user ID can also run in the same Linux process and share the same VM (these applications must also be signed by the same certificate).
    • Applications can request access to device data, such as user contacts, text messages, mount Storage (SD cards), cameras, Bluetooth, and so on. Permissions for all applications must be authorized by the user at the time of installation.

The above outlines how the Android application works in the system. The remainder of this article describes:

    • The main components required to build the application.
    • The manifest file used to declare the component and the required hardware.
    • The resources separated from the code allow the application to display the interface in a friendly manner based on a variety of hardware configurations.
Application components

Component (component) is the base part for building Android applications. Each component is a separate entry point through which the system can enter your application. Not every component is a portal for users, and some components are interdependent, but each component runs as an entity and plays a specific role-each component is the only component that contributes to the overall performance of the application.

There are four types of application components. Each class of components implements different goals, with varying lifecycles from creation to extinction.

These four types of application components are described below:

Activity
Activity represents a screen (window) that contains a user interface. For example, an email application might contain an activity that shows an unread mailing list, an activity that writes a message, and an activity that reads a message. While the email application consists of multiple activity together to form a complete user experience, each activity is independent of each other. Therefore, another application can start any of these Activity (if allowed by the email application). For example, to allow a user to share a photo, a photo app can initiate the Activity of the email application to compose a new message.

The activity is implemented as Activity a subclass of the object, and see activity in the Development Guide for more information.

Service
A
service is a component that runs in the background to perform long-running operations or to service a remote process. The service does not provide a user interface. For example, when a user uses another application, the service can play music in the background, or it can download data over the network, which does not require Activity to interact with the user. Other components, such as Activity, can start and run the service and can be bound to interact with it.

Services are Service implemented as subclasses of objects, and you can learn more in the developer Guide's services.

Content Provider
Content Provider manages a shareable set of application data. You can keep your data in a file system, SQLite database, Web, or persistent storage accessible to any other application. With content Provider, other applications can query and even modify data (if Content Provider allows). For example, the Android system provides a Content Provider that manages user directory information. In this way, any application that has the appropriate permissions can query a subset of the data in the Address Book Content Provider (for example ContactsContract.Data ) to read and write information about a contact.

Content Provider is also useful for data that is private to read and write applications. For example, the routine note Pad uses a Content Provider to save notes.

Content Provider is implemented as a ContentProvider subclass, and a standard set of APIs must be implemented so that other applications can commit transactions. Please refer to the Content Providers section of the Developer's Guide for details.

Broadcast receivers
A broadcast receiver is a component that responds to system-level broadcast information. Many of the broadcasts originate from the system-such as the screen is off, the battery is low, and a picture is taken. The application can also initiate broadcasts-such as notifying another program that the required data has been downloaded to the local device and is available. Although the broadcast receiver does not display the user interface, it can create a status bar notification to notify the user when a broadcast event occurs. However, more often than not, a broadcast receiver simply acts as a "portal" for other components to do a very small amount of work. For example, it can initialize a service and perform certain tasks based on broadcast events.

A broadcast sink is implemented as a subclass of an BroadcastReceiver object, and every broadcast that is distributed is an Intent object. For more information, see BroadcastReceiver classes.

The Android system has a unique design, which is that any application can launch components of other applications. For example, let's say you want to have your users take pictures with the camera, and other applications have already done that, and your app can be used directly without having to develop an Activity to complete the camera function. You don't even have to include or link the code of the camera app, just start the photo Activity in the camera app. After the shot is completed, the photos will even be returned directly to your app for use. For the user, the camera app is just like a part of your application.

When a component is started, the system initiates the process of the application (if the program is not yet running) and instantiates the classes required by the component. For example, if your application launches a snapshot activity in the camera app, this activity runs in the process of the camera app, not the process of your application. Therefore, unlike most other systems, Android applications do not have a single entry point (such as no main() function).

Because the system runs each application into a separate process, file permissions restrict access to other applications, and your application cannot directly launch components from other applications. But the Android system can do this. Therefore, to activate the components of other apps, you must distribute a message to the system that sets the Intentto activate a component. The system will then start the component for you.

Activating components

Of the four types of components, there are three-activity, service, and broadcast receivers-all activated by an asynchronous message named Intent . At run time, Intent binds to a component (you can treat them as request messages from other components that perform an action), whether the component belongs to your app itself or another application.

Intent is created with an Intent object that defines a message that activates a component or class of components (Intent, respectively, explicitly or implicitly).

For Activity and services, Intent defines the action to be performed (for example, "View" or "send" information) and can specify the URI of the data being manipulated (the component to be activated may need to know) For example, a Intent may send a request to make a Activity displays a picture or opens a Web page. At some point, when you start an activity and receive results, the activity also Intent returns results in (for example, you can submit a Intent to let the user pick a contact and return the data-the returned Intent contains a URI that points to the contact information).

For a broadcast receiver, Intent simply defines the message to broadcast (for example, a broadcast that is low on power can contain only one "low battery" string.)

The remaining class of component Content Provider is not activated by Intent. Instead ContentResolver , it is started by a request made. The content Resolver is responsible for handling all of the content Provider transactions, so the component that needs to execute the transaction does not have to call ContentResolver the object's methods. This creates an abstraction layer between the Content Provider and the component that requests the data (in security considerations).

Each of these components has its own activation method:

    • Intent startActivity() startActivityForResult() You can start an Activity (or let it perform some new tasks) by passing in or (if you need to return the result).
    • By passing Intent startService() in, you can start a service (or post new instructions to an existing service). Or you can Intent pass bindService() in to bind a service.
    • sendBroadcast() sendOrderedBroadcast() sendStickyBroadcast() Intent You can initialize a broadcast message by passing in one of the methods, or the like.
    • By invoking ContentResolver The query() method, you can execute a query on the Content Provider.

For more information about Intent, see document Intents and Intent filters. More information about activating components is also covered in the following documents: Activity, Services, BroadcastReceiver and content Provider.

Manifest file

Before starting an application component, the Android system must know the presence of the component, which is achieved by reading the application's AndroidManifest.xml file ("Manifest" file). The file must be located at the root of the project, and the application must declare all components in the file.

In addition to declaring application components, Manifest files have other uses, such as:

    • Determine the user rights required for an application, such as accessing the Internet or reading and writing user contacts
    • Declaring the minimum version API level required by your application indicates that the application will use this version of the API.
    • Declare the hardware and software requirements of your application, such as: Camera, Bluetooth service, and multi-touch screen.
    • The application requires a linked API library (a library other than the Android system API), such as the Google Maps library.
    • Other
declaring components

The primary purpose of the Manifest file is to inform the system of the components of the application. For example: The Manifest file can declare an Activity as follows:

<?XML version= "1.0" encoding= "Utf-8"?><Manifest... >    <ApplicationAndroid:icon= "@drawable/app_icon.png" ... >        <ActivityAndroid:name= "Com.example.project.ExampleActivity"Android:label= "@string/example_label" ... >        </Activity>        ...    </Application></Manifest>

In the < application > element, the android:icon attribute points to an icon resource that identifies the application.

In the < activity > element, the android:name attribute sets the Activity fully qualified class name of the subclass, and the android:label property sets a string to use as the Activity caption.

All components of the application must be declared according to the following rules:

    • Elements used in Activity < activity >
    • Elements for the service < service >
    • Elements for broadcast receivers < receiver >
    • Elements for Content Provider < provider >

If your code uses some Activity, service, and Content Provider, but is not declared in the Manifest file, the system cannot see these components, so they cannot take effect. However, a broadcast receiver can be declared either in the Manifest file or dynamically created (created as an object) with code and BroadcastReceiver registerReceiver() registered.

For more information about building a Manifest file, see document Androidmanifest.xml file

Declaring the compatibility of components

As described in the Activating Components section, you can use one Intent to launch activity, service, and broadcast receivers. You can start with an explicitly named Target component (the class name of the component) in Intent. However, the true strength of Intent lies in the idea of implicit Intent . The implicit Intent can be used to find the component that executes this action on the device and start it, as long as the type of action to be executed (and the data that the action uses) is indicated. If there are multiple components that can perform this Action, the user can choose one.

The system identifies the components that can respond to Intent by comparing the received Intent with the Intent filter in the Manifest file of the other application.

When you declare an activity in the application's Manifest file, you can also include a Intent filter that declares that the activity can respond to Intent from other applications. By adding a child element under the component declaration element < intent-filter > , you can declare a Intent filter for the component.

For example, if you have created an email application with an Activity that composes a new message, you can declare a Intent filter that responds to the "send" type Intent (for sending new messages) as follows:

<Manifest... >    ...    <Application... >        <ActivityAndroid:name= "Com.example.project.ComposeEmailActivity">            <Intent-filter>                <ActionAndroid:name= "Android.intent.action.SEND" />                <DataAndroid:type="*/*" />                <categoryAndroid:name= "Android.intent.category.DEFAULT" />            </Intent-filter>        </Activity>    </Application></Manifest>

Then, if other applications create a ACTION_SEND type of Action and pass it startActivity() on, the system can start your activity and the user can draft and send an email.

For more information on creating Intent filters, see document Intent and Intent filters.

Declaring application requirements

Android supports a variety of devices, not all of which provide the same hardware configuration. In order to prevent your application from being installed on devices that do not provide the appropriate hardware, it is important to clearly define a configuration file, which declares the hardware and software requirements in the Manifest file. Most statements are only reported, and the system does not read them. But to allow users to filter on hardware devices as they search for applications, external services like Google Play will read this information.

For example, if your application needs to use the camera and Android 2.1 + API (API Level 7), you can make the following statement in the Manifest file:

<Manifest... >    <uses-featureAndroid:name= "Android.hardware.camera.any"android:required= "true" />    <USES-SDKandroid:minsdkversion= "7"android:targetsdkversion= "+" />    ...</Manifest>

Now, devices that don't have a webcam and Android that's under version 2.1 won't be able to install your app from Google Play. Now, devices. Does not has a camera and has an

However, you can also declare that your application uses a webcam but is not required to use it. At this point, your application must be required set to "false" , and at run time, detect the presence of a camera in order to disable the functionality associated with it in a timely manner.

More detailed information is given in document device compatibility on how to keep applications compatible with various devices.

Application Resources

Android apps are not just made up of source code-they also need to use resource files, slices, audio files, and all the other visualizations that are separate from the source code. For example, you need to define the Layout of animations, menus, colors, and Activity user interfaces with an XML file. Resource files allow you to easily change the appearance of your application without modifying the source code-by giving an alternative resource set-you can optimize your application based on a variety of device configurations, such as different languages and screen sizes.

The SDK compilation tool defines a unique integer ID for each resource in the Android project to reference the resource from source code or other resources in XML format. For example, if your application contains a logo.png picture file (saved in a res/drawable/ directory), the SDK compilation tool will create a R.drawable.logo unique ID named, which you can use to refer to the image and put it in the user interface.

One of the main points of separating the resource files from the source code is to configure different alternative resources for each device. For example, by defining a string for the user interface in XML format, you can translate the string into a different language and save it in a separate file. Then, depending on the language identifier followed by the resource directory name, such as the French string res/values-fr/ , and the user's language settings, the Android system will apply the string of the corresponding language to the user interface.

Android offers a number of different identifiers for alternative resources. In order to define the device configuration required for a resource, the identifier is a short string in the resource directory name. For example, depending on the screen orientation and size of the device, it is often necessary to create many different Layout for the Activity. For example, when the device screen is placed vertically (high height), you may need to make the button portrait layout. When the screen is placed horizontally (larger width), the button should be horizontally aligned. To change the layout according to the screen orientation, you can define two layouts and name the layout directory with the appropriate identifiers. This allows the system to automatically select the appropriate Layout according to the current device orientation.

For more information about the various resources available to an application and how to create alternative resources for various device configurations, see providing resources.

Follow-up reading:
Intent and Intent Filters
For content that uses Intent APIs to activate application components such as Activity and services, make components available to other applications, and so on.
Activity
For more information about creating Activity instances of classes. Activity gives a window in the application that contains a user interface.
Provide resources
An
Android application architecture for resource and source-code separation, including content such as alternative resources for a device configuration.
may also be interested in:
Device compatibility
Information about running Android on various models of devices, as well as optimizing programs or restricting functionality for each device.
System permissions
Android restricts application access to certain APIs through a set of authorization systems that allow the user to authorize the application to use these APIs.

Android Development-API Guide-Application Development Basics

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.