1. Trang chủ
  2. » Công Nghệ Thông Tin

Android studio overview

506 1,5K 1

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 506
Dung lượng 7,58 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Giới thiệu về Android Studio, các chức năng, công cụ, cách vận hành, debug, run...Khởi tạo project với Android Studio, với các example cơ bản.Chú thích các lệnh, phím tắt khi dùng Android StudioCó đường link để tham khảo thêm,...,

Trang 1

Android Studio Overview

In this document

1 Project and File Structure

2 Android Build System

3 Debug and Performance

4 Installation, Setup, and Update Management

5 Other Highlights

See also

1 IntelliJ FAQ on migrating to IntelliJ IDEA

Android Studio is the official IDE for Android application development, based on IntelliJ IDEA On top of the capabilities you expect from IntelliJ, Android Studio offers:

 Flexible Gradle-based build system

 Build variants and multiple apk file generation

 Code templates to help you build common app features

 Rich layout editor with support for drag and drop theme editing

 Lint tools to catch performance, usability, version compatibility, and other problems

 ProGuard and app-signing capabilities

 Built-in support for Google Cloud Platform, making it easy to integrate Google CloudMessaging and App Engine

 And much more

Download Android Studio now

If you're new to Android Studio or the IntelliJ IDEA interface, this page provides an

introduction to some key Android Studio features

For specific Android Studio how-to documentation, see the pages in the Workflow section, such as Managing Projects from Android Studio and Building and Running from Android Studio

Trang 2

Project and File Structure

Android Project View

By default, Android Studio displays your profile files in the Android project view This view

shows a flattened version of your project's structure that provides quick access to the key source files of Android projects and helps you work with the new Gradle-based build system The Android project view:

 Groups the build files for all modules at the top level of the project hierarchy

 Shows the most important source directories at the top level of the module hierarchy

 Groups all the manifest files for each module

 Shows resource files from all Gradle source sets

 Groups resource files for different locales, orientations, and screen types in a single group per resource type

Figure 1 Show the Android project view.

Trang 3

Figure 2 Project Build Files.

The Android project view shows all the build files at the top level of the project hierarchy

under Gradle Scripts Each project module appears as a folder at the top level of the project

hierarchy and contains these three elements at the top level:

 java/ - Source files for the module.

 manifests/ - Manifest files for the module.

 res/ - Resource files for the module.

For example, Android project view groups all the instances of the ic_launcher.png resource

for different screen densities under the same element

Note: The project structure on disk differs from this flattened representation To switch to

back the segregated project view, select Project from the Project

New Project and Directory Structure

When you use the Project view of a new project in Android Studio, you should notice that the

project structure appears different than you may be used to in Eclipse Each instance of Android Studio contains a project with one or more application modules Each application module folder contains the complete source sets for that module, including src/main and src/androidTest directories, resources, build file and the Android manifest For the most part, you will need to modify the files under each module's src/main directory for source code updates, the gradle.build file for build specification and the files under

src/androidTest directory for test case creation

Trang 4

Figure 3 Android Studio project structure

For more information, see IntelliJ project organization and Managing Projects

Creating new files

You can quickly add new code and resource files by clicking the appropriate directory in the

Project pane and pressing ALT + INSERT on Windows and Linux or COMMAND + N on Mac Based on the type of directory selected, Android Studio offers to create the appropriate file type

For example, if you select a layout directory, press ALT + INSERT on Windows, and select

Layout resource file, a dialog opens so you can name the file (you can exclude the .xml suffix) and choose a root view element The editor then switches to the layout design editor

so you can begin designing your layout

Android Build System

Android Build System

The Android build system is the toolkit you use to build, test, run and package your apps This build system replaces the Ant system used with Eclipse ADT It can run as an integrated tool from the Android Studio menu and independently from the command line You can use the features of the build system to:

 Customize, configure, and extend the build process

 Create multiple APKs for your app with different features using the same project and modules

 Reuse code and resources across source sets

The flexibility of the Android build system enables you to achieve all of this without

modifying your app's core source files To build an Android Studio project, see Building and

Trang 5

Running from Android Studio To configure custom build settings in an Android Studio project, see Configuring Gradle Builds.

Application ID for Package Identification

With the Android build system, the applicationId attribute is used to uniquely identify

application packages for publishing The application ID is set in the android section of the

Trang 6

Note: If you have multiple manifests (for exmample, a product flavor specific manifest and a build type manifest), the package name is optional in those manifests If it is specified in those manifests, the package name must be identical to the package name specified in the manifest in the src/main/ folder

For more information about the build files and process, see Build System Overview

Debug and Performance

Android Virtual Device (AVD) Manager

