Android Application Basics

Source: Internet
Author: User
Tags sqlite database least privilege

Android applications are written in the Java programming language. The Android SDK tool compiles your code-along with any data and resource files-into a apk:android package, which is an archive file with an. apk suffix. An APK file contains all the content of an Android app, which is a file that is used by Android-based devices to install the app.


After installing to the device, each Android app runs in its own security sandbox:

The 1.Android operating system is a multi-user Linux system, where each application is a different user;
2. By default, each app is assigned a unique Linux user ID (the ID is only used by the system and is not known by the app). The system sets permissions for all files in the app so that only the user ID assigned to the app can access the files;
3. each process has its own virtual machine (VM), so the application code is run in an environment that is isolated from other applications;
4. By default, each app runs within its own Linux process . Android starts the process when it needs to execute any application components, and then shuts down the process when it is no longer needed or when the system must recover memory for other apps.


This is the way Android systems can implement the principle of least privilege. That is, by default, each app has access only to the components that it needs to perform its work, not to other components. This creates a very secure environment in which apps cannot access the parts of the system that they do not have permissions on.


However, apps can still share data with other apps and access system services in some ways:


1. You can schedule two apps to share the same Linux user ID, in which case they can access each other's files. To conserve system resources, you can schedule an app with the same user ID to run in the same Linux process and share the same VM (the app must also be signed with the same certificate );

