Android Programming Cookbook

Loading...
Android Programming Cookbook

Android Programming Cookbook

i

Android Programming Cookbook

ii

Contents

1

2

Android Tutorial For Beginners

1

1.1

What is Android? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1

1.2

Installing Android Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1

1.3

Android versions and Android SDK Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

7

1.4

Supporting different screen sizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

7

1.5

Android Project Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8

1.6

Create "Hello Android World" application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

9

1.6.1

Create a New Android Studio Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

9

1.6.2

Create the source code of a simple FirstAndroidApplication Activity . . . . . . . . . . . . . . . . . . . . 13

1.6.3

Create the layout of the project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

1.6.4

Android Manifest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

1.6.5

Edit the FirstAndroidApplication dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

1.6.6

Edit the FirstAndroidApplication strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

1.6.7

Add the drawable for every screen density . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

1.6.8

Build, compile and run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

1.7

Download the Android Studio Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

1.8

How to continue? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

Android Project migration from Eclipse to Android Studio

19

2.1

Why to use Android Studio over Eclipse ADT? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

2.2

Android Studio new project structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

2.3

Gradle and build.gradle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

2.4

Simple Eclipse ADT project migration to Android Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

2.5

Java code and resources migration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

2.6

AndroidManifest.xml and build.gradle file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

2.7

Download the Android Studio Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

Android Programming Cookbook

3

Android Google Maps v2 Tutorial

iii

33

3.1

Create a Google Maps API key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

3.2

Create a New Android Application Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

3.3

Importing Google Play Services in your project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

3.4

Create the layout of the main Google Maps v2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

3.5

Create the source code of the main AndroidGoogleMapsActivity . . . . . . . . . . . . . . . . . . . . . . . . . . 52

3.6

Creating the source code of the helper class CustomMarker.java . . . . . . . . . . . . . . . . . . . . . . . . . . 58

3.7

Creating the source code of the helper class LatLngInterpolator.java . . . . . . . . . . . . . . . . . . . . . . . . 59

3.8

Creating the source code of the helper class MarkerAnimation.java . . . . . . . . . . . . . . . . . . . . . . . . . 61

3.9

Modifying the AndroidManifest.xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

3.10 Build, compile and run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 3.11 Download the Eclipse Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 4

5

Android Start Service on Boot Example

67

4.1

Create a New Android Studio Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

4.2

Create the layout and the source code of a simple AndroidStartServiceOnBoot Activity . . . . . . . . . . . . . . 71

4.3

Creating the source code of the BroadcastReceiverOnBootComplete Service . . . . . . . . . . . . . . . . . . . . 72

4.4

Creating the source code of the AndroidServiceStartOnBoot Service . . . . . . . . . . . . . . . . . . . . . . . . 72

4.5

Editing the Android Manifest xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

4.6

Build, compile and run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

4.7

Download the Android Studio Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

Android Bluetooth Connection Example

80

5.1

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

5.2

Create a New Android Studio Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

5.3

Create the layout of the BluetoothChat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

5.4

Create the source code of the BluetoothChat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

5.5

Create the source code of the BluetoothChatService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

5.6

Create the layout of the DeviceListActivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

5.7

Create the source code of the DeviceListActivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

5.8

AndroidManifest.xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100

5.9

build.gradle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

5.10 Build, compile and run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 5.11 Download the Android Studio Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

Android Programming Cookbook

6

7

Android Multitouch Example

iv

105

6.1

Create a New Android Studio Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

6.2

Create the layout of the project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

6.3

Creating the source code of the TouchableFrameLayout FrameLayout . . . . . . . . . . . . . . . . . . . . . . . 110

6.4

Creating the source code of the main AndroidMultitouchActivity Activity . . . . . . . . . . . . . . . . . . . . . 113

6.5

Create the strings.xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

6.6

Android Manifest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

6.7

build.gradle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

6.8

Build, compile and run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

6.9

Download the Android Studio Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118

Android StackView Example

119

7.1

Create a New Android Studio Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

7.2

Create the layout of the AndroidStackViewActivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

7.3

Create the layout of the StackView items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

7.4

Create the source code of the StackItems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

7.5

Create the source code of the StackAdapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

7.6

