THE BOOK FOR LEARNING ANDROID----GREAT ONE

http://ofps.oreilly.com/titles/9781449390501/Android_Overview.html




Chapter 3. Quick Start

 If you're new to the Android mobile operating system, Learning Android is the perfect way to master the fundamentals. This gentle introduction shows you how to use Android's basic building blocks to develop user interfaces, store data, and more. Buy the print book or ebook.

In this chapter, you will learn how to set up your environment for Android development. I’ll go beyond just telling you where to download the software from, but will also into some of the best practices in getting set up. I’ll look at development operating system choices as well as Android tools available. You will see the good, the bad, and the ugly of various choices of tools and platforms that you’re about to make (or someone else has already made for you).

By the end of this chapter, you will have your entire development environment setup. You’ll be able to write a Hello World application, build it, and run it on the emulator (or physical device, if you want).

Note

I’m going to be using ~ to refer to your home directory. On Mac OS X, that’s typically something like /Users/marko. On Linux, it would be/home/marko and on Windows Vista and 7, C:\Users\marko (in Windows XP, it would be C:\Documents and Settings\marko). Also, I’m going to be using Unix-style forward slashes and not Windows back slashes to denote file path separators.

So, if you’re on Windows, just change ~ to C:\Users\YourUserName and / to \. Other than that, everything should be pretty much the same no matter whether you are on Mac, Linux, or Windows.

Installing the Android SDK

Android Software Development Kit (SDK) is all you need to develop applications for Android. It comes with a set of tools as well as a platform to run it and see it all work. You can download Android SDK for your particular platform from Android SDK Download page.

Once you download it, unzip (or on Linux, untar) it into a folder that is easy to get to. Further examples in the book will assume your SDK is in the folder ~/android-sdk. If it’s in a different location, use that location instead of ~/android-sdk. For example:

Windows
C:\apps\android-sdk-windows
Linux
/home/ YourUserName /android-sdk-linux_86
Mac OS X
/Users/ YourUserName /android-sdk-mac_86

Tip

For Windows users, I strongly recommend choosing directories without spaces in them. This is because we’ll be doing work on the command-line and spaces just complicate things. Because the Windows XP home directory is in C:\Documents and Settings, I would recommend puttingandroid-sdk in a top-level directory that you create, such as C:\apps.

However, on Windows Vista or 7, you can simply extract android-sdk intoC:\Users\YourUserName.

Setting up PATH to Tools

Android SDK has a folder with all the major tools in it. Since we’re going to be using these tools from the command line, it is very helpful to add your ~/android-sdk/tools/ directory to your system PATH variable. This will allow you easier access to your tools without having to navigate to their specific location every single time.

Details for setting up PATH variable depend on the platform, and are documented at Installing Android SDK page, Step 2.

Installing Eclipse

Eclipse is an open-source collection of programming tools originally created by IBM for for Java. Nowadays, most developers in the Java community favor Eclipse as their Integrated Development Environment (IDE) of choice. Eclipse lives atEclipse.org.

Eclipse is very feature-rich and has a lot of time-saving features. I’ll be pointing them out as we keep on going. Keep in mind that, while powerful, Eclipse tends to be very resource-hungry and you may want to restart it once a day if it starts running very sluggishly.

While you can do Android development with any favorite text editor or IDE, most developers seem to be using Eclipse, and thus I’m basing this book on its use as well.

Tip

If you choose not to use Eclipse, please refer to Developing in Other IDEs

Now, download Eclipse from http://www.eclipse.org/downloads/. I recommend Eclipse IDE for Java Developers (NOT the twice-as-large Eclipse for Java EE developers). You can install it in any directory you’d like.

Eclipse Workspace

Eclipse organizes all your work by projects. Projects are placed in a workspace, which is a location you choose. So, where you put your workspace is significant. I recommend ~/workspace as a simple place for your code. On Windows however, I recommend storying your workspace in a directory that doesn’t have spaces it (they complicate anything you might do at the command-line). C:\workspace is a good choice for Windows users.

Setting Up Android Development Tools

You also need to set up Android Tools for Eclipse. The instructions are:

Figure 3.1. Install New Software

Install New Software

  1. Start Eclipse, then select Help → Install New Software.
  2. In the Available Software dialog, click Add.
  3. In the Add Site dialog that appears, enter a name for the remote site (for example, "Android Plugin") in the "Name" field.
  4. In the "Location" field, enter this URL: https://dl-ssl.google.com/android/eclipse/
  5. Click OK.
  6. Back in the Available Software view, you should now see "Developer Tools" added to the list. Select the checkbox next to Developer Tools, which will automatically select the nested tools Android DDMS and Android Development Tools. Click Next.
  7. In the resulting Install Details dialog, the Android DDMS and Android Development Tools features are listed. Click Next to read and accept the license agreement and install any dependencies, then click Finish.
  8. Restart Eclipse.

Note

If you have trouble downloading the plugin, you can try using "http" in the URL, instead of "https" (https is preferred for security reasons).

Hello, World

To make sure everything is set up properly, we’re going to write a simple Hello World program. As a matter of fact, there’s not much for us to write, but a lot to understand. This is because Eclipse will create the project shell for us from some predefined templates.

Creating New Project

In Eclipse, choose File→New→Android Project. Sometimes (especially the first time you run Eclipse) the Android tools may not be appear there right away. They should show up in the future after you’ve used them for the first time. If Android Project is not an option under File→New, choose Other and look for Android Project in there.

In the new project dialog window, fill out the following:

  1. "Project name" is an Eclipse construct. Eclipse organizes everything into projects. A project name should be one word. I like to use CamelCase naming convention here. Go ahead and type: HelloWorld.
  2. Next, you need to choose the build target. The build target tells the build tools which version of Android platform you are building for. You should see a list of available platforms and add-ons you have installed as part of your SDK in here. Go ahead, pick one of the newer ones, such as Android 2.2 (but don’t choose the targets named Google APIs).
  3. You need to fill out your project properties next. The application name is the plain English name of your application. Go ahead, write something like Hello, World!!!.
  4. The package name is a Java construct. In Java, all source code is organized into packages. Packages are important because, among other things, they specify the visibility of objects between the various Java classes in your project. In Android, packages are also important for application signing purposes. Your package name should be the reverse of your domain name with optional subdomains. I might use com.example.calculator if I were building a calculator app and my domain name was example.com. I’m going to be usingcom.marakana for my package name here.
  5. You can optionally specify an activity. I haven’t covered activities yet (you’ll learn about them in Chapter 6, Android User Interface), but think of them as corresponding to the various screens in your application. An activity is going to be represented by a Java class, so as such its name should adhere to Java class naming conversion: start with upper case and use CamelCase to separate words. So, type HelloWorld for your activity name.
  6. The minimum SDK version is the minimum version of Android—as represented by API level—that is required on the device in order to run this application. You want this number to be as low as possible so that your app can run on as many various devices out there as possible. I’m going to put 8 here to represent Android 2.2, which I know I have installed.

Finally, click on Finish button and Eclipse will create your project. Let’s look at the various files that this process created:

Figure 3.2. HelloWorld New Project Window

HelloWorld New Project Window

Manifest File

Manifest file glues everything together. It is this file that explains what the application consists of, what all its main building blocks are, what permissions it requires, and so on.

Example 3.1. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.marakana" android:versionCode="1" android:versionName="1.0">
  <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".HelloWorld" 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>
  <uses-sdk android:minSdkVersion="8" />

</manifest>

Layout XML Code

The layout file specifies the layout of your screen. In this case, we have only one screen and its loaded by the Java code, HelloWorld activity above.

Example 3.2. res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content" android:text="@string/hello" />
</LinearLayout>

Strings

This is another XML file that contains all text that your application uses. For example, names of buttons, labels, default text and all such strings go into this file. This is the best practice of separating concerns of various files, even if they are XML files. In other words, layout XML is responsible for layout out widgets, but strings XML is responsible for their textual content.

Example 3.3. res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, HelloWorld!</string>
    <string name="app_name">Hello, World!!!</string>
</resources>

The R File

