Você está na página 1de 11

Android Apps Programming

The Android Project

An Android project is organized similar to other Java projects, with a few important
exceptions. The Android SDK automatically generates certain features specific to an
Android project.

Folder, File & Description

/src
This contains the Java source files for the project. By default, it includes a
MainActivity.javasource file having an activity class that runs when app is launched
using the app icon.

/gen
This directory contains files automatically generated by Android SDK.

The R.java file


It is an auto-generated index that assigns unique variables to all the resources
in the app. It contains references to all resources (layouts, images, etc.). Every
time we add a new resource it is automatically added to this file, assigning a
unique identifier to the resource. The R.java file acts as a master index for the
resources. We should not modify this file.

BuildConfig.java file
It contains settings for build configurations.

/bin
This folder contains the Android package files .apk built by the ADT during the
build process and everything else needed to run an Android application.

/raw
An application can include raw files as resources. Raw files in application might
use include audio files, video files, and any other file formats you might need. All
raw resource files should be included in this folder. To access a raw file resource
programmatically from within your Activity class, simply use the
openRawResource() method of the Resources class, with the resource ID, which is
R.raw.filename to open such raw files.

Example:
InputStream iFile = getResources().openRawResource(R.raw.file1);

/assets
Any files included in this directory are included as binary resources, along with the
application installation package, and are not compiled into the application.
Uncompiled files, called application assets, are not accessible through the
getResources() method. Instead, you must use AssetManager to access files
included in the /assets directory.

Example:

InputStream iFile = assetManager.open(filename);

/res
It contains all resources in various subdirectories. Application resources include
animations, drawable graphics, layout files, data-like strings and numbers, and raw
files.

Lecture 4 The Android Project Page 1


Android Apps Programming

Directory Resource Type

/drawable
Image files like .png, .jpg, .gif or XML files that are compiled into bitmaps, state
lists, shapes, animation drawables store graphics and drawable resource files
for different screen densities and resolutions.

/drawable-ldpi
Will hold images for low-density screens (36x36).

/drawable-hdpi
Will hold images for high-density screens (48x48).

/drawable-mdpi
Will hold images for medium-density screens (72x72).

/layout
This subdirectory stores user interface layout files.

/values
This subdirectory organizes the various types of resources, such as text strings,
color values, and other primitive types. Here are some filename conventions for
resources we can create in this directory:

arrays.xml for resource arrays.