Create the source code of the AndroidStackViewActivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

7.7

AndroidManifest.xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

7.8

build.gradle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

7.9

Build, compile and run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

7.10 Download the Android Studio Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 8

Android ViewPager Example

130

8.1

Create a New Android Studio Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

8.2

Create the layout of the main AndroidViewPagerExample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134

8.3

Create the source code of the main AndroidViewPagerExample Activity . . . . . . . . . . . . . . . . . . . . . . 135

8.4

Create the layout of the main FragmentViewPager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136

8.5

Create the source code of the main FragmentViewPager support.v4.app.Fragment . . . . . . . . . . . . . . . . . 136

8.6

Android Manifest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

8.7

Composing build.gradle file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

8.8

Build, compile and run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

8.9

Download the Android Studio Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

Android Programming Cookbook

Copyright (c) Exelixis Media P.C., 2016 All rights reserved. Without limiting the rights under copyright reserved above, no part of this publication may be reproduced, stored or introduced into a retrieval system, or transmitted, in any form or by any means (electronic, mechanical, photocopying, recording or otherwise), without the prior written permission of the copyright owner.

v

Android Programming Cookbook

vi

Preface Android is a mobile operating system developed by Google, based on the Linux kernel and designed primarily for touchscreen mobile devices such as smartphones and tablets. Android’s user interface is mainly based on direct manipulation, using touch gestures that loosely correspond to real-world actions, such as swiping, tapping and pinching, to manipulate on-screen objects, along with a virtual keyboard for text input. In addition to touchscreen devices, Google has further developed Android TV for televisions, Android Auto for cars, and Android Wear for wrist watches, each with a specialized user interface. Variants of Android are also used on notebooks, game consoles, digital cameras, and other electronics. Android has the largest installed base of all operating systems of any kind. Android has been the best selling OS on tablets since 2013, and on smartphones it is dominant by any metric. (Source: http://en.wikipedia.org/wiki/Android_(operating_system)) In this ebook, we provide a compilation of Android programming examples that will help you kick-start your own web projects. We cover a wide range of topics, from Services and Views, to Google Maps and Bluetooth functionality. With our straightforward tutorials, you will be able to get your own projects up and running in minimum time.

Android Programming Cookbook

vii

About the Author Chryssa is a Computer Science graduate from Athens University of Economic and Business. During her studies, Chryssa carried out a great variety of projects ranging from networking to software engineering. She is very keen on front end development especially on mobile technologies and web applications. She has worked as a junior Software Engineer in the telecommunications area and currently works as an Android Developer.

Android Programming Cookbook

1 / 143

Chapter 1

Android Tutorial For Beginners There are lots of reasons why more and more people are interested in learing how to be able to develop Android applications. Unarguably, Android is the most popular mobile operating system, with almost 2 billion devices activated and it offers a unified approach to application development for mobile devices. That means, that developers need only develop for Android, and their applications will be able to run on different devices powered by Android. This particular asset gives Android endless possibilites! This means that and application that is designed to work on mobile phone devices can be also transfered to Android powered TV sets or Android Car systems. This is why, Android is an exciting space to make apps that can help you in every aspect of your life, can help you communicate, organize, educate, entertain or just to make your life easier in every device that they might run on! In this special example, we are going to set our Android Development Studio IDE, make our very first Android application and discover the Android Development world in the easiest possible way. The mobile development world can be very fun, because the direct results we see when creating our own application, can be highly motivating and rewarding.

1.1

What is Android?

Android is a mobile operating system currently developed by Google, based on the Linux kernel and designed primarily for touchscreen mobile devices such as smartphones and tablets. And as we said before, Android offers a unified approach to application development for mobile devices. Android is an open-source operating system named Android. Google has made the code for all the low-level "stuff" as well as the needed middleware to power and use an electronic device, and gave Android freely to anyone who wants to write code and build the operating system from it. There is even a full application framework included, so third-party apps can be built and installed, then made available for the user to run as they like. The "proper" name for this is the Android Open Source Project, and this is what people mean when they say things like Android is open and free. Android, in this iteration, is free for anyone to use as they like.

1.2

Installing Android Studio

In order to write an Android application, we are going to need a development environment. Google has made a very useful tool for all Android Developers, the Android Studio. Android Studio is the official IDE for Android development, and with a single download includes everything you need to begin developing Android apps. Included in the download kit, are the Software Development Kit (SDK), with all the Android libraries we may need, and the infrastructure to download the many Android emulator instances, so that we can initially run our application, without needing a real device. So, we are going to download and install Android Studio.

Android Programming Cookbook

2 / 143

First we have to have installed the Java Development Kit (JDK) from Oracle. If you do not, please you should download the latest JDK from the Oracle’s special section here.

Figure 1.1: Android Studio Installation - step 1

Android Programming Cookbook

3 / 143

Figure 1.2: Android Studio Installation - step 2

Android Programming Cookbook

4 / 143

Figure 1.3: Android Studio Installation - step 3

Android Programming Cookbook

5 / 143

Figure 1.4: Android Studio Installation - step 4

Android Programming Cookbook

6 / 143

Figure 1.5: Android Studio Installation - step 5

Android Programming Cookbook

7 / 143

Figure 1.6: Android Studio Installation - Ready

1.3

Android versions and Android SDK Manager

Google, releases almost every year (or even sooner than a year), a new Android version in order to update the mobile operating system, so that it contains new features and possibilities and of course to fix things that might not work in the right way. So, each version of Android has it’s own SDK (software development kit), so that we can use to build apps that can run on and include all the latest features Android has added in its latest versions. This means that it is essential that we keep up updating our applications with the latest features all the time, and if possible, without losing the consistency of the previous Android versions. As part of the Setup Wizard you will already have the latest SDK available to you, however it’s useful to know how to install additional SDK’s if you need to work with older devices that do not run the latest version of Android. SDK’s allow you to create AVD’s (Android Virtual Devices) to test your Apps on, customized to your personal configuration. Want to see how your Android App looks on a TV sized screen? If you have a screen big enough you can find out.

1.4

Supporting different screen sizes

Android runs on a variety of devices that offer different screen sizes and densities. This means that Android can handle applications that run on small mobile phone devices, as well as applications that run on large tablet densities.

Android Programming Cookbook

8 / 143

This feature gives Android a great advantage, but also, although the system performs scaling and resizing on different screens, developers should make the effort to optimize their application for different screen sizes and densities. Android system provides a consistent development environment across devices and handles most of the work to adjust each application’s user interface to the screen on which it is displayed. At the same time, the system provides APIs that allow you to control your application’s UI for specific screen sizes and densities, in order to optimize your UI design for different screen configurations. For example, you might want a UI for tablets that’s different from the UI for handsets. Below is an introduction to the terms and concepts used, a summary of the screen configurations that the system supports, and an overview of the API and underlying screen-compatibility features: Screen size Actual physical size, measured as the screen’s diagonal. For simplicity, Android groups all actual screen sizes into four generalized sizes: small, normal, large, and extra-large. Screen density The quantity of pixels within a physical area of the screen; usually referred to as dpi (dots per inch). For example, a "low" density screen has fewer pixels within a given physical area, compared to a "normal" or "high" density screen. For simplicity, Android groups all actual screen densities into six generalized densities: low, medium, high, extra-high, extraextra-high, and extra-extra-extra-high. Orientation The orientation of the screen from the user’s point of view. This is either landscape or portrait, meaning that the screen’s aspect ratio is either wide or tall, respectively. Be aware that not only do different devices operate in different orientations by default, but the orientation can change at runtime when the user rotates the device. Resolution The total number of physical pixels on a screen. When adding support for multiple screens, applications do not work directly with resolution; applications should be concerned only with screen size and density, as specified by the generalized size and density groups. Density-independent pixel (dp) A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application’s UI, to ensure proper display of your UI on screens with different densities. Android provides support for multiple screen sizes and densities, reflecting the many different screen configurations that a device may have. You can use features of the Android system to optimize your application’s user interface for each screen configuration and ensure that your application not only renders properly, but provides the best user experience possible on each screen. To simplify the way that you design your user interfaces for multiple screens, Android divides the range of actual screen sizes and densities into sizes: small, normal, large, and xlarge A set of six generalized densities: • ldpi (low) ~120dpi • mdpi (medium) ~160dpi • hdpi (high) ~240dpi • xhdpi (extra-high) ~320dpi • xxhdpi (extra-extra-high) ~480dpi • xxxhdpi (extra-extra-extra-high) ~640dpi

1.5

Android Project Structure

Before we try to make our first Android application, we should first see the basic parts of an Android application project, in order to recognize them and be able to understand them better. • Activities The Activities are the main Java classes, that contain the Android code with which we are going to develop, what do we want the application to do.

Android Programming Cookbook

9 / 143

• Layouts The Layouts are the main xml files, that contain the Android xml code with which we are going to develop, how will our application views look like. • Values The Layouts are the main xml files, that contain the Android xml code with which we are going to develop, how will our application views look like. – Animation Resources – Color State List Resource – Drawable Resources – Layout Resource – Menu Resource – String Resources – Style Resource • Drawables A drawable resource is a general concept for a graphic that can be drawn to the screen. There are several different types of drawables: – Bitmap File A bitmap graphic file (.png, .jpg, or .gif). Creates a BitmapDrawable. – Nine-Patch File A PNG file with stretchable regions to allow image resizing based on content (.9.png). Creates a NinePatchDrawable. – Layer List A Drawable that manages an array of other Drawables. These are drawn in array order, so the element with the largest index is be drawn on top. Creates a LayerDrawable. – State List An XML file that references different bitmap graphics for different states (for example, to use a different image when a button is pressed). Creates a StateListDrawable. – Level List An XML file that defines a drawable that manages a number of alternate Drawables, each assigned a maximum numerical value. Creates a LevelListDrawable. – Transition Drawable An XML file that defines a drawable that can cross-fade between two drawable resources. Creates a TransitionDrawable. – Inset Drawable An XML file that defines a drawable that insets another drawable by a specified distance. This is useful when a View needs a background drawble that is smaller than the View’s actual bounds. – Clip Drawable An XML file that defines a drawable that clips another Drawable based on this Drawable’s current level value. Creates a ClipDrawable. – Scale Drawable An XML file that defines a drawable that changes the size of another Drawable based on its current level value. Creates a ScaleDrawable – Shape Drawable An XML file that defines a geometric shape, including colors and gradients. Creates a ShapeDrawable. Once our app is ready, we will use a build tool to compile all the project files and package them together into an .apk file that you can run on Android devices and/or submit to Google Play.

1.6 1.6.1

Create "Hello Android World" application Create a New Android Studio Project

Open Android Studio and choose Start a new Android Studio Project in the welcome screen.

Android Programming Cookbook

Figure 1.7: Welcome to Android Studio screen. Choose Start a new Android Studio Project. Specify the name of the application, the project and the package.

10 / 143

Android Programming Cookbook

Figure 1.8: Configure your new project screen. Add your application name and the projects package name. In the next window, select the form factors your app will run on.

11 / 143

Android Programming Cookbook

12 / 143

Figure 1.9: Target Android Devices screen. In the next window you should choose Add no activity. In this example, we are going to create our Activity.

Android Programming Cookbook

13 / 143

Figure 1.10: Add an activity to Mobile. Choose: Add no activity. Now, our project has just been created!

1.6.2

Create the source code of a simple FirstAndroidApplication Activity

Add a new Java class Activity inside src/com.javacodegeeks.FirstAndroidApplication/ so that we are going to have the src/com.javacodegeeks.FirstAndroidApplication/FirstActivity.java file and paste the code below. FirstActivity.java package com.javacodegeeks.FirstAndroidApplication; import android.app.Activity; import android.os.Bundle; public class FirstActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); } }