AVD Manager has updated screens with links to help you select the most popular device configurations, screen sizes and resolutions for your app previews.

Click the Android Virtual Device Manager in the toolbar to open it and create new virtual devices for running your app in the emulator.

The AVD Manager comes with emulators for Nexus 6 and Nexus 9 devices and also supports creating custom Android device skins based on specific emulator properties and assigning those skins to hardware profiles Android Studio installs the Intel® x86 Hardware Accelerated Execution Manager (HAXM) emulator accelerator and creates a default emulator for quick app prototyping.

For more information, see Managing AVDs

Memory Monitor

Android Studio provides a memory monitor view so you can more easily monitor your app's memory usage to find deallocated objects, locate memory leaks and track the amount of memory the connected device is using With your app running on a device or emulator, click the Memory Monitor tab in the lower right corner to launch the memory monitor

Trang 7

Figure 4 Memory Monitor

New Lint inspections

Lint has several new checks to ensure:

Cipher.getInstance() is used with safe values

In custom Views, the associated declare-styleable for the custom view uses the same base name as the class name.

Security check for fragment injection.

Where ever property assignment no longer works as expected.

Gradle plugin version is compatible with the SDK.

Right to left validation

Required API version

many others

Hovering over a Lint error displays the full issue explanation inline for easy error resolution There is also a helpful hyperlink at the end of the error message for

additional error information.

With Android Studio, you can run Lint for a specific build variant, or for all build

variants You can configure Lint by adding a lintOptions property to the Android

settings in the build.gradle file

For more information, see Improving Your Code with Lint

Dynamic layout preview

Android Studio allows you to work with layouts in both a Design View

Trang 8

Figure 5 Hello World App with Design View

and a Text View

Figure 6 Hello World App with Text View

Easily select and preview layout changes for different device images, display densities,

UI modes, locales, and Android versions (multi-API version rendering)

Trang 9

Figure 7 API Version Rendering

From the Design View, you can drag and drop elements from the Palette to the Preview

or Component Tree The Text View allows you to directly edit the XML settings, while previewing the device display

Log messages

When you build and run your app with Android Studio, you can view adb and device log messages (logcat) in the DDMS pane by clicking Android at the bottom of the

window.

If you want to debug your app with the Android Debug Monitor, you can launch it by

clicking Monitor in the toolbar The Debug Monitor is where you can find the complete set of DDMS tools for profiling your app, controlling device behaviors, and more It also includes the Hierarchy Viewer tools to help optimize your layouts

Installation, Setup, and Update Management

Android Studio installation and setup wizards

An updated installation and setup wizards walk you through a step-by-step installation and setup process as the wizard checks for system requirements, such as the Java Development Kit (JDK) and available RAM, and then prompts for optional installation options, such as the Intel® HAXM emulator accelerator

Trang 10

An updated setup wizard walks you through the setup processes as the wizard updates your system image and emulation requirements, such GPU, and then creates an optimized default Android Virtual Device (AVD) based on Android 5 (Lollipop) for speedy and reliable

emulation

Figure 8 Setup Wizard

Expanded template and form factor support

Android Studio supports new templates for Google Services and expands the availabe device types

Android Wear and TV support

For easy cross-platform development, the Project Wizard provides new templates for creatingyour apps for Android Wear and TV

Trang 11

Figure 9 New Form Factors

During app creation, the Project Wizard also displays an API Level dialog to help you choose

the best minSdkVersion for your project.

Google App Engine integration (Google Cloud Platform/Messaging)

Quick cloud integration Using Google App Engine to connect to the Google cloud and create

a cloud end-point is as easy as selecting File > New Module > App Engine Java Servlet Module and specifying the module, package, and client names

Trang 12

Figure 10 Setup Wizard

Update channels

Android Studio provides four update channels to keep Android Studio up-to-date based on your code-level preference:

Canary channel: Canary builds provide bleeding edge releases, updated

about weekly While these builds do get tested, they are still subject to bugs, as we want people to see what's new as soon as possible This is not recommended for production.

Dev channel: Dev builds are hand-picked older canary builds that

survived the test of time They are updated roughly bi-weekly or monthly.

Beta channel: Beta builds are used for beta-quality releases before a

production release.

Stable channel: Used for stable, production-ready versions.

By default, Android Studio uses the Stable channel Use File > Settings > Updates to change

your channel setting

Other Highlights

Translation Editor

Trang 13

Multi-language support is enhanced with the Translation Editor plugin so you can easily add locales to the app's translation file Color codes indicate whether a locale is complete or still missing string translations Also, you can use the plugin to export your strings to the Google Play Developer Console for translation, then download and import your translations back intoyour project