2. The app can request access to device data (such as the user's contacts, SMS, Removable storage device [SD card], camera, Bluetooth, etc.). All app permissions must be granted by the user at installation time .


The above covers the basics of how Android apps exist in the system. The remainder of this section will introduce you to the following:

1. Define the core framework components of the application.
2. A manifest file that you use to declare components and apply the required device functionality.
3. Detach from the app code and allow your app to configure the resources appropriate to optimize its behavior for a variety of device configurations.


Application Components

Application components are the basic building blocks for Android apps. Each component is a different point from which the system can enter your application. Not all components are the actual entry points for the user, and some components depend on each other, but each component exists as a separate entity and plays a specific role-each component is a unique building block that helps define the overall behavior of the app.


There are four different types of application components. Each type serves a different purpose and has different lifetimes that define how the components are created and destroyed.


Here are the four types of application components:


Activity:

activity represents a single screen with a user interface. For example, an e-mail app might have an activity that displays a list of new e-mail messages, an activity for composing an e-mail message, and an activity for reading e-mail. Although these activity forms a cohesive user experience in e-mail applications through collaboration, each activity is independent of other activity. As a result, other apps can start any of these Activity (if the email app allows it). For example, a camera app can start an Activity within an email app that is used to compose new e-mail messages so that users share pictures. Activity is implemented as a subclass of activity.


Services (Service):

A service is a component that runs in the background to perform long-running operations or to execute a job for a remote process . The service does not provide a user interface. For example, when a user is in another app, the service may play music in the background or get data over the network, but it does not block the user from interacting with the Activity. Other components, such as Activity, can start a service, let it run, or bind it to interact with it. Services are implemented as subclasses of the service.


ContentProvider (content Provider):

The content provider manages a set of shared app data. you can store data on the file system, the SQLite database, the Web, or any other persistent storage location that your app can access. Other apps can query the data through the content provider, or even modify the data if allowed by the content provider. For example, an Android system can provide content providers that manage user contact information. Therefore, any app with the appropriate permissions can query a portion of the content provider , such as Contactscontract.data, to read and write information about a particular person.


content providers also apply to read and write private data that your app does not share. For example, the Notepad sample app uses a content provider to save notes.

The content provider is implemented as a subclass of ContentProvider and must implement a set of standard APIs that enable other applications to perform transactions.



Broadcast Receivers (BROADCASTRECEIVER):

A broadcast receiver is a component that responds to system-wide broadcast notifications. Many broadcasts are initiated by the system-for example, the notification screen is turned off, the battery is low, or a photo has been taken for broadcast. Apps can also initiate broadcasts-for example, notifying other apps that some data has been downloaded to the device and available for use. Although the broadcast receivers do not display the user interface, they can create status bar notifications that alert users when a broadcast event occurs. But the more common use of broadcast receivers is simply as a "channel" to other components designed to perform a very small amount of work . For example, it might initiate a service based on an event to perform a task.


The broadcast receiver is implemented as a subclass of the Broadcastreceiver, and each broadcast is passed as a Intent object.

The unique thing about Android system design is that any application can launch components from other applications . For example, if you want a user to take a photo using the device's camera, there is a good chance that another app can do it, and your app can take advantage of the app instead of developing an Activity to take photos from the line. You don't need to integrate or even link to the code of the camera app, but you just start the Activity in the camera app where you take the photo. When you finish shooting, the system will even return the photos to your app for you to use. To the user, it's as if the camera is really part of your application.

When a component is started by the system, the process of the app is started (if it is not already running) and the classes required by the component are instantiated. For example, if your app launches a photo activity in the camera app, the activity will run in a process that belongs to the camera app, not your app. Therefore, unlike most other systems, Android apps do not have a single entry point (for example, no main () feature).

Because the system runs each app in a separate process and its file permissions restrict access to other apps, your app won't be able to launch components directly from other apps, but Android can. Therefore, to start a component in another app, you must pass a message to the system stating that you want to launch the Intent for a particular component. The system will then start the component for you.


Start Component

Three-activity, service, and broadcast receivers in four component types-start with an asynchronous message named Intent. Intent will bind the components to each other at runtime (you can treat Intent as a messenger to request operations from other components), whether the component belongs to your app or another application.


Intent is created using the Intent object, which defines the message that is used to start a particular component or a specific type of component-intent can be either explicit or implicit.


For Activity and services, Intent defines the action to be performed (for example, "View" or "send" a content), and you can specify the URI of the data to perform the action (and the information that the component being started might need to know). For example, Intent communicates a request to start an Activity that displays an image or opens a Web page. In some cases, you can initiate activity to receive results, in which case the activity will also return results in Intent (for example, you can issue a Intent that lets the user pick a contact and return it to you-return Intent including the U that points to the selected contact RI).


For a broadcast receiver, Intent only defines the notification to be broadcast (for example, a broadcast that indicates that the device is low on battery power only includes a known action string indicating "low battery").


Intent does not start another component type-the content provider, which is started when it becomes the Contentresolver request target. The content resolver handles all direct transactions through the content provider, making it possible for a component that executes a transaction through a provider to invoke a method on a Contentresolver object instead of performing a transaction. This leaves an abstraction layer between the content provider and the component that requested the information (to ensure security).


Each type of component has a different startup method:

1. You can start the activity (or schedule a new task for it) by passing the Intent to startactivity () or Startactivityforresult ()(when you want the activity to return the results);
2. You can start the service by passing Intent to StartService () (or release new instructions to the service in execution). Or you can bind to the service by passing the Intent to Bindservice () ;
3. You can initiate a broadcast by passing the Intent to sendbroadcast (), Sendorderedbroadcast (), or sendstickybroadcast ( );
4. You can execute a query on the content provider by calling query () on the contentresolver.


manifest file

Before the Android system launches the application component, the system must confirm that the component exists by reading the app's Androidmanifest.xml file (the "manifest" file). Your app must declare all its components in this file, which must be in the root directory of the app project directory.


In addition to declaring the components that are applied, the manifest file has many other functions, such as:


1. Determine any user rights that your app requires, such as Internet access or read access to a user's contacts

2. According to the API used by the app, declare the minimum API level required by the app
3. Declare the hardware and software features that your app uses or needs, such as cameras, Bluetooth services, or multi-touch screens
4. App needs to link API library (except Android framework API), such as Google Maps API Library
5. Other functions


declaring Components

The main task of the manifest file is to inform the system about the application components. For example, a manifest file can declare an Activity like this:

<span style= "FONT-SIZE:14PX;" ><?xml version= "1.0" encoding= "Utf-8" ><manifest ... >    <application android:icon= "@drawable/ App_icon.png "... >        <activity android:name=" com.example.project.ExampleActivity "android:label="                  @ String/example_label "... > </activity> ...    </application></manifest></span>

in the <application> element, the Android:icon property points to the resource that identifies the icon for the app.


In the <activity> element, the Android:name property specifies the fully qualified class name of the activity subclass, and the Android:label property specifies a string that is used as the user visible label for the activity.


You must declare all application components in the following ways:

<activity> Elements of 1.Activity
2. <service> Elements of the service
3. <receiver> Elements of broadcast receivers
4. Content provider <provider> elements


Activity, service, and content providers that you include in the source code but are not declared in the manifest file are not visible to the system and therefore never run. However, a broadcast receiver can be declared in a manifest file or dynamically created in code (such as a Broadcastreceiver object) and registered in the system by calling Registerreceiver ().


declaring component Functionality

As described in the starting component above, you can use Intent to start Activity, service, and broadcast sinks. You can do this by explicitly naming the target component (using the Component class name) in Intent. However, the true strength of Intent lies in the implicit Intent concept. Implicit Intent is nothing more than a description of the type of operation to be performed (optionally, the data that describes the action you want to perform), allowing the system to find the component that can perform the operation on the device and start the component. If more than one component can perform the action described by Intent, the user chooses which component to use.


The system determines which components can respond to Intent by comparing the received Intent with the Intent filter provided in the manifest file for other apps on the device.


When you declare an activity in your app's manifest file, you can optionally join the Intent filter that declares the activity feature to respond to Intent from other apps.
You can use the &lt; Intent-filter&gt; The Intent element is added as a child of the component declaration element to declare a filter for your component.


For example, if you develop an e-mail application that contains an Activity for composing a new e-mail message, you can declare a Intent filter in response to the "send" Intent (to send a new e-mail message) as follows:

<span style= "FONT-SIZE:14PX;" ><manifest ... > ...    <application >        <activity android:name= "com.example.project.ComposeEmailActivity" >            < intent-filter>                <action android:name= "Android.intent.action.SEND"/>                <data android:type= "*/*"/ >                <category android:name= "Android.intent.category.DEFAULT"/>            </intent-filter>        </ Activity>    </application></manifest></span>

Then, if another app creates a Intent that contains the Action_send action and passes it to startactivity (), your Activity may be started so that the user can draft and send the e-mail.


declaring application Requirements

Android-based devices are diverse and not all devices offer the same features and functionality. To prevent your app from being installed on a setup that lacks the features required by your app, you must explicitly define a profile for the type of device your app supports by declaring the device and software requirements in the manifest file. Most of these statements are for informational purposes only and are not read by the system, but external services such as Google Play read them to provide users with filtering capabilities when they search for apps on their devices.


For example, if your app requires a camera and uses the APIs introduced in Android 2.1 (API Level 7), you should declare the information as required in the manifest file as follows:

<span style= "FONT-SIZE:14PX;" ><manifest >    <uses-feature android:name= "Android.hardware.camera.any"                  android:required= " True "/>    <uses-sdk android:minsdkversion=" 7 "android:targetsdkversion="/>    ... </manifest ></span>

now, devices without a camera and Android version less than 2.1 will not be able to install your app from Google Play.


However, you can also claim that your app uses the camera, but it does not require you to use it. In this case, your app must set the Required property to "false", and at run time check whether the device has a camera, and then disable any camera features as needed.


Application Resources

Android apps are not just code-it also requires resources that are detached from the source code, like, audio files, and any content that is relevant to the visual presentation of the app. For example, you should define animations, menus, styles, colors, and layouts for the Activity user interface through an XML file. Using application resources allows you to easily update the various features of your app without modifying your code, and allows you to optimize your app for a variety of device configurations, such as different languages and screen sizes, by providing an alternate set of resources.


For each resource included in your Android project, theSDK Builder defines a unique integer IDthat you can use to reference resources in the application code or other resources defined in the XML. For example, if your app contains an image file named Logo.png (saved in the res/drawable/directory), the SDK tool generates a resource ID named R.drawable.logo that you can use to reference the image and insert it into your user interface.


One of the most important advantages of providing resources that are separate from source code is that you can provide alternate resources that are configured for different devices. For example, by defining UI strings in XML, you can translate strings into other languages and save those strings in separate files. The Android system then applies the appropriate language string to your UI based on the language qualifier appended to the resource directory name (such as appending res/values-fr/to the French string value) and the user's language settings.


Android supports many different alternate resource qualifiers . Qualifiers are short strings that are added to the resource directory name to define the device configuration that these resources apply to. For example, you should often create different layouts for your Activity based on the screen orientation and size of your device. For example, when the device screen is portrait (long), you might want a layout that arranges the buttons vertically, but when the screen is landscape (wide), the buttons should be arranged horizontally. To change the layout by direction, you can define two different layouts, and then apply the corresponding qualifier to the catalog name for each layout. The corresponding layout is then automatically applied according to the current device orientation.


This article is from Google Android Developer



Android Application Basics

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.