Docsity
Docsity

Prepare-se para as provas
Prepare-se para as provas

Estude fácil! Tem muito documento disponível na Docsity


Ganhe pontos para baixar
Ganhe pontos para baixar

Ganhe pontos ajudando outros esrudantes ou compre um plano Premium


Guias e Dicas
Guias e Dicas


Guia Passo a Passo para Desenvolver Aplicativos Android usando Eclipse, Manuais, Projetos, Pesquisas de Informática

Este documento fornece instruções detalhadas sobre como instalar e configurar o ambiente de desenvolvimento integrado (ide) eclipse para desenvolver aplicativos android. Ele aborda o download e instalação do java development kit (jdk), do android sdk e do android development tool (adt) plug-in, além da configuração do android debug bridge (adb) e do emulador. O documento também discute como instalar classes java compartilhadas entre projetos e atualizar o android sdk.

Tipologia: Manuais, Projetos, Pesquisas

2016

Compartilhado em 29/02/2016

eniac-estudante-1
eniac-estudante-1 🇧🇷

1 documento

1 / 74

Toggle sidebar

Esta página não é visível na pré-visualização

Não perca as partes importantes!

bg1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a

Pré-visualização parcial do texto

Baixe Guia Passo a Passo para Desenvolver Aplicativos Android usando Eclipse e outras Manuais, Projetos, Pesquisas em PDF para Informática, somente na Docsity!

Android Cookbook

by Ian F. Darwin

Copyright © 2012 O’Reilly Media, Inc.. All rights reserved. Printed in the United States of America.

Published by O’Reilly Media, Inc, 1005 Gravenstein Highway North, Sebastopol, CA 95472.