integers.xml for resource integers
bools.xml for resource boolean
colors.xml for color values (#RGB, #ARGB, #RRGGBB, #AARRGGBB)
dimens.xml for dimension values
strings.xml for string values
styles.xml to define styles objects
themes.xml to define theme values

/menu
XML files that define application menus, such as an Options Menu, Context
Menu, or Sub Menu.

/xml
Arbitrary XML files that can be read at runtime by calling Resources.getXML().
We can save various configuration files here which will be used at run time.

Configuration files
The app now has Java code, XML resources, and binary assets that define it.
Configuration files are the glue that holds all of it (Java code, XML resources, and
binary assets) together. Everything from the title of the app on the Android home
screen, to the different screens in the app are defined in these configuration files.
AndroidManifest.xml
It is located in the root directory of the project. This is the manifest file which
describes the fundamental characteristics of the app and defines each of its
components. It is where we specify the app name, all activities, permissions, and
device targeting.

The Android Manifest

Lecture 4 The Android Project Page 2


Android Apps Programming

This file works as an interface between Android OS and the application, so if we


do not declare the component in this file, then it will not be considered by the OS. The
Android system uses the information in this file to do the following:
Install and upgrade the application package
Display application details to users
Launch application activities
Manage application permissions
Handle a number of other advanced application configurations, including
acting as a service provider or content provider

We can edit the Android manifest file by using the Eclipse manifest file resource
editor or by manually editing the XML. The Eclipse manifest file resource editor
organizes the manifest information into categories presented on five tabs:

Manifest
The Manifest tab contains package-wide settings, including the package name,
version information, and minimum Android SDK version information. We can also
set any hardware configuration requirements here.

Application
The Application tab contains application-wide settings, including the application
label and icon, as well as information about application components, such as
activities, intent filters, and other application functionality, including configuration
for service and content provider implementations.

Permissions
The Permissions tab contains any permission rules required by the application.
This tab can also be used to enforce custom permissions created for the
application.

Instrumentation
The Instrumentation tab is used to declare any instrumentation classes for
monitoring the application.

AndroidManifest.xml
Using the AndroidManifest.xml Tab to edit the Android manifest file which is a
specially formatted XML file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=http://schemas.android.com/apk/res/android
package="org.anddev.android.hello_android">
<application android:icon="@drawable/icon">
<activity android:name=".Hello_Android"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Manifest Configuration file for the application.
Naming Android Packages
Naming an Application
Versioning an Application
Setting the Version Name
Setting the Version Code
Lecture 4 The Android Project Page 3
Android Apps Programming

Setting the Minimum Android API Version


Providing an Icon for an Application
Providing an Application Description
Setting Debug Information for an Application
Setting Other Application Attributes

<manifest>
This is the root node of each AndroidManifest.xml. It contains the package-
attribute, which points to any package in out Activity. Other Activities-path will base
relative to its value. It specifies a namespace called android, which is used
throughout the rest of the manifest file. The package attribute defines the root
package name of our application. Inside the <manifest> element, we then define
the applications components, permissions, hardware profiles, and supported
Android versions.

Attributes of <activity> element:

name
This specifies the name of the activitys class relative to the package attribute we
specified in the <manifest> element

label
This label is displayed in the title bar of the activity (if it has one).The label will also
be used as the text displayed in the application launcher if the activity we define is
an entry point to our application. If we dont specify it, the label from the
<application> element will be used instead
.
screenOrientation
This attribute specifies the orientation that the activity will use (portrait /
landscape). Both configurations will force the orientation of the activity to stay the
same over the activitys life cycle, no matter how the device is actually oriented. If
we leave out this attribute, then the activity will use the current orientation of the
device, usually based on accelerometer data. This also means that whenever the
device orientation changes, the activity will be destroyed and restartedsomething
thats undesirable in the case of a game. We usually fix the orientation of our
games activity either to landscape or portrait mode.

configChanges
Reorienting the device or sliding out the keyboard is considered a configuration
change. In the case of such a change, Android will destroy and restart our
application to accommodate the change. Thats not desirable in the case of a
game. The configChanges attribute of the <activity> element comes to the rescue.
It allows us to specify which configuration changes we want to handle ourselves,
without destroying and recreating our activity. Multiple configuration changes can
be specified by using the | character to concatenate them. In the preceding case,
we handle the changes keyboard, keyboardHidden, and orientation ourselves.

<intent-filter>
Declares what kind of Intents a component supports. In addition to the various
kinds of values that can be specified under this element, attributes can be given
here to supply a unique label, icon, and other information for the action being
described.

<action>
Lecture 4 The Android Project Page 4
Android Apps Programming

An action-type that the component supports. Typical values for action are MAIN (the
front door of the application), VIEW, PICK, EDIT, etc.

Example: <action android:name="android.intent.action.MAIN" />

<category>
A category-type that the component supports.

Example: <category android:name="android.intent.category.LAUNCHER" />

<uses-sdk>
It specifies the minimum version supported by our application and the target
version of our application.

<uses-sdk android:minSdkVersion="3" android:targetSdkVersion="13"/>

<permission>
Declares a security permission that can be used to restrict which applications can
access components or features in the (or another) package.

<uses-permission>
Describes a security permission, which the package must be granted in order for it
to operate correctly. The permissions get granted by the user during installation of
the application.

Syntax: <uses-permission android:name="string"/>

Example:
<uses-permission android:name=android.permission.READ_CONTACTS />

Here are a few permission names that might come in handy:


android.permission.RECORD_AUDIO
android.permission.READ_CONTACTS
android.permission.WRITE_CONTACTS
android.permission.INTERNET
android.permission.MODIFY_AUDIO_SETTINGS
android.permission.ACCESS_NETWORK_STATE
android.permission.CHANGE_NETWORK_STATE
android.permission.ACCESS_WIFI_STATE
android.permission.CHANGE_WIFI_STATE
android.permission.BATTERY_STATS
android.permission.WRITE_EXTERNAL_STORAGE
android.permission.WAKE_LOCK
android.permission.ACCESS_COARSE_LOCATION
android.permission.NFC

For a full list of permissions see


http://developer.android.com/reference/android/Manifest.permission.html

<receiver>
An IntentReceiver allows an application to be told about changes to data or actions
that happen, even if it is not currently running. As with the activity tag, we can
optionally include <intent-filter> elements that the receiver supports or <meta-
data> values, just all the same as with <activity>.

Example: <receiver android:name=".SMSReceiver">

Lecture 4 The Android Project Page 5


Android Apps Programming

<service>
A Service is a component that can run in the background for an arbitrary amount of
time. As with the activity tag, we can optionally include one or more <intent-filter>
elements that the service supports or <meta-data> values.
<provider>
A ContentProvider is a component that manages persistent data and publishes it
for access by other applications. We can also optionally attach one or more <meta-
data> values.

<uses-feature>
With the <uses-feature> element, an application can specify which hardware
features it needs.

A <uses-feature> element has the following attributes:

<uses-feature android:name="string"
android:required=["true" | "false"]
android:glEsVersion="integer" />

The name attribute specifies the feature itself. The required attribute tells the filter
whether we really need the feature under all circumstances or if its just nice to
have. The last attribute is optional and only used when a specific OpenGL ES
version is required.

Example:

<uses-feature android:name="android.hardware.touchscreen.multitouch"
android:required="true"/>

Let's say we want to have optional support of USB peripherals for our game so that
the device can be a USB host and have controllers or other peripherals connected
to it. The correct way of handling this is to add:

<uses-feature android:name="android.hardware.usb.host"
android:required="false"/>

<supports-screens>
This allow us to declare the screen sizes and densities where app can run on.
Ideally, the app will work on all screens.

<uses-configuration>
This let us declare explicit support for an input configuration type on a device, such
as a hard keyboard, qwerty-specific keyboard, touchscreen, or maybe trackball
navigation input.

<uses-library>
This allows for the declaration that a third-party library, on which app is dependent,
be present on the device.

Application Components
Application components are the essential building blocks of an Android
application. These components are loosely coupled by the application manifest file
AndroidManifest.xml that describes each component of the application and how they
interact. There are four main components that can be used within an Android
application:

Lecture 4 The Android Project Page 6


Android Apps Programming

Activities
They dictate the UI and handle the user interaction to the smartphone screen. An
activity represents a single screen with a user interface. An activity is implemented
as a subclass of Activity class as follows:
public class MainActivity extends Activity {

}

Services
They handle background processing associated with an application. It is a code
that is long-lived and runs without UI. A service is implemented as a subclass of
Service class as follows:

public class MyService extends Service {



}

Broadcast Receivers
They handle communication between Android OS and applications. Broadcast
Receivers simply respond to broadcast messages from other applications or from
the system. It is implemented as a subclass of BroadcastReceiver class and each
message is broadcasted as an Intent object.

public class MyReceiver extends BroadcastReceiver {



}

Content Providers
They handle data and database management issues. A content provider
component supplies data from one application to others on request. The data may
be stored in the file system, the database or somewhere else entirely. It is
implemented as a subclass of ContentProvider class and must implement a
standard set of APIs that enable other applications to perform transactions.

public class MyContentProvider extends ContentProvider {



}

Lecture 4 The Android Project Page 7


Android Apps Programming

Additional Components
Fragments
Represents a behavior or a portion of user interface in an Activity.

Views
UI elements that are drawn onscreen including buttons, lists forms etc.

Layouts
View hierarchies that control screen format and appearance of the views.

Intents
Messages wiring components together.

Resources
External elements, such as strings, constants and drawables pictures.

Custom Components

The simplest way to create your custom component is to extend an existing


widget class or subclass with your own class if you want to extend the functionality of
existing widget

public class CustomView extends TextView {


public CustomView(Context context) {
super(context);
//--- Additional custom code --
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
//--- Additional custom code
}
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);

Lecture 4 The Android Project Page 8


Android Apps Programming

//--- Additional custom code --


}
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomView customView = new CustomView(this);
setContentView(customView);
}

