Mastering Android Studio

Transcription

Mastering AndroidStudio

Mastering Computer ScienceSeries Editor: Sufyan bin UzayrMastering Android Studio: A Beginner’s GuideDivya Sachdeva and Reza NafimMastering Swift: A Beginner’s GuideMathew Rooney and Madina KarybzhanovaMastering C : A Beginner’s GuideDivya Sachdeva and Natalya UstukpayevaMastering Git: A Beginner’s GuideSumanna Kaul, Shahryar Raz, and Divya SachdevaMastering Ruby on Rails: A Beginner’s GuideMathew Rooney and Madina KarybzhanovaMastering Sketch: A Beginner’s GuideMathew Rooney and Md Javed KhanFor more information about this series, please visit: https://w w ries/MCSThe “Mastering Computer Science” series of books areauthored by the Zeba Academy team members, led bySufyan bin Uzayr.Zeba Academy is an EdTech venture that developscourses and content for learners primarily in STEMfields, and offers education consulting to Universities andInstitutions worldwide. For more info, please visit https://zeba.academy

Mastering AndroidStudioA Beginner’s GuideEdited by Sufyan bin Uzayr

First edition published 2022by CRC Press6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742and by CRC Press2 Park Square, Milton Park, Abingdon, Oxon, OX14 4RNCRC Press is an imprint of Taylor & Francis Group, LLC 2022 Sufyan bin UzayrReasonable efforts have been made to publish reliable data and information, but theauthor and publisher cannot assume responsibility for the validity of all materials orthe consequences of their use. The authors and publishers have attempted to tracethe copyright holders of all material reproduced in this publication and apologize tocopyright holders if permission to publish in this form has not been obtained. If anycopyright material has not been acknowledged please write and let us know so we mayrectify in any future reprint.Except as permitted under U.S. Copyright Law, no part of this book may be reprinted,reproduced, transmitted, or utilized in any form by any electronic, mechanical, or othermeans, now known or hereafter invented, including photocopying, microfilming, andrecording, or in any information storage or retrieval system, without written permissionfrom the publishers.For permission to photocopy or use material electronically from this work, access www.copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222 RosewoodDrive, Danvers, MA 01923, 978-750-8400. For works that are not available on CCCplease contact mpkbookspermissions@tandf.co.ukTrademark Notice: Product or corporate names may be trademarks or registeredtrademarks and are used only for identification and explanation without intent toinfringe.ISBN: 978-1-032-13412-3 (hbk)ISBN: 978-1-032-13411-6 (pbk)ISBN: 978-1-003-22907-0 (ebk)DOI: 10.1201/9781003229070Typeset in Minionby KnowledgeWorks Global Ltd.

ContentsAbout the Editor, xiiiChapter 1        Introduction to Android Studio1WHAT IS ANDROID STUDIO4MAJOR FEATURES8The User Interface9Tool Windows10Navigation12Style and Formatting14Version Control Basics15Gradle Build System15Build Variants16Multiple Android Application PackageSupport16Resource Shrinking17Managing Dependencies17Debug and Profile Tools17Performance Profilers18v

vi        ContentsHeap Dump18Memory Profiler18Data File Access19Code Inspections19Annotations in Android Studio19Log Messages20Sign in to Your Developer Account20A BRIEF HISTORY OF ANDROID STUDIO20ADVANTAGES OF ANDROID DEVELOPMENT25DISADVANTAGES OF ANDROIDDEVELOPMENT25EXPLORING ANDROID STUDIO31Chapter 2        Getting Started with AndroidStudioINSTALLATION AND CONFIGURATION3334Windows34Mac35Linux36Chrome OS37Customizing Your VM Options40Customizing Your IDE Properties42Configuring the IDE for Low-MemoryMachines43Setting the JDK Version44Proxy Settings45