To access the Translation Editor, open a strings.xml file and click the Open Editor link

Figure 11 Translation Editor

Editor support for the latest Android APIs

Android Studio supports the new Material Design themes, widgets, and graphics, such as shadow layers and API version rendering (showing the layout across different UI versions) Also, the new drawable XML tags and attributes, such as <ripple> and <animated-selector>, are supported

Easy access to Android code samples on GitHub

Clicking Import Samples from the File menu or Welcome page provides seamless access to

Google code samples on GitHub

Trang 14

Figure 12 Code Sample Access

Except as noted, this content is licensed under Creative Commons Attribution 2.5 For details and restrictions, see the Content License

About Android | Legal | Support

Trang 15

Android Studio Tips and Tricks

1 Download Android Studio

2 IntelliJ IDEA Android Tutorials

3 IntelliJ FAQ on migrating to IntelliJ IDEA

If you're unfamiliar with using Android Studio and the IntelliJ IDEA interface, this page provides some tips to help you get started with some of the most common tasks and

With smart rendering, Android Studio displays links for quick fixes to rendering errors For

example, if you add a button to the layout without specifying the width and height atttributes, Android Studio displays the rendering message Automatically add all missing attributs

Clicking the message adds the missing attributes to the layout

Bitmap rendering in the debugger

While debugging, you can now right-click on bitmap variables in your app and invoke View Bitmap This fetches the associated data from the debugged process and renders the bitmap in

the debugger

Trang 16

Figure 1 Bitmap Rendering

Output window message filtering

When checking build results, you can filter messages by message type to quickly locate

messages of interest

Figure 2 Filter Build Messages

Hierarchical parent setting

Trang 17

The activity parent can now be set in the Activity Wizard when creating a new activity

Setting a hierarchal parent sets the Up button to automatically appear in the app's Action bar

when viewing a child activity, so the Up button no longer needs to be manually specified in

the menu.xml file.

Creating layouts

Android Studio offers an advanced layout editor that allows you to drag-and-drop widgets into your layout and preview your layout while editing the XML

While editing in the Text view, you can preview the layout on devices by opening the

Preview pane available on the right side of the window Within the Preview pane, you can

modify the preview by changing various options at the top of the pane, including the preview device, layout theme, platform version and more To preview the layout on multiple devices

simultaneously, select Preview All Screen Sizes from the device drop-down.

Figure 3 Preview All Screens

You can switch to the graphical editor by clicking Design at the bottom of the window While

editing in the Design view, you can show and hide the widgets available to drag-and-drop by

clicking Palette on the left side of the window Clicking Designer on the right side of the

window reveals a panel with a layout hierarchy and a list of properties for each view in the layout

Trang 18

Working with IntelliJ

This section list just a few of the code editing practices you should consider using when creating Android Studio apps

For complete user documentation for the IntelliJ IDEA interface (upon which Android Studio

is based), refer to the IntelliJ IDEA documentation

External annotations

Specify annotations within the code or from an external annotation file The Android Studio IDE keeps track of the restrictions and validates compliance, for example setting the data type of a string as not null

Alt + Enter key binding

For quick fixes to coding errors, the IntelliJ powered IDE implements the Alt + Enter key

binding to fix errors (missing imports, variable assignments, missing references, etc) when possible, and if not, suggest the most probable solution

Ctrl + D key binding

The Ctrl + D key binding is great for quickly duplicating code lines or fragments Simply

select the desired line or fragment and enter this key binding

Navigate menu

In case you're not familiar with an API class, file or symbol, the Navigate menu lets you jump

directly to the class of a method or field name without having to search through individual classes

Injecting languages

With language injection, the Android Studio IDE allows you to work with islands of different languages embedded in the source code This extends the syntax, error highlighting and coding assistance to the embedded language This can be especially useful for checking regular expression values inline, and validating XML and SQL statments

Trang 19

Code folding

This allows you to selectively hide and display sections of the code for readability For example, resource expressions or code for a nested class can be folded or hidden in to one line to make the outer class structure easier to read The inner clas can be later expanded for updates

Image and color preview

When referencing images and icons in your code, a preview of the image or icon appears (in actual size at different densities) in the code margin to help you verify the image or icon reference Pressing F1 with the preview image or icon selected displays resource asset details,

such as the dp settings

Quick F1 documentation

You can now inspect theme attributes using View > Quick Documentation (F1), see the

theme inheritance hierarchy, and resolve values for the various attributes

If you invoke View > Quick Documentation (usually bound to F1) on the theme attribute ?

android:textAppearanceLarge, you will see the theme inheritance hierarchy and resolved

values for the various attributes that are pulled in

New Allocation Tracker integration in the Android/DDMS window