The R file is the glue between the world of Java and the world of resources. It is an automatically generated file and as such you never modify it. It is recreated every time you change anything in the res directory, for example add an image or XML file.

You don’t need to look at this file much. We will use data it in quite a bit, but we’ll use Eclipse to help us refer to values stored in this file.

Example 3.4. gen/com/marakana/R.java

/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.marakana;

public final class R {
    public static final class attr {
    }
    public static final class drawable {
        public static final int icon=0x7f020000;
    }
    public static final class layout {
        public static final int main=0x7f030000;
    }
    public static final class string {
        public static final int app_name=0x7f040001;
        public static final int hello=0x7f040000;
    }
}

Java Source Code

The Java code is what drives everything. It is this code that ultimately gets converted to Dalvik executable and runs your application.

Example 3.5. HelloWorld.java

package com.marakana;

import android.app.Activity;
import android.os.Bundle;

public class HelloWorld extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }
}

The Emulator

Running your application on a physical device versus an emulated device is pretty much the same thing. That is because the emulator is an actual code emulator, meaning it runs the same code base as the actual device, all the way down to the machine layer.

Tip

A simulator and an emulator sound very similar, but are fundamentally different. To emulate means to imitate the machine executing the binary code. So, an emulator is sort of like a virtual machine. A simulator merely simulates the behavior of the code at a higher level. Android SDK ships with a true emulator, based on QEMU.

To use the emulator, we’ll have to create an Android Virtual Device (AVD). The easiest way to do that is to start the android tool via Eclipse.

To create a new AVD, start the tool called Android SDK and AVD Manager. You can start this tool from Eclipse by clicking on icon  or via command line by starting tool called android in your SDK/tools directory.

Figure 3.3. Android SDK and AVD Manager

Android SDK and AVD Manager

From within Android SDK and AVD Manager, you can choose New… and a Create New AVD dialog window will pop up. In this dialog, you specify the parameters for your new AVD. The name is any name you choose. Target is what you what to have installed as version of Android on this particular AVD. The list of possible targets is based on platforms and add-ons that you have installed into your SDK. If you don’t have any targets, go back to Android SDK and AVD Manager and choose Available packages tab to install at least one platform, such as Android 2.3 - API level 9, for example.

Each AVD can have an SD Card. You can just specify a number here for your built-in card, in megabytes. Skin is the look and feel of your device as well as its form factor. Hardware option lets you fine tune what this AVD does or doesn’t support.

Figure 3.4. New AVD Dialog

New AVD Dialog

Once you are done with this dialog, you will have and AVD in your list. Go ahead and start it. An emulator will pop up.

Figure 3.5. Emulator

Emulator

An Emulator Versus a Physical Phone

For the most part, running your application on the emulator is identical to running it on a physical phone. There are some notable exceptions, mostly to do with things that are just hard to virtualize, such as sensors. Other hardware-related features like telephony and location services, can be simulated in the emulator.

Summary