Contents        viiAndroid Plugin for Gradle HTTP ProxySettingsTHE USE OF GRADLE BUILD SCRIPTS4648Sensible Defaults49Dependencies50Build Variants51Manifest Entries51ProGuard Support51Changing Default Source Set Configurations54Managing Libraries and Dependencies55Creating Different Versions of Your App55Configuring Instrumentation ManifestSettings56Configuring Gradle Test Options56WORKING WITH PROJECTSModules6161Android App Module62Feature Module63Library Module63Google Cloud Module63Project Files64Project Structure Settings66Choosing Your Project70Configuring Your Project70Import an Existing Project71Feature Module Build Configuration71

viii        ContentsEstablish a Relationship to the Base Module72Specify Additional ProGuard Rules73Deploy Your App74Use Feature Modules for Custom Delivery75Building a URI for a Resource76Considerations for Feature Modules79Chapter 3        Android Studio Basics85ANDROID STUDIO UI86TERMS AND FOLDERS89Splitting the Action Bar92Hiding the Action Bar93Overlaying the Action Bar94LAYOUTS95Layout Position96Types of Android Layout98Using UI Elements in the XML File99Inspect Your Layout102Revise Your Layout102Use Lint103Creating a Re-Usable Layout104Use the include Tag106Use the merge Tag107STRINGS108String109String Array110

Contents        ixQuantity Strings (Plurals)Handling Special CharactersFormatting StringsVIEWS110113115118The Basic Approach119Fully Customized Components120Extend onDraw() and onMeasure()121Subclass a View125Define Custom Attributes126Apply Custom Attributes128Add Properties and Events129Design for Accessibility131Chapter 4        Android Studio ToolsTHE SDK MANAGERInstalling the Android SDK (Automated Way)133134135Installing for Ubuntu Linux135Installing via Homebrew135Installing the Android SDK (Manual Way)136Installing via the GUI137Installing via the Command Line138Anatomy of the Android SDK139Using the ADB141The Android Emulator143

x        ContentsInstall and Add Files146Snapshots147Using the SDK Independently148THE AVD MANAGER150System Images150Storage Area151Skin151Creating an AVD151Creating a Hardware Profile153THE NAVIGATION EDITOR159Gradle Plugins161Navigation oller169SafeArgs170GENERATING A JAVADOC170Adding a New Comment173Add a Javadoc Using Context Actions173Disable Automatic Comments174Fix a Javadoc174Render Javadocs174Render Javadocs by Default175Generate a Javadoc Reference175View Javadocs in the Editor176Troubleshoot176

Contents        xiChapter 5        DebuggingRUNNING AND DEBUGGING179180Debug Window Frames185Inspect Variables185View and Change Resource Value DisplayFormat186About Run/Debug Configurations188Default Run/Debug Configuration188Symbol Directories191LLDB Startup Commands192LLDB Post Attach Commands192Logging: Target Channels193Miscellaneous TabANDROID DEVICE MONITOR193194Dalvik Debug Monitor Server (DDMS)195Traceview196Systrace196Hierarchy Viewer198Pixel Perfect199Network Traffic Tool199IMPORTANT SHORTCUTS AND BUTTONTECHNIQUES201General201Navigating and Searching Within Studio202Viewing Layouts204Design Tools: Layout Editor204

xii        ContentsDesign Tools: Navigation Editor205Writing Code205Build and Run208Debugging209Refactoring209Version Control/Local History210Compile Options213Link Options214Environment Variables219Android Studio Configuration EnvironmentVariables221Emulator Environment Variables221adb Environment Variables223ADB Logcat Environment Variables223How to Set Environment Variables224APPRAISAL, 227INDEX, 237