You can now inspect theme attributes using View > Quick Documentation F1, see the theme

inheritance hierarchy, and resolved values for the various attributes

Figure 4 Allocation Tracker

Keyboard Commands

The following tables list keyboard shortcuts for common operations

Note: This section lists Android Studio keyboard shortcuts for the default keymap To change

the default keymap on Windows and Linux, go to File > Settings > Keymap To change the default keymap on Mac OS X, go to Android Studio > Preferences > Keymap.

Note: If you're using Mac OS X, update your keymap to use the Mac OS X 10.5+ version

keymaps under Android Studio > Preferences > Keymap.

Table 1 Programming key commands

Trang 20

Action Android Studio Key Command

Command look-up (autocomplete command name) CTRL + SHIFT + A

OPTION + CMD + L (Mac)Show docs for selected API CTRL + Q (Win)F1 (Mac)

Show parameters for selected method CTRL + P

CMD + N (Mac)

Delete line CTRL + Y (Win)CMD + Backspace (Mac)

OPTION + CMD + O (Mac)

Table 2 Project and editor key commands

Build CTRL + F9 (Win)CMD + F9 (Mac)

Build and run SHIFT + F10 (Win)

CTRL + R (Mac)Toggle project visibility ALT + 1 (Win)CMD + 1 (Mac)

Navigate open tabs ALT + left-arrow; ALT + right-arrow (Win)CTRL + left-arrow; CTRL + right-arrow (Mac)

For a complete keymap reference guide, see the IntelliJ IDEA documentation

Except as noted, this content is licensed under Creative Commons Attribution 2.5 For details and restrictions, see the Content License

About Android | Legal | Support

Trang 21

Developer Workflow

To develop apps for Android, you use a set of tools that are included in Android Studio In addition to using the tools from Android Studio, you can also access most of the SDK tools from the command line Developing with Android Studio is the preferred method because it can directly invoke the tools that you need while developing applications

However, you may choose to develop with another IDE or a simple text editor and invoke thetools on the command line or with scripts This is a less streamlined way to develop because you will sometimes have to call command line tools manually, but you will have access to thesame number of features that you would have in Android Studio

Trang 22

Figure 1 The development process for Android applications

App Workflow

The basic steps for developing applications (with or without Android Studio) are shown in figure 1 The development steps encompass four development phases, which include:

Trang 23

Environment Setup

During this phase you install and set up your development environment You also create Android Virtual Devices (AVDs) and connect hardware devices on which you can install your applications

See Managing Virtual Devices and Using Hardware Devices for more information

Project Setup and Development

During this phase you set up and develop your Android Studio project and applicationmodules, which contain all of the source code and resource files for your application For more information, see Create an Android project

Building, Debugging and Testing

During this phase you build your project into a debuggable apk package(s) that you can install and run on the emulator or an Android-powered device Android Studio uses a build system based on Gradle that provides flexibility, customized build

variants, dependency resolution, and much more If you're using another IDE, you canbuild your project using Gradle and install it on a device using adb For more

information, see Build and run your application

Next, with Android Studio you debug your application using the Android Debug Monitor and device log messages (logact) along with the IntelliJ IDEA intelligent coding features You can also use a JDWP-compliant debugger along with the

debugging and logging tools that are provided with the Android SDK For more information see Debug your application with the SDK debugging and logging tools.Last, you test your application using various Android SDK testing tools For more information, see Test your application with the Testing and Instrumentation

framework

Publishing

During this phase you configure and build your application for release and distribute your application to users For more information, see Publishing Overview

Essential command line tools

When developing in IDEs or editors other than Android Studio, be familiar with all of the tools below, because you will have to run them from the command line or script

android

Create and update Android projects and create, move, and delete AVDs

Android Emulator

Run your Android applications on an emulated Android platform

Android Debug Bridge

Trang 24

Interface with your emulator or connected device (install apps, shell the device, issue commands, etc.).

In addition to the above tools that are included with the SDK, you need the following open source and third-party tools:

Jarsigner (or similar signing tool)

To sign your apk file with a private key generated by Keytool Jarsigner is part of the JDK

If you are using Android Studio, tools such as adb and android are automatically called by Android Studio so you don't have to manually invoke these tools You need to be familiar with adb, however, because certain functions are not accessible from Android Studio, such as the adb shell commands You might also need to call Keytool and Jarsigner to sign your applications, but you can set up Android Studio to do this automatically as well

For more information on the tools provided with the Android SDK, see the Tools section of the documentation

Except as noted, this content is licensed under Creative Commons Attribution 2.5 For details and restrictions, see the Content License

About Android | Legal | Support

Trang 25

Managing Virtual Devices