Android Programming Cookbook

1.6.3

14 / 143

Create the layout of the project

Add a new xml file inside /res/layout folder, with name main_layout.xml. We should have the /res/layout/ main_layout.xml file and paste the code below. main_layout.xml

1.6.4

Android Manifest

Edit the AndroidManifest.xml file inside /app/manifests folder. The AndroidManifest.xml of our project is simple and should be like this: AndroidManifest.xml

Android Programming Cookbook

1.6.5

15 / 143

Edit the FirstAndroidApplication dimensions

Add a new xml file inside /res/values folder, with name dimens.xml. We should have the /res/values/dimens. xml file and paste the code below. dimens.xml 20dp 10dp

1.6.6

Edit the FirstAndroidApplication strings

Add a new xml file inside /res/values folder, with name strings.xml. We should have the /res/values/strings. xml file and paste the code below. strings.xml AndroidFirstApplication Hello Android!

1.6.7

Add the drawable for every screen density

Inside /res/values folder, we should add the folders for each screen dimension we have, and add the specific drawable for each one.

Android Programming Cookbook

16 / 143

Figure 1.11: Add the drawables for every screen density. In this way, we are going to have the right drawable dimension for every different screen density.

1.6.8

Build, compile and run

When we are ready, we build our application by pressing the play button in our AndroidStudio main toolbar.