About the EditorSufyan bin Uzayr is a writer, coder, and entrepreneur withmore than a decade of experience in the industry. He hasauthored several books in the past, pertaining to a diverserange of topics, ranging from History to Computers/IT.Sufyan is the Director of Parakozm, a multinational ITcompany specializing in EdTech solutions. He also runsZeba Academy, an online learning and teaching verticalwith a focus on STEM fields.Sufyan specializes in a wide variety of technologies,such as JavaScript, Dart, WordPress, Drupal, Linux, andPython. He holds multiple degrees, including ones in management, IT, literature, and political science.Sufyan is a digital nomad, dividing his time betweenfour countries. He has lived and taught in universities andeducational institutions around the globe. Sufyan takes akeen interest in technology, politics, literature, history, andsports, and in his spare time, he enjoys teaching codingand English to young students.Learn more at sufyanism.com.xiii

Chapter1Introduction toAndroid StudioIN THIS CHAPTER Getting to know the history of the Android platform Learning about Android Studio major benefits Reviewing Android Studio main features andcharacteristicsAs a modern user, your choice of products can mean thedifference between struggling and prospering. It is normalalways to be searching for tools that increase productivity and optimize work. Specific tools have advantagesthat are so obvious that one adopts them immediately.Android Studio is one of them. The world was introducedto Android Studio just a few days after its prerelease atDOI: 10.1201/9781003229070-11

2        Mastering Android StudioGoogle’s processing system in 2013. Before that premiered,we had been using Android Developer Tools (ADT) bothprofessionally and as a learning tool. ADT is an Androiddevelopment environment built upon the open-sourceintegrated development environment (IDE) called Eclipse.Android Studio is a product of a great collaboration between JetBrains and Google. Android Studio wasbuilt over JetBrain’s IntelliJ, meaning that its functionality is a superset of IntelliJ. Almost anything you can dowith IntelliJ, you should be able to do in Android Studio.Android Studio is revolutionary in the field because itstreamlines the Android development process and makesAndroid development far more approachable than it haspreviously been.Android Studio is now the official IDE for Android.The Android platform lets developers script managed codeapplying Java to operate and control the Android device.At the same time, Android Studio has replaced Eclipse asthe IDE of choice for developing Android applications.Previously, the Android development was spread using

Introduction to Android Studio        3the Eclipse platform with the Android Development Kit(ADK), provided by Google, which launched the AndroidStudio platform. The Android Studio IDE has some greatadvantages, for instance, the Gradle dependency manager,also based on IntelliJ, which is widely used all over theworld. This application is one of the great strengths of theplatform editor as it offers more options to the developer atbuild time.Android Studio can be installed on Windows, OSX,and Linux operating systems. In addition, it is recommended by Google itself that the hardware must have atleast 4 GB of memory and 1 GB of free hard disk spacebecause, otherwise, Android Studio might be a little slow.You should also have Java installed on the machine via theJava Development Kit (JDK) since to develop on Android,and it is necessary for all Java development classes to bepresent on the machine.Prior to its release, Android development was managedpredominantly through Eclipse IDE, which offered a moregeneric Java IDE that with numerous other programminglanguages.Now, it is safe to claim that Android Studio can makeanyone’s life significantly easier compared with nonspecialist software, but at the same time it still has a longway to go before it can certainly state to be a completelyintuitive and smooth experience. For complete beginners,there is a lot to learn here, and much of the informationavailable—even through official channels—can seem toodense to absorb at first.This chapter will explain in a little more detail whatAndroid Studio does and go over the basic functionality

4        Mastering Android Studiothat you need to get started. We aim to keep everything aseasy as possible, and hopefully, this will serve as the firststep on your journey to Android development.WHAT IS ANDROID STUDIOThose of you without any prior experience in coding maybe wondering about what exactly the Android Studio’s roleis when it comes to the development and what an IDE hasto do with that anyway?To start with, the Android Studio’s responsibility is toprovide the interface for you to create your applications andto operate much of the complex file management behind thescenes. The programming language you will be expected touse is either Java or Kotlin. If you opt for Java, this shouldbe installed separately on your machine. Android Studiois simply a canvas where you will write, edit, and saveyour projects and the files that make up those projects. Atthe same time, Android Studio will give you access to theAndroid Software Development Kit (SDK). This should beviewed as an extension to the Java code that allows it torun smoothly on Android devices and take advantage ofthe native hardware. To put it simply, Java is necessary toscript the programs, the Android SDK is needed to makethose programs run on Android, and Android Studio hasthe job of assembling it all together for you. On the otherhand, Android Studio also enables you to run your codethrough an emulator so that you will be able to “debug” theprogram as it operates and get feedback explaining crashesso that you can solve that problem faster.Google has accomplished a great deal making AndroidStudio as powerful and useful as possible. For instance,