An Android Virtual Device (AVD) is an emulator configuration that lets you model an actual device by defining hardware and software options to be emulated by the Android Emulator

The easiest way to create an AVD is to use the graphical AVD Manager, which you launch

from Eclipse by clicking Window > AVD Manager You can also start the AVD Manager

from the command line by calling the android tool with the avd options, from the

<sdk>/tools/ directory.

You can also create AVDs on the command line by passing the android tool options For more information on how to create AVDs in this manner, see Managing Virtual Devices from the Command Line

An AVD consists of:

 A hardware profile: Defines the hardware features of the virtual device For example, you can define whether the device has a camera, whether it uses a physical QWERTY keyboard or a dialing pad, how much memory it has, and so on

 A mapping to a system image: You can define what version of the Android platform will run on the virtual device You can choose a version of the standard Android platform or the system image packaged with an SDK add-on

 Other options: You can specify the emulator skin you want to use with the AVD, which lets you control the screen dimensions, appearance, and so on You can also specify the emulated SD card to use with the AVD

 A dedicated storage area on your development machine: the device's user data

(installed applications, settings, and so on) and emulated SD card are stored in this area

You can create as many AVDs as you need, based on the types of device you want to model

To thoroughly test your application, you should create an AVD for each general device configuration (for example, different screen sizes and platform versions) with which your application is compatible and test your application on each one

Keep these points in mind when you are selecting a system image target for your AVD:

 The API Level of the target is important, because your application will not be able to run on a system image whose API Level is less than that required by your application,

as specified in the minSdkVersion attribute of the application's manifest file For more information about the relationship between system API Level and application minSdkVersion, see Specifying Minimum System API Version

 You should create at least one AVD that uses a target whose API Level is greater than that required by your application, because it allows you to test the forward-

Trang 26

compatibility of your application Forward-compatibility testing ensures that, when users who have downloaded your application receive a system update, your

application will continue to function normally

 If your application declares a uses-library element in its manifest file, the

application can only run on a system image in which that external library is present Ifyou want to run your application on an emulator, create an AVD that includes the required library Usually, you must create such an AVD using an Add-on component for the AVD's platform (for example, the Google APIs Add-on contains the Google Maps library)

To learn how to manage AVDs using a graphical tool, read Managing AVDs with AVD Manager To learn how to manage AVDs on the command line, read Managing AVDs from the Command Line

Managing AVDs with AVD Manager

In this document

1 Creating an AVD

1 Creating a device definition

2 Hardware options

2 Creating Emulator Skins

The AVD Manager is a tool you can use to create and manage Android virtual devices

(AVDs), which define device configurations for the Android Emulator

To launch the AVD Manager:

In Android Studio, select Tools > Android > AVD Manager, or click the AVD

Manager icon in the toolbar

 Or, use the command line to navigate to your SDK's tools/ directory and execute:

$ android avd

The AVD Manager main screen shows your current virtual devices, as shown in figure 1

Trang 27

Figure 1 The AVD Manager main screen shows your current virtual devices.

Note: If you launch the AVD Manager from the command line, the UI is different than how it

appears in Android Studio, as documented here Most of the same functionality is available, but the command-line version of the AVD Manager is currently not documented

Creating an AVD

You can create as many AVDs as you would like to use with the Android Emulator To effectively test your app, you should create an AVD that models each device type for which you have designed your app to support For instance, you should create an AVD for each API level equal to and higher than the minimum version you've specified in your manifest <uses- sdk> tag

To create an AVD based on an existing device definition:

1 From the main screen (figure 1), click Create Virtual Device.

2 In the Select Hardware window, select a device configuration, such as Nexus 6, then

click Next.

Trang 28

Figure 2 The Select Hardware window.

3 Select the desired system version for the AVD and click Next

4 Verify the configuration settings, then click Finish

If necessary, click Show Advanced Settings to select a custom skin for the hardware

profile and adjust other hardware settings

To launch the AVD in the Android Emulator, click the launch button in the list of AVDs

Creating a device definition

In case the available device definitions do not match the device type you'd like to emulate, you can create a custom device definition for your AVD:

1 From the main screen (figure 1), click Create Virtual Device.

2 To begin you custom device by using an existing device profile as a template, select a

device profile then click Clone Device

Or, to start from scratch, click New Hardware Profile.

3 The following Configure Hardware Profile window (figure 3) allows you to specify various configurations such as the screen size, memory options, input type, and sensors

When you're done configuring the device, click Finish.

Trang 29

Figure 3 The Configure Hardware window when creating a custom device

configuration

4 Your custom device configuration is now available in the list of device definitions

(shown after you click Create Virtual Device) To continue preparing an AVD with