O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles ( http://my.safaribooksonline.com ). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected].

Editors: Mike Loukides and Courtney Nash

Production Editor: Teresa Elsey

Copyeditor: Audrey Doyle

Proofreader: Stacie Arellano

Indexer: Lucie Haskins

Cover Designer: Karen Montgomery

Interior Designer: David Futato

Illustrators: Robert Romano and Rebecca Demarest

April 2012: First Edition.

Revision History for the First Edition:

2012-04-05 First release See http://oreilly.com/catalog/errata.csp?isbn=9781449388416 for release details.

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Android Cookbook , the image of a marine iguana, and related trade dress are trade- marks of O’Reilly Media, Inc.

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps.

While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein.

ISBN: 978-1-449-38841-

[LSI]

1333645094

Table of Contents

CHAPTER 1

Getting Started

1.1 Introduction: Getting Started

Ian Darwin

Discussion

The famous “Hello, World” pattern came about when Kernighan and Plaugher wanted to write a “recipe” on how to get started in any new programming language and envi- ronment. This chapter is affectionately dedicated to these fine gentlemen, and to everyone who has ever struggled to get started in a new programming paradigm.

1.2 Learning the Java Language

Ian Darwin

Problem

Android apps are written in the Java programming language before they are converted into Android’s own class file format, DEX. If you don’t know how to program in Java you will find it hard to write Android apps.

Solution

Lots of resources are available for learning Java. Most of them will teach you what you need, but will also mention some API classes that are not available for Android devel- opment. Avoid any sections in any resource that talk about topics listed in the lefthand column of Table 1-1.

1

Table 1-1. Parts of the Java API to ignore

Java API Android equivalent Swing, applets Android’s GUI; see Chapter 7. Application entry point main() See Recipe 1.6. J2ME/Java ME Most of android.* replaces Java ME API. Servlets/JSP, J2EE/Java EE Designed for server-side use.

Discussion

Here are some books and resources on Java programming:

  • Java in a Nutshell by David Flanagan (O’Reilly) is a good introduction for pro- grammers, particularly those who are coming from C/C++. This book has grown from an acorn to a coconut in size, to keep up with the growth of Java SE over its lifetime.
  • Head First Java by Kathy Sierra and Bert Bates (O’Reilly). This provides a great visual-learner-oriented introduction to the language.
  • Thinking in Java by Bruce Eckel (Prentice-Hall).
  • Learning Java by Patrick Niemeyer and Jonathan Knudsen (O’Reilly).
  • “Great Java: Level 1”, a video by Brett McLaughlin (O’Reilly). This provides a visual introduction to the language.
  • Java: The Good Parts by Jim Waldo (O’Reilly).
  • Java Cookbook , which I wrote and which O’Reilly published. This is regarded as a good second book for Java developers. It has entire chapters on strings, regular expressions, numbers, dates and time, structuring data, I/O and directories, inter- nationalization, threading, and networking, all of which apply to Android. It also has a number of chapters that are specific to Swing and to some EE-based tech- nologies.

Please understand that this list will probably never be completely up-to-date. You should also refer to O’Reilly’s freely downloadable (with registration) Android Devel- opment Bibliography , a compilation of all the books from the various publishers whose books are in the online Safari service. This book is also distributed without charge at relevant conferences where O’Reilly has a booth.

See Also

This book’s primary author maintains a list of Java resources online at http://www .darwinsys.com/java/.

2 | Chapter 1: Getting Started

Table 1-2. List of create project arguments

Name Meaning Example --activity Name of your “main class” and default name for the generated .apk file. --activity HelloActivity --name Name of the project and the generated .apk file. --name MyProject --package Name of the Java package for your classes. --package com.exam ple.hello --path Path to create the project in (does not create a subdirectory under this, so don’t use /home/ you /workspace, but rather /home/ you /workspace/ NewProjectName ).

--path /home/ian/ workspace/MyPro ject (see above for Windows example) --target API level of the Android platform to target; use android list tar gets to see list of targets. A number is an "ID,” not an API level; for that, use android- with the API level you want.

--target android-

If it cannot complete the requested operation, the android command presents a volu- minous “command usage” message listing all the operations it can do and the argu- ments for them. If successful, the android create project command creates the files and directories listed in Table 1-3.

Table 1-3. Artifacts created by create project

Name Meaning AndroidManifest.xml Config file that tells Android about your project bin Generated binaries (compiled class files) build.properties Editable properties file build.xml Standard Ant build control file default.properties or project.properties (depending on tools version)

Stores SDK version and libraries used; maintained by plug-in

gen Generated stuff libs Libraries, of course res Important resource files (strings.xml, layouts, etc.) src Source code for your application src/packagename/ActivityName.java Source of “main” starting activity test Copies of most of the above

It is a normal and recommended Android practice to create your user interface in XML using the layout file created under res/layout, but it is certainly possible to write all the code in Java. To keep this example self-contained, we’ll do it the “wrong” way for now. Use your favorite text editor to replace the contents of the file HelloWorld.java with the contents of Example 1-2.

4 | Chapter 1: Getting Started

Example 1-2. HelloWorld.java

import android.app.Activity; import android.widget.*;

public class Hello extends Activity {

/**

  • This method gets invoked when the activity is instantiated in
  • response to e.g., you clicked on the app's Icon in the Home Screen. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create a TextView for the current Activity TextView view = new TextView(this); // Make it say something view.setText("Hello World"); // Put this newly created view into the Activity, // sort of like JFrame.getContentPane().add(view) setContentView(view); } }

Assuming you have the Apache Software Foundation Ant Build Tool installed (and it is included with recent versions of the Android SDK), you can now (in a command-line window) change to the project directory (...MyDocuments\MyAndroid in Example 1-1) and issue the command:

ant debug

This will create an archive file named, for example, MyAndroid.apk (with “apk” stand- ing for Android Package) in the bin directory.

If this is your first time here, you may need to create an Android Virtual Device (AVD), which is just a named configuration for the Android emulator specifying target reso- lution, API level, and so on. You can create an emulator using:

android create avd -n my_droid -t 7

For more details on creating an AVD, see Recipe 3.3.

You can then start the Android Debug Bridge (ADB) server and the emulator:

adb start-server emulator -avd my_droid -t 5

Assuming you now have either the emulator running or your device plugged in and recognized via USB, you can then do:

adb -e install -r bin/MyAndroid.apk

The -e flag is for the emulator; use -d for a real device.

If you are handy with shell scripts or batch files, you’ll want to create one called, say, download , to avoid typing the adb invocation on every build cycle.

1.3 Creating a “Hello, World” Application from the Command Line | 5

Figure 1-1. Starting to create an Eclipse project

Click Next. Give your new project a name, and click Next (see Figure 1-2).

Select an SDK version to target. Version 2.1 gives you almost all the devices in use today; version 3.x or 4.x gives you the latest features (see Figure 1-3). You decide.

Figure 1-4 shows the project structure expanded in the Project panel on the right. It also shows the extent to which you can use Eclipse auto-completion within Android— I added the gravity attribute for the label, and Eclipse is offering a full list of possible attribute values. I chose center-horizontal, so the label should be centered when we get the application running.

In fact, if you set gravity to center_vertical on the LinearLayout and set it to cen ter_horizontal on the TextView, the text will be centered both vertically and horizon- tally. Example 1-3 is the layout file main.xml (located under res/layout ) which achieves this.

1.4 Creating a “Hello, World” Application in Eclipse | 7

Example 1-3. The XML layout

Figure 1-2. Setting parameters for a new Eclipse project

8 | Chapter 1: Getting Started