Figure 1.12: Compile and run. After we build, compile and run our project, the main FirstAndroidApplication application should look like this:

Android Programming Cookbook

17 / 143

Figure 1.13: This is our FirstAndroidApplication.

Android Programming Cookbook

1.7

18 / 143

Download the Android Studio Project

This was an example of first Android application. Download You can download the full source code of this example here: FirstAndroidApplication

1.8

How to continue?

Here is a list of basic Android tutorials, that you can follow in order to make the first basic steps in the Android World: Android Layouts and Views • Android FrameLayout Example • Android LinearLayout Example • Android ImageView Example • Android TextView Example • Android Button Example Android Click and Drag Listeners • Android OnClickListener Example • Android Drag and Drop Example Android Styles and UI Elements • Android Styles and Themes Example • Android Toast Example • Android Toolbar Example Android Activities • Android Activity Transition Example Android Development • Building Android Applications with Gradle • Android Project migration from Eclipse to Android Studio Of course the most accurate and complete guide, is the official Android Developers Guide, that covers every aspect of the Android Development: • Official Android Developers Guide

Android Programming Cookbook

19 / 143

Chapter 2

Android Project migration from Eclipse to Android Studio Android Studio is the official IDE for Android development, and with a single download includes everything you need to begin developing Android apps. This example describes the differences between Eclipse ADT and Android Studio, including project structure, build system, and application packaging, and will help you migrate your Android Eclipse project to Android Studio as your new development environment. For our example will use the following tools in a Windows 64-bit or an OS X platform: • JDK 1.7 • Android Studio 1.3.2 • Eclipse 4.2 Juno • Android SDK Let’s start with a slice of Android Studio theory. . .