your custom device configuration, select the new configuration and follow the instructions above to create an AVD with an existing device definition (and select your new definition)

Hardware options

If you are creating a new AVD, you can specify the following hardware options for the AVD

to emulate:

Device ram size

The amount of physical RAM on the device, in megabytes Default value is

Touch-screen

support

Whether there is a touch screen or not

on the device Default value is "yes" hw.touchScreenTrackball support Whether there is a trackball on the

device Default value is "yes" hw.trackBallKeyboard support Whether the device has a QWERTY keyboard Default value is "yes". hw.keyboard

DPad support Whether the device has DPad keys Default value is "yes". hw.dPad

GSM modem

support

Whether there is a GSM modem in thedevice Default value is "yes" hw.gsmModemCamera support Whether the device has a camera hw.camera

Trang 30

Default value is "no".

Battery support Whether the device can run on a

battery Default value is "yes" hw.batteryAccelerometer Whether there is an accelerometer in the device Default value is "yes". hw.accelerometer

Audio recording

support

Whether the device can record audio

Default value is "yes" hw.audioInputAudio playback

support

Whether the device can play audio

Default value is "yes" hw.audioOutput

Abstracted LCD

density

Sets the generalized density characteristic used by the AVD's screen Default value is "160"

hw.lcd.density

Creating Emulator Skins

An Android emulator skin is a collection of files that define the visual and control elements of

an emulator display If the skin definitions available in the AVD settings don't meet your needs, you can create your own custom skin definition, then apply it to your AVD from the advanced settings on the Verify Configuration screen

Each emulator skin contains:

 A hardware.ini file

 Layout files for supported orientations (landscape, portrait) and physical configuration

 Image files for display elements, such as background, keys and buttons

To create and use a custom skin:

1 Create a new directory where you will save your skin configuration files

2 Define the visual appearance of the skin in a text file named layout This file defines many characteristics of the skin, such as the size and image assets for specific buttons.For example:

Trang 31

3 Add the bitmap files of the device images in the same directory.

4 Specify additional hardware-specific device configurations an hardware.ini file for the device settings, such as hw.keyboard and hw.lcd.density

5 Archive the files in the skin folder and select the archive file as a custom skin For more detailed information about creating emulator skins, see the Android Emulator Skin File Specification in the tools source code

Managing AVDs from the Command Line

In this document

1 Listing Targets

2 Creating AVDs

1 Customize the device resolution or density

2 Default location of AVD files

3 Setting hardware emulation options

3 Moving an AVD

4 Updating an AVD

Trang 32

5 Deleting an AVD

See also

1 Building and Running from the Command Line

2 Using the Android Emulator

The android tool lets you manage AVDs on the command line For a complete reference of the command line options that you can use, see the reference for the android tool

Listing Targets

To generate a list of system image targets, use this command:

android list targets

The android tool scans the <sdk>/platforms/ and <sdk>/add-ons/ directories looking forvalid system images and then generates the list of targets Here's an example of the command output:

Available Android targets:

Trang 33

Creating AVDs

In addition to creating AVDs with the AVD Manager user interface, you can also create them

by passing in command line arguments to the android tool

Open a terminal window and change to the <sdk>/tools/ directory, if needed

To create each AVD, you issue the command android create avd, with options that specify

a name for the new AVD and the system image you want to run on the emulator when the AVD is invoked You can specify other options on the command line also, such as the

emulated SD card size, the emulator skin, or a custom location for the user data files

Here's the command-line usage for creating an AVD:

android create avd -n <name> -t <targetID> [-<option> <value>]

You can use any name you want for the AVD, but since you are likely to be creating multiple AVDs, you should choose a name that lets you recognize the general characteristics offered

by the AVD The target ID is an integer assigned by the android tool The target ID is not derived from the system image name, version, or API Level, or other attribute, so you need torun the android list targets command to list the target ID of each system image You

should do this before you run the android create avd command See the android tool documentation for more information on the command line options

When you've selected the target you want to use and made a note of its ID, use the android create avd command to create the AVD, supplying the target ID as the -t argument Here's

an example that creates an AVD with name "my_android1.5" and target ID "2" (the standard Android 1.5 system image in the list above):

android create avd -n my_android1.5 -t 2

If the target you selected was a standard Android system image ("Type: platform"), the android tool next asks you whether you want to create a custom hardware profile

Android 1.5 is a basic Android platform.

Do you wish to create a custom hardware profile [no]

If you want to set custom hardware emulation options for the AVD, enter "yes" and set values

as needed If you want to use the default hardware emulation options for the AVD, just press the return key (the default is "no") The android tool creates the AVD with name and system image mapping you requested, with the options you specified For more information, see