Introduction to Android Studio        5they have added live hints so that while you are coding,you will get suggestions to make necessary changes thatcan fix errors or make your code sharper. Moreover, in casea variable is not being used, it will be highlighted in grey.And once you start typing a line of code, Android Studiowill provide a list of autocomplete suggestions to help youfinish it, which is great for when you cannot quite remember the correct syntax or you just want to save some time.The following is a list of Android Studio’s major releases1:Version-Release .41.31.21.11.01May 2021October 2020May 2020February 2020August 2019April 2019January 2019September 2018March 2018October 2017March 2017September 2016April 2016April 2016November 2015September 2015July 2015April 2015February 2015December 2014https://developer.android.com/studio/releases, Android

6        Mastering Android StudioTABLE 1.1 Basic System Randomaccessmemory(RAM)Free digitalstorageMinimumrequired JDKversionMinimumscreenresolutionMacLinuxGNOME or KDEMac OS XMicrosoftdesktopWindows 7/8/10 10.10(Yosemite) Tested on gLinux(32- or 64-bit)based on Debianor higher,The Android(4.19.67-2rodete2).up to 10.14Emulator only(macOSsupports 64-bitMojave)Windows.4 GB RAM minimum; 8 GB RAM recommended.2 GB of available digital storage minimum, 4 GBrecommended (500 MB for IDE 1.5 GB forAndroid SDK and emulator system image).Java Development Kit 81280 800In addition, prior to installing the tool, it is recommendedto see if you comply with the following basic systemrequirements shown in Table 1.12:Android Studio contains great tools such as the AndroidVirtual Device Manager and the Android Device Monitor.It also has Gradle toolkit that lets you automate and manage the build process, allowing you to determine flexible2https://developer.android.com/studio, Android

Introduction to Android Studio        7custom build configurations. Other key features of AndroidStudio include the following: Support for a fast emulator Support for plenty of code templates and GitHubintegration Support for template-based wizards for creatingAndroid designs and components Support for rich layout editor Support for deep code analysis Support for an extensive set of tools and frameworksOn top of that, there are certain IntelliJ’s code editor features that can enhance your productivity when buildingAndroid apps, such as: A unified environment where you can develop for allAndroid devices Apply changes to push code and resource changes toyour running app without restarting your app Lint tools to catch performance, usability, versioncompatibility, and other problems C and Native Development Kit (NDK) support Built-in support for Google Cloud Platform, makingit easy to integrate Google Cloud Messaging and AppEngine

8        Mastering Android StudioMAJOR FEATURESEvery project started in Android Studio contains one ormore modules with source code files and resource files.Standard types of modules include Android app modules,Library modules, and Google App Engine modules.Normally, Android Studio displays project files in theAndroid project view to provide quick access to your project’s key source files. Thus, all the build files should bevisible at the top level under Gradle Scripts, and each appmodule should have the following folders: Manifests holds the AndroidManifest.xml file. Java holds the Java source code files, including JUnittest code. Res holds all non-code resources, such as XML layouts, UI strings, and bitmap images.The Android project architecture on disk is different fromthe typical flattened representation. It is also possible tocustomize the view of the project files to focus on specificaspects of your app development. For instance, selectingthe Problems view of your project displays links to thesource files holding any recognized coding and syntaxerrors, such as a missing XML element closing tag in a layout file.