Using the Application Context


The application context is the central location for all top-level application
functionality. It is used to access settings and resources shared across multiple activity
instances. Retrieve the application context for the current process by using the
getApplicationContext() method, like this:

Context context = getApplicationContext();

Because the Activity class is derived from the Context class, use this object
instead of retrieving the application context explicitly when writing code inside Activity
class. After retrieving a valid application context, use it to access application-wide
features and services.

Application Resources
Application resources are defined by the developer within the Android project
files and are specific to the application. All application resources are stored within the
/res directory. When resources are handled during the build process, their name
dictates their variable name. Each time a resource file is copied into the appropriate
directory within Eclipse, the R.java class file is recompiled to incorporate the changes.
Application resources can be accessed programmatically using the generated class file
(R.java). It can also be referenced in other application resources. To reference a
resource from within Activity class, retrieve the applications Resources object using the
getResources() method and make the appropriate method call based on the type of
resource need to retrieve. Application resources are not shared with the rest of the
Android System.

Example: String title = getResources().getString(R.string.strTitle);

System Resources
Applications can access the Android system resources in addition to their private
resources. This standardized set of resources is shared across all applications,
providing users with common styles and other useful templates, as well as commonly
used string and colors. System resources are common resources defined by the
Android platform and accessible to all applications through the Android SDK. System
resources are stored within the android.R package. There are
Classes for each major resource type. To retrieve a system resource, use the static
method of the Resources class called getSystem() to retrieve the global system
Resource object.