2.1

Why to use Android Studio over Eclipse ADT?

Android Studio offers: • Flexible Gradle-based build system • Build variants and multiple apk file generation • Code templates to help you build common app features • Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging and App Engine • Rich layout editor with support for drag and drop theme editing • lint tools to catch performance, usability, version compatibility, and other problem • Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging and App Engine • Official Google Support and usual updates that need no migration

Android Programming Cookbook

2.2

20 / 143

Android Studio new project structure

Eclipse provides workspaces as a common area for grouping related projects, configurations, and settings. In Android Studio, each instance of Android Studio contains a top-level project with one or more app modules. Each app module folder contains the equivalent to an Eclipse project, the complete source sets for that module, including src/main and src/androidTest directories, resources, build file, and the Android manifest. In general, to update and build your app you 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. Also due to the structural differences between Android Studio projects vs Eclipse ADT projects, they cannot co-exist. Here is a table of the main differences:

Figure 2.1: Eclipse - Android Studio Comparison

2.3

Gradle and build.gradle

Gradle is a build and automation tool, that can automate our building, testing, deploying tasks and many more. Gradle is the next generation build system for Java technologies that includes some advantages from older tools like Ant or Maven systems. Android Studio uses the power of Gradle, in order to provide all the above advantages, such as build variants and multiple apk file generation. Android Studio projects contain a top-level build file and a build file for each module. The build files are called build.gradle, and they are plain text files that use Groovy syntax to configure the build with the elements provided by the Android plugin for Gradle. In most cases, you only need to edit the build files at the module level. It looks like this: apply plugin: ’com.android.application’ android { compileSdkVersion 19 buildToolsVersion "19.0.0" defaultConfig { minSdkVersion 8 targetSdkVersion 19

Android Programming Cookbook

21 / 143

versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile(’proguard-android.txt’), ’proguard-rules. ←pro’ } } } dependencies { compile project(":lib") compile ’com.android.support:appcompat-v7:19.0.1’ compile fileTree(dir: ’libs’, include: [’*.jar’]) }