Introduction to Android Studio        9The User InterfaceThe Android Studio main window consists of several mainlogical areas: The toolbar allows you to carry out a wide range ofactivities, such as running your app and launchingAndroid tools. The navigation bar helps you to revise the project andselect certain files for editing. It gives a more compact view of the overall structure visible in the projectwindow. The editor window is where you script and edit code.Depending on the current file type, the editor can bemodified. For example, when viewing a layout file,the editor shows the Layout Editor.

10        Mastering Android Studio The tool window bar runs around the outside of theIDE window and contains the buttons that let youexpand or shrink individual tool windows. The tool windows give you access to specific taskslike project management, search, and version control.You can also expand or shrink them. The status bar is used to review the status of yourproject as well as the IDE, including all the warningsand messages.Keep in mind that you can organize the main windowto give yourself more screen space by hiding or movingtoolbars and tool windows. You can also insert keyboardshortcuts to access most IDE functions.Also, at any time, you can activate the search optionacross your source code, databases, actions, and elementsof the user interface, just by double-pressing the Shift keyor clicking the magnifying glass icon in the upper righthand corner of the Android Studio window. This can bevery helpful if you are trying to locate a particular IDE feature that you have forgotten how to activate.Tool WindowsInstead of using preset options, Android Studio follows theoriginal context to be able to automatically bring up relevant tool windows as you work. By default, the most commonly sought tool windows are pinned to the tool windowbar at the edges of the application window. To expand or collapse a tool window, click the tool’sname in the tool window bar. Here, you can also

Introduction to Android Studio        11choose to drag, pin, unpin, attach, or detach toolwindows. To return to the current default tool window layout,click Window Restore Default Layout or customize your default layout by clicking Window StoreCurrent Layout as Default. To show or hide the entire tool window bar, click thewindow icon in the bottom left-hand corner of theAndroid Studio window. To locate a specific tool window, go over the windowicon and select the tool window from the menu.Or as an alternative, you can also use keyboard shortcutsto open tool windows3:Tool windowWindows and LinuxMac1. Project2. Version Control3. Run4. Debug5. Logcat6. Return to Editor7. Hide All ToolWindowsAlt 1Alt 9Shift F10Shift F9Alt 6EscControl Shift F12Command 1Command 9Control RControl DCommand 6EscCommand Shift F12In case you need to hide all toolbars, tool windows, andeditor tabs, click View Enter Distraction Free Mode. Thiswill enable Distraction Free Mode. And in order to exit3https://developer.android.com/studio/intro, Android

12        Mastering Android StudioDistraction Free Mode, click View Exit Distraction FreeMode.You can also activate Speed Search to search and filterwithin most tool windows in Android Studio. To use SpeedSearch, select the tool window and then type your searchquery.In addition, Android Studio also has three types of codecompletion, which you can access using the following keyboard shortcuts given in Table 1.24:It is also possible to complete quick fixes and showintention actions by pressing Alt Enter. Additionally, theCode Sample Browser in Android Studio can help you lookfor high-quality, Google-provided Android code samplesbased on the currently highlighted symbol in your project.NavigationWe shall cover the navigation option in depth later inChapter 4 of this book. But the basic features include thefollowing:You can switch between your recently accessed filesapplying the Recent Files action. To bring up the RecentFiles action press Control E (Command E on a Mac) andby default, the last accessed file will be selected. You canalso access any tool window through the left column in thisaction.In case you need to view the structure of the current file, youcan use the File Structure action. Bring up the File Structureaction by pressing Control F12 (Command F12 on a Mac)and quickly navigate to any part of your current file.4https://developer.android.com/studio/intro, Android

Mastering Android Studio: A Beginner's Guide Divya Sachdeva and Reza Nafim Mastering Swift: A Beginner's Guide Mathew Rooney and Madina Karybzhanova Mastering C : A Beginner's Guide Divya Sachdeva and Natalya Ustukpayeva Mastering Git: A Beginner's Guide Sumanna Kaul, Shahryar Raz, and Divya Sachdeva