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

ANDROID 5 PROGRAMMING BY EXAMPLE

212 386 0

Đ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 212
Dung lượng 3,51 MB

Nội dung

With Android 5 Programming by Example, design and customize GUI using material design to create attractive and intuitive layouts easily. Bring your designs to life with Android 5’s powerful and extensive Java libraries, new sensors, and new platforms such as TVs, wearables, and cars. This is an examplebased guide to learn and develop applications for Android 5. Description Topics included: Setting Up the Development Environment • Building a UI • Activities and Fragments • Managing RecyclerViews and Their Data • Detecting Touchscreen Gestures • Notifications and the Action Bar • Maps, Locations, and Google Services • Apps for TVs, Cars, and Wearables • Camera, Video, and Multimedia • Publishing and Marketing.

Android Programming by Example Turn your ideas into elegant and powerful mobile applications using the latest Android Studio for the Android Lollipop platform Kyle Mew BIRMINGHAM - MUMBAI Android Programming by Example Copyright © 2015 Packt Publishing All rights reserved No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews Every effort has been made in the preparation of this book to ensure the accuracy of the information presented However, the information contained in this book is sold without warranty, either express or implied Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals However, Packt Publishing cannot guarantee the accuracy of this information First published: July 2015 Production reference: 1210715 Published by Packt Publishing Ltd Livery Place 35 Livery Street Birmingham B3 2PB, UK ISBN 978-1-78528-844-9 www.packtpub.com Credits Author Kyle Mew Reviewers Mustafa Gezen Project Coordinator Vijay Kushlani Proofreader Safis Editing Olivier Goutay Ten Wong Commissioning Editor Neil Alexander Acquisition Editor Vivek Anantharaman Content Development Editor Nikhil Potdukhe Technical Editors Ruchi Desai Chinmay S Puranik Copy Editors Ulka Manjrekar Swati Priya Indexer Mariammal Chettiyar Graphics Abhinash Sahu Production Coordinator Nilesh R Mohite Cover Work Nilesh R Mohite About the Author Kyle Mew has been programming since the early 80s and has written for several technology websites He has also written three radio plays and another book on Android development, Android 3.0 Application Development Cookbook, published by Packt Publishing I would like to thank Rhonda for the photographs About the Reviewers Mustafa Gezen is a Norwegian developer who develops applications for both Android and iOS devices His early experiences with programming have helped him develop amazing stuff He likes to take things apart and make them function differently He has experience in Python, Objective-C, Java, PHP and some other languages His main field of interest is runtime code modification I would like to thank my amazing family for supporting me in what I do, always believing in me, and putting their trust in me Olivier Goutay is an expert in Android application development With more than years of professional experience, he currently takes part in healthcare and open source Android developments in San Francisco He currently works for Omada Health, the lead start-up in chronic disease prevention in the U.S Before this, he was involved with major French and European Bank mobile services and developed tomorrow's technologies, which are now used by many people on their mobile devices His specialties are Android development, software security, software architecture, and iOS Ten Wong is an embedded software engineer at Seeed Studio, an open source hardware company He has years of experience in Android driver and framework He also has experience in TV Android app development and Arduino open source hardware shield I would like to thank my wife for supporting me in reviewing this book www.PacktPub.com Support files, eBooks, discount offers, and more For support files and downloads related to your book, please visit www.PacktPub.com Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub com and as a print book customer, you are entitled to a discount on the eBook copy Get in touch with us at service@packtpub.com for more details At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks TM https://www2.packtpub.com/books/subscription/packtlib Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library Here, you can search, access, and read Packt's entire library of books Why subscribe? • Fully searchable across every book published by Packt • Copy and paste, print, and bookmark content • On demand and accessible via a web browser Free access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view entirely free books Simply use your login credentials for immediate access Table of Contents Preface v Chapter 1: Setting Up the Development Environment What is Android 5? Lollipop from a user's perspective Lollipop from a developer's perspective Material Design Other devices Installing and configuring the development environment Installing the SDK Managing the SDK tools Creating a "Hello World" app Testing the app on a physical device Setting up a virtual device Monitoring devices Summary 2 3 11 11 13 14 Chapter 2: Building a UI 15 Chapter 3: Activities and Fragments 33 Applying a Material Design theme 16 Adding animated widgets 20 Designing an XML layout 20 Controlling the widget behavior with Java 25 Creating alternative layouts 29 Summary 31 Adding a CardView widget Adding images and text to the layout Creating a second Activity Applying Fragments Adding static Fragments [i] 34 37 40 43 49 Chapter 10 Distributing your app from your website is almost as simple as e-mailing it All you need to is host the APK file on your site somewhere and provide a download link along the lines of When browsing your site from an Android device, a tap on your link will install your app on their device Distribution by e-mail provides no protection against piracy and should only be used with this in mind The other methods are as secure as we could hope, but if you would like to take extra measures then Google offers a Licensing Service that can be found at developer.android.com/google/play/ licensing Whether we have released a paid app or a free one, we want to be able to reach as many users as possible Google provides several tools to help us with this, as well as ways to monetize our apps, as we shall see next Promoting and monetizing apps Very few apps become successful without first being well promoted There are countless ways to this and you will, no doubt, be well ahead of the curve on how to promote your products To help you reach a wider audience, Google provides some handy tools to assist with promotion After looking at promotion tools, we will explore two ways to make money from our app: in-app payments and advertising Promoting an app There are two very simple methods, provided by Google, to help steer people towards our products on the Play Store; links from both websites and our apps and the Google Play Badge, which provides official branding to our links We can add links to both individual apps and our publisher page, where all our apps can be browsed We can include these links in our apps as well as our websites • To include a link to a specific app's page in the Play Store, use the full package name, as found in the Manifest, in the following format: http://play.google.com/store/apps/details?id=com.full.package.name • To Include this within an Android app, use: market://details?id= com.my.full.package.name [ 179 ] Publishing and Marketing • If you want a link to your publisher page and a list of all your products, use: http://play.google.com/store/search?q=pub:my publisher name • Make the same changes as before when linking from an app: Market://search?q=pub:my publisher name • To link to a specific search result, use: search?q=my search query&c=apps • To use an official Google Badge as your link, replace one of the above elements with the highlighted HTML here: The Badge comes in two sizes, 60.png and 45.png, and two styles, "Android app on Google Play" and "Get it on Google Play" Simply change the relevant code to select the Badge that best suits your purpose With our app published and with well-placed links to our Play Store page, it is now time to consider how we can profit from the inevitable downloads, and so we come to how to monetize our Android app [ 180 ] Chapter 10 Monetizing an app There are many ways to make money from an app, but two of the most popular and effective are: in-app billing (IAB) and advertising In-app billing can become quite involved and perhaps deserves an entire chapter to itself Here, we will see how to build an effective template that you can use as a foundation for an in-app product you might develop It will include all the libraries and packages needed, along with some very useful helper classes Including Google AdMob advertisements in our apps is, in contrast, a very familiar process to us by now An ad is in effect just another View, and can be identified and referenced just like any other Android widget The final exercise of this chapter, and indeed this book, will be constructing a simple working AdMob demo First, though, let us take a look at in-app billing In-app billing There are a large number of products that users can purchase from within an app, from upgrades and unlockables to in-game objects and currencies Whatever the user is buying, the Google checkout process ensures they will pay in the same way as they pay for other Play Store products From the developer's point of view, each purchase will boil down to responding to the click of a button We will need to install the Google Play Billing Library, and add an AIDL file and some helper classes to our project Here is how: Start a new Android project or open one you want to add in-app billing to Open the SDK Manager Under Extras, make sure you have the Google Play Billing Library installed Open the manifest and apply the following permission: In the Project pane of the Studio, right click on app and select New | Folder | AIDL Folder [ 181 ] Publishing and Marketing From this folder as aidl, create a New | Package, and fill out the resultant dialog like so: Locate and copy the IinAppBillingService.aidl file in the sdk\extras\ google\play_billing directory Paste the file into the com.android.vending.billing package Create a New | Package in the Java folder, selecting \app\src\main\ java from the dialog box 10 Name the package com.your.package.name.util and click on Finish 11 From the play_billing directory, locate and open the TrivialDrive\src\ com\example\android\trivialdrivesample\util folder 12 Copy the nine Java files into the util package you just created You now have a working template for any app you wish to include on in-app purchasing Alternatively, you can complete the above steps on a project where you have already developed your in-app products Either way, you will no doubt be taking advantage of the IabHelper class, which vastly simplifies the coding, providing listeners for every step of the purchasing process Documentation on IAB can be found at http://developer.android.com/google/play/billing/ billing_reference.html Before you can start to implement in-app purchases, you will need to secure a License Key for your app This can be found in the app's details in your developer console Paid apps and in-app products are just two ways to make money from an app, and many people choose another, and often lucrative, route for monetizing their work through advertising Google AdMob allows for a great deal of flexibility and a familiar programming interface, as we shall see next [ 182 ] Chapter 10 Including an advertisement There are many ways that we can earn money from advertising, but AdMob provides one of the easiest Not only does the service allow you to select what types of product you wish to advertise but it also provides great analytical tools and seamless payment into your Checkout account On top of this, an AdView can be treated programmatically in a way that is almost identical to the methods we are used to and familiar with, as we shall see in this final exercise where we will develop a Hello World app with a demo banner AdMob ad Before you start this exercise, you will need to have signed up for an AdMob account at http://www.google.com/admob/ Open a project you want to test ads on or start a new Android project Make sure you have the Google Repository installed with the SDK Manager In the build.gradle file, add this dependency: compile 'com.google.android.gms:play-services:7.0.+' Rebuild the project In the manifest, set these two permissions: Within the application node, add this meta-data tag: Include this second Activity to the manifest: Add the following string to the res/values/strings.xml file: ca-app-pub-3940256099942544/6300978111 Open the main_activity.xml layout file [ 183 ] Publishing and Marketing 10 Add this second namespace to the root layout: xmlns:ads="http://schemas.android.com/apk/res-auto" 11 Add this AdView under the TextView: 12 In the onCreate() method of the MainActivity, insert these lines: AdView adView = (AdView) findViewById(R.id.ad_view); AdRequest adRequest = new AdRequest.Builder() addTestDevice(AdRequest.DEVICE_ID_EMULATOR) build(); adView.loadAd(adRequest); 13 Now test the app on a device [ 184 ] Chapter 10 More or less everything we did here resembles the way that we would program any other element, with one or two exceptions The use of the ACCESS_NETWORK_STATE permission is not strictly necessary; it is used here to check for a connection prior to requesting an ad Any Activity that displays an ad will require a separate ID and be declared in the manifest The ID supplied here is for testing purposes only and it is forbidden to use live IDs for testing purposes There are only six classes in the android gms.ads package and documentation for all of them can be found at https:// developers.google.com/android/reference/com/google/android/gms/ads/ package-summary AdMob ads come in two flavors, the banner that we saw here and the interstitial, or full screen We only dealt with banner ads here but interstitial ads are handled in a very similar manner With a knowledge of how to implement paid apps, in-app billing and AdMob, we are now armed to reap the rewards of our hard work and make the very most of our apps Summary In this chapter, we have covered the final aspect of the app development process: packaging and deployment We began by making our apps backward-compatible, including many of the features we had originally designed for Android 5; by doing, so we were able to reach a far wider audience We continued by preparing and then publishing our app in the Google Play Store Once published, we saw how easy it is to promote and then monetize an Android app This concludes our journey into the world of Android development We have gone from installation to publication and hopefully covered most of the components required for the apps that you are planning If you are new to developing or IDEs such as the Android Studio and have worked your way through this book, then what was previously a daunting set of tools will now seem like a familiar and productive place to work The Android platform will, no doubt, continue to flourish and develop in new and unexpected ways Android is the perfect entry point; with Material Design at its core and the most powerful set of mobile APIs available, things can only get better and brighter for Android developers [ 185 ] Index Symbol "Hello World" app creating 9-11 testing, on physical device 11 A Action Bar 33 Activity adding 70 creating 40-43 landscape layout, creating 72-74 portrait layout, creating 70-72 Views, connecting to web pages 75-77 Adapter creating 66-69 AdMob about 183 URL 183 AIDL file 181 alternative layouts creating 29-31 Android about 1, developer's perspective reference link user's perspective 2, Android Auto about 144 apps, designing 145, 146 references 145 safety rules 144 simulators, installing 146, 147 Android Debug Bridge 129 Android Device Monitor about 13, 147 used, for monitoring virtual device 13, 14 android.gms.ads package URL 185 Android TV about 142 TV compatible app, building 142-144 Android Wear about 128 sensor data, accessing 139-141 UI for wearables, designing 133 URL 129 wearable AVD, connecting to 128-130 wearable AVD, constructing 128-130 wearable project, creating 131, 132 animated widgets adding 20 widget behavior, controlling with Java 25-29 XML layout, designing 20-24 AppCompat 173 apps distributing, by e-mail and websites 178, 179 making, backward compatible 168 monetizing 179-181 promoting 179, 180 publishing 174 publishing, on Google Play Store 177, 178 v7 Support Libraries, adding 169, 170 audio playing 163-166 recording 163-166 [ 187 ] B Broadcasts 43 C camera2 APIs about 161-163 exploring 161-163 CardView about 34, 170 adding 34-37 adding, with layout 59-62 images, adding to layout 37-40 text, adding to layout 37-40 click listener 69 D Dalvik Debug Monitor Server (DDMS) about 85 gesture activity, viewing 85-87 dataset adding 63-66 dates adding 103-106 developer's perspective, Android Material Design other devices support support for auto support for TV support for wearables development environment configuring installing SDK, installing 5, SDK tools, managing 6-8 double-taps 79 E e-mail apps, distributing 178, 179 F filter 87 flings 79 FragmentManager about 48 URL 48 FragmentPagerAdapter adding 99-103 Fragments about 95 applying 43-48 static Fragments, adding 49 FragmentTransaction about 48 URL 48 FrameLayout 48 Full-Screen Activity 94 G GestureDetector, adding to Activity GestureDetector, adding 92-94 Manifest, editing 91, 92 splash screen layout, designing 89, 90 steps 88 GestureDetector, adding to view gallery data, adding 80 gesture activity, viewing with DDMS 85-87 GestureDetector, adding 81-85 SimpleOnGestureListener, implementing 88 steps 80 Google AdMob 181, 182 Google Maps animating 124, 125 used, for building location aware app 114 Google Play Badge 179 Google Play Billing Library 181 Google Play Developer 174 Google Play Policies and Agreements 174 Google Play Store apps, publishing 177, 178 Google Services APIs URL 113 H hardcoded strings 47 heads-up notifications about 106 issuing 111, 112 [ 188 ] I long presses 79 icon adding 107-109 images adding, to layout of CardView widget 37-40 camera output, previewing 152, 153 camera output, saving 154-156 capturing 150 code, refactoring 150-152 in-app billing (IAB) about 181 advertisement, including 183-185 reference link 182 using 181, 182 intents 43 M J notification bar 95 notifications expanding 110, 111 heads-up notifications, issuing 111, 112 icon, adding 107-109 lock screen notifications, issuing 111, 112 priority settings, assigning 106 programming 106 standard notification, adding 107-109 visibility settings, assigning 106 Manifest editing 91, 92 Material Design about 15 applying, to older platforms 171-174 theme, applying 16-20 Material Jelly Bean 171 Material Toolbar 174 menus adding 49-51 menu items, adding to menu XML files 51 N Java used, for controlling widget behavior 25-29 JDK URL, for downloading Jelly Bean 168 K KitKat 168 L LayoutManager adding 62, 63 Leanback Support Library 144 License Key securing 182 location aware app API Key, acquiring 114-117 building, with Google Maps 114 Google Map, animating 124, 125 Google Map, moving around 124, 125 last known location, acquiring 118-120 location updates, requesting 121-124 lock screen notifications issuing 111, 112 Log Tag 87 Lollipop See  Android O OnClickListener about 48 creating 69 Options menu 49 R RecyclerView about 170 Activity, adding 70 CardView, adding with layout 59-62 creating 58 dataset, adding 63-66 LayoutManager, adding 62, 63 OnClickListener, creating 69 responding 69 RelativeLayout 24 [ 189 ] S SDK installing 5, tools, managing 6-8 URL, for downloading sensor simulator URL 140 services 43 signed APK apps, publishing on Google Play Store 177, 178 generating 175, 176 registering, as developer 176, 177 Signed Release APK 174 SimpleOnGestureListener implementing 88 splash screen layout designing 89, 90 standard notification adding 107-109 static Fragments adding 49 support library (v4) 99 Unicode Technical Standards (UTS) about 106 URL 106 V v7 AppCompat r21 168 v7 support libraries adding 169, 170 video camera2 APIs, exploring 161-163 capturing 157-159 playing 157-159 playing, from internet 160, 161 playing, from memory 160, 161 ViewGroup 24 ViewPager adding 99-103 constructing 96 layout, creating 96-99 virtual device monitoring, with Android Device Monitor 13, 14 setting up 11-13 T W tabs adding 103-106 TaskStackBuilder 109 text adding, to layout of CardView widget 37-40 theme applying 16-20 toolbar adding 49-51 configuring 52-54 touchscreen gestures detecting 79 wearable AVD connecting to 128-130 connecting, with another emulator 130, 131 constructing 128-130 Wearable UI Library 133 Wear app about 176 URL 176 websites apps, distributing on 178, 179 U X XML layout designing 20-24 UI, for wearables cards, adding 135-137 cards, customizing 137-139 designing 133 layout, designing 133-135 [ 190 ] Thank you for buying Android Programming by Example About Packt Publishing Packt, pronounced 'packed', published its first book, Mastering phpMyAdmin for Effective MySQL Management, in April 2004, and subsequently continued to specialize in publishing highly focused books on specific technologies and solutions Our books and publications share the experiences of your fellow IT professionals in adapting and customizing today's systems, applications, and frameworks Our solution-based books give you the knowledge and power to customize the software and technologies you're using to get the job done Packt books are more specific and less general than the IT books you have seen in the past Our unique business model allows us to bring you more focused information, giving you more of what you need to know, and less of what you don't Packt is a modern yet unique publishing company that focuses on producing quality, cutting-edge books for communities of developers, administrators, and newbies alike For more information, please visit our website at www.packtpub.com About Packt Open Source In 2010, Packt launched two new brands, Packt Open Source and Packt Enterprise, in order to continue its focus on specialization This book is part of the Packt Open Source brand, home to books published on software built around open source licenses, and offering information to anybody from advanced developers to budding web designers The Open Source brand also runs Packt's Open Source Royalty Scheme, by which Packt gives a royalty to each open source project about whose software a book is sold Writing for Packt We welcome all inquiries from people who are interested in authoring Book proposals should be sent to author@packtpub.com If your book idea is still at an early stage and you would like to discuss it first before writing a formal book proposal, then please contact us; one of our commissioning editors will get in touch with you We're not just looking for published authors; if you have strong technical skills but no writing experience, our experienced editors can help you develop a writing career, or simply get some additional reward for your expertise Near Field Communication with Android Cookbook ISBN: 978-1-78328-965-3 Paperback: 286 pages Discover the endless possibilities of using Android NFC capabilities to enhance your apps over 50 practical recipes Practical and real-life examples showing how and where NFC can be used Discover how to exploit NFC capabilities to enhance your apps to easily share and interact with the world Learn how to extend cross-device content sharing by taking advantage of Android Beam's capabilities Building Android Games with Cocos2d-x ISBN: 978-1-78528-383-3 Paperback: 160 pages Learn to create engaging and spectacular games for Android using Cocos2d-x Create fun physics games to rival the bestselling games on Google Play Save time by creating your Android games using this integrated framework Learn to create a simple game using step-by-step instructions provided throughout the book Please check www.PacktPub.com for information on our titles Learning Android Intents ISBN: 978-1-78328-963-9 Paperback: 318 pages Explore and apply the power of intents in Android application development Understand Android Intents to make application development quicker and easier Categorize and implement various kinds of Intents in your application Perform data manipulation within Android applications Building Android Games with OpenGL ES [Video] ISBN: 978-1-78328-613-3 Duration: 01:42 hours A comprehensive course exploring the creation of beautiful games with OpenGL ES Create captivating games through creating simple and effective codes in Java Develop a version of the classic game Breakout and see how to monetize it Step-by-step instructions and theoretical concepts describe each activity before you implement them Please check www.PacktPub.com for information on our titles .. .Android Programming by Example Turn your ideas into elegant and powerful mobile applications using the latest Android Studio for the Android Lollipop platform Kyle Mew BIRMINGHAM - MUMBAI Android. .. 181 Including an advertisement 183 Summary 1 85 Index 187 [ iv ] Preface Welcome to Android Programming by Example, a step -by- step guide to developing Android mobile apps for the Lollipop platform... Connecting Views to web pages 57 58 59 62 63 66 69 69 70 70 72 75 Summary 78 Chapter 5: Detecting Touchscreen Gestures 79 Chapter 6: Notifications and the Action Bar 95 Adding a GestureDetector

Ngày đăng: 14/07/2017, 14:35

TỪ KHÓA LIÊN QUAN