2.4

Simple Eclipse ADT project migration to Android Studio

Here, we have an example of this Eclipse ADT project migration to Android Studio. In this example, we are going to migrate the eclipse project that we created in this example: Android Google Maps v2 Tutorial. This is a wonderful example of how we are going to migrate a simple application project, that has a java class package and a Google Play Services library dependency. So, we are going to take this code, import it and compile it under Gradle system, and run it. Open Android Studio and choose "Start a new Android Studio Project" in the welcome screen.

Android Programming Cookbook

Figure 2.2: Welcome to Android Studio screen. Choose Start a new Android Studio Project. Specify the name of the application, the project and the package.

22 / 143

Android Programming Cookbook

Figure 2.3: "Configure your new project" screen. Add your application name and the projects package name. In the next window, select the form factors your app will run on.

23 / 143

Android Programming Cookbook

24 / 143

Figure 2.4: "Target Android Devices" screen. In the next window you should choose to "Add an activity to Mobile". In our example, we will choose to create a project with no activity, because we will migrate our Activities for the eclipse formed project. So, choose: "Add no activity".

Android Programming Cookbook

Figure 2.5: Add an activity to Mobile. Choose: Add no activity. Now, our project has just been created. This is how it looks like in the "Android" project view:

25 / 143

Android Programming Cookbook

Figure 2.6: A new Android Studio project has just been created. This is how it looks like.

26 / 143

Android Programming Cookbook

2.5

27 / 143

Java code and resources migration

As we discussed above, there are some pretty significant changes between the project structures between Eclipse ADT and Android Projects. The biggest is that both Java classes and the Android resources folder, are under app/src/main/ directory. We are going to copy our Java classes alone, inside the app/java/com.javacodegeeks.androidgooglemapsexam ple folder, as we see it in Android package view. After this, we are going to copy also our eclipse resources folders under app/res/ folder, as we see it in Android package view. If this suggest to overwrite some files and folders, we do it cautiously. We should now have something like this:

Android Programming Cookbook

Figure 2.7: This is how our projects looks like, after we have also moved inside our Java and resource folders.

28 / 143

Android Programming Cookbook

2.6

29 / 143

AndroidManifest.xml and build.gradle file

Then, we move on copying our AndroidManifest.xml file. In Android Studio project structure, we can find our manifest files inside the app/manifests folder. We overwrite the Android Studio project AndroidManifest.xml with our eclipse project manifest xml. We should now have something like this:

Figure 2.8: This is our AndroidManifest.xml. This is located in app manifests folder Finally, we have our build.gradle file, that we should be very careful in its configurations.

Android Programming Cookbook

30 / 143

Figure 2.9: Here is our build.gradle file. We write something like this: build.gradle apply plugin: ’com.android.application’ android { compileSdkVersion 22 buildToolsVersion "23.0.1" defaultConfig { applicationId "com.javacodegeeks.androidgooglemapsexample" minSdkVersion 14 targetSdkVersion 22

Android Programming Cookbook

31 / 143

versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile(’proguard-android.txt’), ’proguard-rules. ←pro’ } } } dependencies { compile fileTree(dir: ’libs’, include: [’*.jar’]) compile ’com.android.support:appcompat-v7:22.2.1’ compile ’com.google.android.gms:play-services:8.1.0’ }

With compile fileTree(dir:’libs’, include:[’*.jar’]) we add in our Gradle configuration, any external library we might have added in the app/libs project folder. And with the next line compile ’com.google.android. gms:play-services:8.1.0’ we add in our Gradle configuration the public repository in which Google supports Google Play Services library with Gradle. In this way we have added Google Play Services library in our project. This library is going to be compiled and packaged in our application project!