Example: String strTnx = Resources.getSystem().getString(android.R.string.bye);

To reference an application and/or system from another compiled resource:

Lecture 4 The Android Project Page 9


Android Apps Programming

@ [ resource type ] / [ resource name ]

Example: @string/strTitle

Working with Simple Resource Values


Simple resources should be defined in XML files under the /res/values project
directory. These resource files use special XML tags that represent name/value pairs.

String Resources

Example: <resources>
<string name = my_title>Android App
Programming</string>
</resources>

Color resources

Example: <resources>
<color name = my_color>#ABCDEF</color>
</resources>

Color Format
#RGB 12-bit color
#ARGB 12-bit color with alpha
#RRGGBB 24-bit color
#AARRGGBB 24-bit color with alpha

Dimension Resources
These are helpful for font sizes, image sizes, and other physical-relative
measurements. Each dimension resource value must end with a unit of
measurement.

Example: <resources>
<dimen name = my_dimen>100px</string>
</resources>

Dimension Unit Measurements Supported in Android


Pixels (px) Actual screen pixels
Inches (in)Physical measurement in English unit
Millimeters (mm)Physical measurement in Metric Unit
Points (pt) Common font measurement
Density-independent pixels (dp) Pixels relative to 160dpi
Scale-independent pixels (sp) Best for scalable font display

To retrieve a dimension resource, use the getDimension() method

Example: float aDimen = getResource().getDimension(R.dimen.my_dimen);

Drawable Resources
Drawable resources can be drag and drop into the /res/drawable project directory.
The system picks the correct version of the resource based on the device on which
the application is running. All versions of a specific resource must have the same
name in each of the drawable directories.

Image Formats Supported in Android

Lecture 4 The Android Project Page 10


Android Apps Programming

Portable Network Graphics (.png)


Nine-Patch Stretchable Images (.9.png)
Joint Photographic Experts Group (.jpg)
Graphics Interchange Format (gif)

Image resources are encapsulated in the class BitmapDrawable. To access a


graphic resource file within Activity class, use the getDrawable() method.

Example: BitmapDrawable bitmap =


(BitmapDrawable)getResources().getDrawable(R.drawable.logo);

Image can be programmatically load, process, and set for a given ImageView
control at runtime.

Example: ImageView iv = (ImageView)findViewById(R.id.logo);

In addition to graphics files, specially formatted XML files can be created to describe
other Drawable subclass such as ShapeDrawable. Use the ShapeDrawable class to
define different shapes.

Lecture 4 The Android Project Page 11

Você também pode gostar