Setting Hardware Emulation Options

Note: If you are creating an AVD whose target is an SDK add-on, the android tool does not allow you to set hardware emulation options It assumes that the provider of the add-on has set emulation options appropriately for the device that the add-on is modeling, and so

prevents you from resetting the options

Customize the device resolution or density

Trang 34

When testing your application, we recommend that you test your application in several different AVDs, using different screen configurations (different combinations of size and density) In addition, you should set up the AVDs to run at a physical size that closely

matches an actual device

To set up your AVDs for a specific resolution or density, follow these steps:

1 Use the create avd command to create a new AVD, specifying the skin option with a value that references either a default skin name (such as "WVGA800") or a custom skin resolution (such as 240x432) Here's an example:

android create avd -n <name> -t <targetID> skin WVGA800

2 To specify a custom density for the skin, answer "yes" when asked whether you want

to create a custom hardware profile for the new AVD

3 Continue through the various profile settings until the tool asks you to specify

"Abstracted LCD density" (hw.lcd.density) Enter an appropriate value, such as "120"

for a low-density screen, "160" for a medium density screen, or "240" for a density screen

high-4 Set any other hardware options and complete the AVD creation

In the example above (WVGA medium density), the new AVD will emulate a 5.8" WVGA screen

As an alternative to adjusting the emulator skin configuration, you can use the emulator skin'sdefault density and add the -dpi-device option to the emulator command line when starting the AVD For example:

emulator -avd WVGA800 -scale 96dpi -dpi-device 160

Default location of AVD files

When you create an AVD, the android tool creates a dedicated directory for it on your development computer The directory contains the AVD configuration file, the user data image and SD card image (if available), and any other files associated with the device Note that the directory does not contain a system image — instead, the AVD configuration file contains a mapping to the system image, which it loads when the AVD is launched

The android tool also creates an <AVD_name>.ini file for the AVD at the root of the

.android/avd/ directory on your computer The file specifies the location of the AVD directory and always remains at the root the android directory

By default, the android tool creates the AVD directory inside ~/.android/avd/ (on

Linux/Mac), C:\Documents and Settings\<user>\.android\ on Windows XP, and C:\Users\<user>\.android\ on Windows 7 and Vista If you want to use a custom locationfor the AVD directory, you can do so by using the -p <path> option when you create the AVD:

Trang 35

android create avd -n my_android1.5 -t 2 -p path/to/my/avd

If the android directory is hosted on a network drive, we recommend using the -p option to place the AVD directory in another location The AVD's ini file remains in the android directory on the network drive, regardless of the location of the AVD directory

Setting hardware emulation options

When you are creating a new AVD that uses a standard Android system image ("Type: platform"), the android tool lets you set hardware emulation options for virtual device The table below lists the options available and the default values, as well as the names of

properties that store the emulated hardware options in the AVD's configuration file (the config.ini file in the AVD's local directory)

Table 1 Available hardware profile options for AVDs and the default values

Device ram size The amount of physical RAM on the device, in megabytes Default value is

"96"

hw.ramSize

Touch-screen

support

Whether there is a touch screen or not

on the device Default value is "yes" hw.touchScreen Trackball support Whether there is a trackball on the device Default value is "yes". hw.trackBall

Keyboard support Whether the device has a QWERTY keyboard Default value is "yes". hw.keyboard

DPad support Whether the device has DPad keys

Default value is "yes" hw.dPadGSM modem

support Whether there is a GSM modem in thedevice Default value is "yes" hw.gsmModem

Camera support Whether the device has a camera Default value is "no". hw.camera

Battery support Whether the device can run on a

battery Default value is "yes" hw.batteryAccelerometer Whether there is an accelerometer in the device Default value is "yes". hw.accelerometer

Audio recording

support

Whether the device can record audio

Default value is "yes" hw.audioInputAudio playback

support Whether the device can play audio Default value is "yes" hw.audioOutput

SD Card support Whether the device supports

insertion/removal of virtual SD Cards

hw.sdCard

Trang 36

Default value is "yes".

Cache partition

support

Whether we use a /cache partition on the device Default value is "yes" disk.cachePartitionCache partition size Default value is "66MB" disk.cachePartition.size

Abstracted LCD

density

Sets the generalized density characteristic used by the AVD's screen Default value is "160"

hw.lcd.density Trackball support Whether there is a trackball present hw.trackBall

Moving an AVD

If you want to move or rename an AVD, you can do so using this command:

android move avd -n <name> [-<option> <value>]

Updating an AVD

If, for any reason, the platform/add-on root folder has its name changed (maybe because the user has installed an update of the platform/add-on) then the AVD will not be able to load the system image that it is mapped to In this case, the android list targets command will produce this output:

The following Android Virtual Devices could not be loaded:

Name: foo

Path: <path>/.android/avd/foo.avd

Error: Invalid value in image.sysdir Run 'android update avd -n foo'

To fix this error, use the android update avd command to recompute the path to the systemimages

Deleting an AVD

You can use the android tool to delete an AVD Here is the command usage:

android delete avd -n <name>

When you issue the command, the android tool looks for an AVD matching the specified name deletes the AVD's directory and files

Using the Emulator

In this document

1 Overview

2 Android Virtual Devices and the Emulator

Trang 37

3 Starting and Stopping the Emulator

4 Installing Applications on the Emulator

5 Using Hardware Acceleration

1 Configuring Graphics Acceleration

2 Configuring Virtual Machine Acceleration

6 SD Card Emulation

1 Creating an SD card image

2 Copying files to an SD card image

3 Loading an SD card image

7 Working with Emulator Disk Images

1 Default image files

2 Runtime images: user data and SD card

3 Temporary images

8 Emulator Networking

1 Network Address Space

2 Local Networking Limitations

3 Using Network Redirection

4 Configuring the Emulator's DNS Settings

5 Using the Emulator with a Proxy

6 Interconnecting Emulator Instances

7 Sending a Voice Call or SMS to Another Emulator Instance

9 Using the Emulator Console

1 Port Redirection

2 Geo Location Provider Emulation

3 Hardware Events Emulation

4 Device Power Characteristics

Trang 38

5 Network Status

6 Network Delay Emulation

7 Network Speed Emulation

2 Managing AVDs with AVD Manager

The Android SDK includes a virtual mobile device emulator that runs on your computer The emulator lets you prototype, develop and test Android applications without using a physical device

The Android emulator mimics all of the hardware and software features of a typical mobile device, except that it cannot place actual phone calls It provides a variety of navigation and control keys, which you can "press" using your mouse or keyboard to generate events for your application It also provides a screen in which your application is displayed, together with any other active Android applications

Trang 39

To let you model and test your application more easily, the emulator utilizes Android Virtual Device (AVD) configurations AVDs let you define certain hardware aspects of your emulatedphone and allow you to create many configurations to test many Android platforms and hardware permutations Once your application is running on the emulator, it can use the services of the Android platform to invoke other applications, access the network, play audio and video, store and retrieve data, notify the user, and render graphical transitions and

themes

The emulator also includes a variety of debug capabilities, such as a console from which you can log kernel output, simulate application interrupts (such as arriving SMS messages or phone calls), and simulate latency effects and dropouts on the data network

Overview

The Android emulator is an application that provides a virtual mobile device on which you can run your Android applications It runs a full Android system stack, down to the kernel level, that includes a set of preinstalled applications (such as the dialer) that you can access from your applications You can choose what version of the Android system you want to run

in the emulator by configuring AVDs, and you can also customize the mobile device skin and key mappings When launching the emulator and at runtime, you can use a variety of

commands and options to control its behavior

The Android system images available through the Android SDK Manager contain code for the Android Linux kernel, the native libraries, the Dalvik VM, and the various Android packages (such as the Android framework and preinstalled applications) The emulator

Trang 40

provides dynamic binary translation of device machine code to the OS and processor

architecture of your development machine

The Android emulator supports many hardware features likely to be found on mobile devices,including:

 An ARMv5 CPU and the corresponding memory-management unit (MMU)

 A 16-bit LCD display

 One or more keyboards (a Qwerty-based keyboard and associated

Dpad/Phone buttons)

 A sound chip with output and input capabilities

 Flash memory partitions (emulated through disk image files on the

development machine)

 A GSM modem, including a simulated SIM Card

 A camera, using a webcam connected to your development computer.

 Sensors like an accelerometer, using data from a USB-connected Android device.

The following sections describe the emulator and its use for development of Android

applications in more detail

Android Virtual Devices and the Emulator

To use the emulator, you first must create one or more AVD configurations In each

configuration, you specify an Android platform to run in the emulator and the set of hardwareoptions and emulator skin you want to use Then, when you launch the emulator, you specify the AVD configuration that you want to load

Each AVD functions as an independent device, with its own private storage for user data, SD card, and so on When you launch the emulator with an AVD configuration, it automatically loads the user data and SD card data from the AVD directory By default, the emulator stores the user data, SD card data, and cache in the AVD directory

To create and manage AVDs you use the AVD Manager UI or the android tool that is

included in the SDK For complete information about how to set up AVDs, see Managing Virtual Devices

Starting and Stopping the Emulator

Ngày đăng: 22/06/2016, 15:41

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w