Figure 2.10: This is our build.gradle configuration file. We, now, have to sync our project, and run this module, by pressing the "run" green button. If everything is the right place, and especially the application package names are the right ones, then we should see our project run.

Android Programming Cookbook

32 / 143

Figure 2.11: This is the running confirmation screen. This was the Android Project migration from Eclipse to Android Studio example. This example was a theoretical one. From now on we are going to present examples in Android Studio IDE, as Google has stopped support on Eclipse ADT. Additionally, Android Studio is now the official Android IDE!

2.7

Download the Android Studio Project

This was an example of Android Google Maps v2 Tutorial migrated to Android Studio. Download You can download the full source code of this example here: AndroidGoogleMapsExampleAD

Android Programming Cookbook

33 / 143

Chapter 3

Android Google Maps v2 Tutorial The great power of mobile applications software, is that it gives us the opportunity to develop many ideas that use hardware features, in order to complete simple everyday tasks. One idea that is implemented in a very good way in the mobile applications world, is the use of maps and the location based applications, that help us in multiple ways in our every day life. So, the use of maps is very important in various mobile applications. Google provides via Google Play Services a library for using maps. This library is the second attempt of Google Maps and this version provides significant improvements to the older API version. So, in this example, we are going to work with Google Maps v2 and see how we will import a fully working map Fragment in an Activity, as well as, we are going to work with basic Markers and CameraPosition on Google Map. For our example will use the following tools in a Windows 64-bit or an OS X platform: • JDK 1.7 • Eclipse 4.2 Juno • Android SDK 4.4.2 Let’s take a closer look:

3.1

Create a Google Maps API key

To begin with, we should create a new Google Maps API key and subscribe our application in order to grant access for our application to succesfully use Google Maps v2. In order to use this API, we will have to enter the Google API console portal. If you do not have an account, just create one or login with your current Google account.

Android Programming Cookbook

34 / 143

Figure 3.1: Enter Google API Console After we enter the console, we are going to see the full list, of all the APIs that Google serves. Now we can see the enabled APIs that this console user has.

Figure 3.2: Figure 2. Go to APIs list After we enter the console,we are going to see the full list, of all the APIs that Google serves. The API that we are going to use,

Android Programming Cookbook

35 / 143

is the Google Maps v2 API. We click on the right service, and we turn it on. We have to accept the terms of Google Maps v2 API, by ticking the checkbox and by clicking the “Accept” button.

Figure 3.3: Enable Google Maps v2 API We should see the Google Maps v2 API enabled.

Figure 3.4: Google Maps v2 API enabled We are going to create a Public API access credential, in order to take the right response from the Google Places API search call.

Android Programming Cookbook

36 / 143

We only have to go to APIs&auth > Credentials tab.

Figure 3.5: Credentials Key We click the “Create new Key” button, and select the “Android Key” in order to make a Key that will both work from our Android Application and from our browser. We are going to do this, exclusively for our example scope. If you want to publish an application to the Google Play Store, that uses any of these Google API calls, you should create an Android key, by using the SHA-1 key of your original keystore (not the debug one) of the application to be exported.

Android Programming Cookbook

37 / 143

Figure 3.6: Create new Key We are going to do this, exclusively for our application scope. So we have to provide our application’s name and package. We have also to fill the SHA-1 cerificate fingerprint.

Android Programming Cookbook

38 / 143

Figure 3.7: Configure the allowed IPs If you are not familiar on how to get your SHA-1 cerificate fingerprint, the easiest way to reach this certificate, is inside your Eclipse IDE, from Window > Preferences > Android > Build.

Android Programming Cookbook

39 / 143

Figure 3.8: SHA-1 cerificate fingerprint on Eclipse

3.2

Create a New Android Application Project

Open Eclipse IDE and go to File → New → Project → Android Application Project.

Android Programming Cookbook

40 / 143

Figure 3.9: Create a new Android project Specify the name of the application, the project and the package and then click Next.

Android Programming Cookbook

41 / 143

Figure 3.10: Create a new Android project name In the next window, the “Create Activity” option should be checked. The new created activity will be the main activity of your project. Then press Next button.

Android Programming Cookbook

42 / 143