Setting up Android development environment breaks down to setting up Android SDK and Eclipse. Once you have set you your development environment, a good test that everything is working is to use Eclipse to create a simple Hello World project and run it in the Emulator. If that runs fine, you are almost certain that your system is setup and ready for further development.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来分别为您解释这些代码: 1. 泛型委托 ```csharp delegate T MyDelegate<T>(T arg); MyDelegate<int> myDelegate = delegate (int arg) { return arg * 2; }; int result = myDelegate(5); // result = 10 ``` 这段代码定义了一个泛型委托`MyDelegate`,它接受一个类型为`T`的参数,并返回一个类型为`T`的结果。然后,我们使用`MyDelegate<int>`来实例化一个`myDelegate`对象,并且将一个匿名方法作为委托的实现。最后,我们调用`myDelegate(5)`,它将返回10,因为传入的参数是5,而匿名方法的实现是将参数乘以2。 2. 委托作为函数参数 ```csharp delegate void MyDelegate(string arg); void MyFunction(MyDelegate myDelegate, string arg) { myDelegate(arg); } MyDelegate myDelegate = delegate (string arg) { Console.WriteLine(arg); }; MyFunction(myDelegate, "Hello, world!"); // 输出:"Hello, world!" ``` 这段代码定义了一个函数`MyFunction`,它接受一个`MyDelegate`类型的参数和一个字符串参数`arg`。在函数内部,它调用了传入的委托并传递了`arg`参数。然后,我们实例化一个`myDelegate`对象,并将一个匿名方法作为委托的实现。最后,我们将`myDelegate`对象作为参数传递给`MyFunction`函数,并传递一个字符串参数"Hello, world!",它将在控制台输出"Hello, world!"。 3. ActionFunc委托 ```csharp Action<string> myAction = delegate (string arg) { Console.WriteLine(arg); }; Func<string, int> myFunc = delegate (string arg) { return arg.Length; }; myAction("Hello, world!"); // 输出:"Hello, world!" int length = myFunc("Hello, world!"); // length = 13 ``` 这段代码实例化了一个`Action`委托对象`myAction`和一个`Func`委托对象`myFunc`,它们分别接受一个字符串参数和返回一个整数值。我们使用匿名方法来实现这两个委托。然后,我们分别调用了`myAction`和`myFunc`,它们分别输出"Hello, world!"和返回字符串"Hello, world!"的长度13。 4. 委托多播 ```csharp delegate void MyDelegate(string arg); MyDelegate myDelegate1 = delegate (string arg) { Console.WriteLine("Delegate 1: " + arg); }; MyDelegate myDelegate2 = delegate (string arg) { Console.WriteLine("Delegate 2: " + arg); }; MyDelegate myDelegate3 = delegate (string arg) { Console.WriteLine("Delegate 3: " + arg); }; MyDelegate myMultiDelegate = myDelegate1 + myDelegate2 + myDelegate3; myMultiDelegate("Hello, world!"); ``` 这段代码定义了三个`MyDelegate`委托对象`myDelegate1`、`myDelegate2`和`myDelegate3`,它们分别输出`"Delegate 1: "`、`"Delegate 2: "`和`"Delegate 3: "`前缀的字符串。然后,我们使用"+"运算符将这三个委托对象组合成一个多播委托`myMultiDelegate`。最后,我们调用`myMultiDelegate("Hello, world!")`,它将依次调用`myDelegate1`、`myDelegate2`和`myDelegate3`,并传递"Hello, world!"作为参数。 5. 事件 ```csharp class MyClass { public delegate void MyDelegate(string arg); public event MyDelegate MyEvent; public void DoSomething(string arg) { Console.WriteLine("DoSomething: " + arg); MyEvent?.Invoke(arg); } } class Program { static void Main(string[] args) { MyClass myClass = new MyClass(); myClass.MyEvent += delegate (string arg) { Console.WriteLine("MyEvent: " + arg); }; myClass.DoSomething("Hello, world!"); } } ``` 这段代码定义了一个`MyClass`类,它包含一个`MyDelegate`委托类型的`MyEvent`事件和一个`DoSomething`方法。在`DoSomething`方法中,我们输出一个字符串"DoSomething: "和传入的参数`arg`,然后调用`MyEvent`委托并传递`arg`参数。在`Program`类中,我们实例化一个`MyClass`对象`myClass`,并将一个匿名方法作为`MyEvent`事件处理程序。然后,我们调用`myClass.DoSomething("Hello, world!")`,它将输出"DoSomething: Hello, world!"和"MyEvent: Hello, world!"。 6. 普通匿名函数 ```csharp delegate int MyDelegate(string arg); MyDelegate myDelegate = delegate (string arg) { Console.WriteLine("MyDelegate: " + arg); return arg.Length; }; int length = myDelegate("Hello, world!"); // 输出:"MyDelegate: Hello, world!" // length = 13 ``` 这段代码定义了一个`MyDelegate`委托类型和一个`myDelegate`委托对象。我们使用匿名方法来实现`myDelegate`委托,并在实现中输出一个字符串"MyDelegate: "和传入的参数`arg`,然后返回`arg`字符串的长度。最后,我们调用`myDelegate("Hello, world!")`,它将输出"MyDelegate: Hello, world!"并返回字符串"Hello, world!"的长度13。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值