Figure 3.11: Configure the project In “Configure Launcher Icon” window you should choose the icon you want to have in your app. We will use the default icon of android, so click Next.

Android Programming Cookbook

43 / 143

Figure 3.12: Configure the launcher icon Select the “Blank Activity” option and press Next.

Android Programming Cookbook

44 / 143

Figure 3.13: Create the activity and select its type You have to specify a name for the new Activity and a name for the layout description of your app. The .xml file for the layout will automatically be created in the res/layout folder. It will also be created a fragment layout xml, that we are not going to use in this project and you can remove it if you want. Then press Finish.

Android Programming Cookbook

45 / 143

Figure 3.14: Create a new blank activity Here you can see, how will the structure of the project become when finished:

Android Programming Cookbook

46 / 143

Figure 3.15: The tree of the project

3.3

Importing Google Play Services in your project

In order to be able to work with Google Maps v2, we have to import the Google Play Services library in the project. Google Maps v2 will work only on devices that do have Google Play Services. If your mobile device does not have Google Play Services you have to download and use the Google Play Services application from Google Play. Download Google Play Services SDK. We have to launch Android SDK Manager and install the Google Play services package.

Android Programming Cookbook

47 / 143

Figure 3.16: Launch Android SDK Manager

Android Programming Cookbook

48 / 143

Figure 3.17: Download Google Play Services library

Android Programming Cookbook

Figure 3.18: Import the library as an existing Android project

49 / 143

Android Programming Cookbook

Figure 3.19: Import the library as an existing Android project

50 / 143

Android Programming Cookbook

51 / 143

Figure 3.20: Import completed. After downloading the Google Play Service package, just import this project into the main Android Google Maps v2 project.

3.4

Create the layout of the main Google Maps v2

We are going to make a simple layout xml for the AndroidGoogleMapsExample.java, that consists of a parent Relati veLayout and a child LinearLayout with vertical orientation, that includes a Google Map Fragment and a horizontal LinearLayout that includes 3 Buttons that lister to the corresponding actions. Open res/layout/activity_main.xml, go to the respective xml tab and paste the following: activity_main.xml
Android Programming Cookbook

52 / 143

android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.javacodegeeks.androidgooglemapsexample.AndroidGoogleMapsActivity" >
Loading...

Android Programming Cookbook

Android Programming Cookbook Android Programming Cookbook i Android Programming Cookbook ii Contents 1 2 Android Tutorial For Beginners 1 ...

8MB Sizes 95 Downloads 19 Views

Recommend Documents

jQuery Programming Cookbook - Web Code Geeks
Don't forget to download or link jQuery library, otherwise the code won't work. Other links of the jQuery UI are provide

Android Programming Tutorials - CommonsWare
Android Programming Tutorials by Mark L. Murphy. Copyright © 2009-2011 CommonsWare, LLC. All Rights Reserved. Printed i

Processing 2 Creative Programming Cookbook - The-Eye.eu!
Bourdon, Ryan Alexander, Matt Pearson, Bert Balcaen, Daniel Shiffman, .... You'll learn to save your sketches as an imag

Android Programming – Android Application Development PDF
Android Programming – Android Application Development PDF. ... Android-Entwicklung für Einsteiger - 20.000 Zeilen unt

COOKBOOK
General Tips for Cooking in the Microwave. • Distribute food equally on the plate to allow microwaves to cook food eve

Modern C++ Programming Cookbook Pdf Free Download | e-Books
Jun 23, 2017 - Explore the most important language and library features of C++17, including containers, algorithms, regu

Android tutorials for hassle-free android development and programming
Oct 20, 2017 - Android Tutorial Point is a one stop solution for hassle-free mastering the skills of android development

Tutorial: Java, Android Programming - OSU CSE
After installing JDK, download Android SDK from http://developer.android.com. • Simplest: download and install Android

Android Application Programming with OpenCV Pdf Download
Android Application Programming with OpenCV Pdf Download. ... for deblurring in OpenCV. Make a self driving toy car usin

Android Programming: Installation, Setup, and Getting Started
Install Java 6 JDK. – http://www.oracle.com/technetwork/java/javase/downloads/. • Scroll down for Java SE 6. Use thi