You are on page 1of 350
Android Programming AS PER NEW SYLLABUS OF GUJARAT TECHNOLOGICAL UNIVERSITY SEM VIII (CE/CSE/IT) ELECTIVE-IIt SIMPLIFIED APPROACH SOLVED UNIVERSITY QUESTION PAPERS SUMMER 2017 to SUMMER 2018 TECHNICAL PUBLICATIONS a ar ANDROID PROGRAMMING Hitesh P. Patel MTech. (Computer Science and Engineering) HOD Information Technology Department, Hosmukh Goswami College of Engineering, Vahelal = TECHNICAL zg PUBLICATIONS ‘Website : www.technicalpublications.org An Up-Thrust for Knowledge ‘Bihttps://www.facebook.com/technicalpublications o ANDROID PROGRAMMING Semester - Vill (CE/CSE/ IT) Elective - IIL Fist Elon: February 201 8 Second Revised Editon : January 2019 © Copyright with Author A publishing rights (printed and ebook version) reserved with Technical Publications, No part of this book should be reproduced in any form, Electronic, Mechanical, Photocopy or any information storage and retrieval system without prior permission in writing, from Technical Publications, Pune. ha A ee - TECHNICAL’ hvevtaisstoasy ass stsoeauss PUBLICATIONS." ssseroncapDiensey Moe eieansineeerson Printer : Yossi Piotes & Baden SENS TOA, Gd ndil Ease, Nnded Vile Ros, Tl Hoveh, Det Pane 417041 Price :€270/- ISBN 978-93-982-1778-1 789333 il Come 13 9789333917781 [2] wo PREFACE The importance of Android Programming is well known in various engineering fields. Overwhelming response to my books on various subjects inspired us to write this book. ‘The book is structured to cover the key aspects of the subject Android Programming. The book uses plain, fucid language to explain fundamentals of this subject. The book provides logical method of explaining various complicated concepts and stepwise methods to explain the important topics. Each chapter is well supported with necessary illustrations, practical examples and solved problems. All the chapters in the book are arranged in a proper sequence that permits each topic to build upon earlier studies. All care has been taken to make students comfortable in understanding the basic concepts of the subject The book not only covers the entire scope of the subject but explains the philosophy of the subject. This makes the understanding of this subject more clear and makes it more interesting. The book will be very useful not only to the students but also to the subject teachers. The students have to omit nothing and possibly have to cover nothing more. I wish to express our profound thanks to all those who helped in making this book a reality, Much needed moral support and encouragement is provided on numerous occasions by my whole family. I wish to thank the Publisher and the entire team of Technical Publications who have taken immense pain to get this book in time with quality printing Any suggestion for the improvement of the book will be acknowledged and well appreciated, Author Hitesh P. Patel wy SYLLABUS Android Programming [2180715] 1. 2. The Basics: ‘+ Hello World : Intro to Android, Why develop apps for Android 2, Flavors of Android operating. systems, Challenges of developing for Android (multiple OS, need backwards compatibility, need to consider performance and offline capability) + Concept : Create Your First Android App : Overview of the development process - Java, Android Studio , Project layout in Android Studio, Target and minimum SDKs, Android Virtual Device (AVD) Monitor, Viewing logs in logeat and AVD, Android manifest file, App Architecture: An app consists of ‘one or more activities, For an activity, write Java code and layout xml, and hook them together, and register the activity in the manifest file. + Concept : Layouts, Views and Resources : Layout elements can be viewed and edited in Layout Editor and XML, Introduction to the range of UI elements, Resources (layouts, strings, styles, themes), Identifying resources with IDs, Programmatically referencing resources using resouree IDs, on Click attribute, Getting user input from a view, Programmatically changing Ul elements, Layout Managers, Defining layouts for activites, inflating the layout. * Concept : Scrolling Views : How to make activities scrollable: compare ScrollView, ListView, RecyclerView , Getting the resource ID fora Ulelementby inflating a layout (needed for RecyclerView), How to implement RecyclerView (requires layout managers and ViewHolders) , Performance impications of different kinds of serolling Ul elements + Concept: Resources to Help You Learn : Resources to help you learn: Samples that ship with the SDK, ‘Templates for projects, developer android, com, Android developer blog , Android developer YouTube channel, Source code and samples in github, Stack overflow, Google search! + Activities and Intents : About activities, Defining, Activ ‘About intents Explicit vs Implicit intents ,Passing info to new activ + The Activity Lifecycle and Managing State : Activity lifecycle , Activity lifecycle callback methods , Activity instance state _ Activity Lifecycle , Activity navigation , Returning data from activity + Starting Activities with Implicit Intents : Starting activities by sending implicit intents, Intent filters and enabling your activities to receive intents, ShareCompat + Testing and Debugging, and Backwards Compatibility : Debugging your apps, Testing your app, Support libraries User Interface : + User Input Controls : Getting user input Spinners, checkboxes, and radio buttons, Gi Changing keyboards tures, Speech recogniti Buttons , Dialogs and piekers , n (not done), Sensors (not done) + Menus : Options menu, contextual menus (floating and action bar), and popup menu, Adding menu items, Handling on Clicks from menus. + Screen Navigation : ‘Terminology, Different ways a user can navigate through an app, Action bar, Settings menu, Navigation drawer, Directed workflow (funnels), Best practices for navigation + Themes and Styles : Best practices for themes and styles, Performance benefits for themes, When and how touse drawables, best practices for drawable, When and how to use nine-patches, best practices for rine-patches, Tools for creating drawables ow ‘+ Material Design : What is material design? Material design best practices. Material Design guidelines, Implementing Material Design look and feel, with compatibility with previous versions, Support library for Material Design, Transitions and Animations + Adapt layouts for multiple devices and orientations : Why we need to consider different screen sizes and orientations , Screen density (dip or dp), How to create adaptive layouts using resources folders , Different ways to create images that scale nicely, Images and image formats and how they alfect performance (download speeds) + Accessibility : Why accessibility matters, Accessibility considerations: Color blindness, poor vision, poor hearing, physical limitations, Accessibility guidelines , Testing for accessibility , Sereen readers, Making your app more accessible: Color and Contrast, button size ~> Material Design guidelines, ‘considerate layouts and navigation + Localization : How to prep your app for localization, LTR and RTL (eg Arabic) text. + Testing the User Interface : Automated testing of Uls, User testing your UL with real users, Using the Espresso and UI Automator frameworks for testing UIs 3. Background Tasks + Connect to the Internet : Background Tasks, Synchronous versus async tasks, What is the UI thread and when should you use it? , Example of a background task ~ retrieving data over the intemet, ‘Creating background tasks. (schedule, send data, etc. , Implementing AsyncTask (dolnBackground(), callbacks) , Limitations of AsyncTask , Passing info to background tasks, Initiating background tasks, Scheduling background tasks (intro only, more later) + Connecting to the Internet : Permissions, Building URIs, Opening and closing Internet connections, Parsing JSON in Android. (Because it's common.) , Sending requests and parsing response. + AsyneTaskLoade : Intro to AsyncTaskLoader , loadInBackground() , AsyncTaskLoader callbacks , Benefits of loaders + Broadcast Receivers : What isa Broadcast Receiver and a Broadcast Intent? Broadcast Receiver Security. and Lifecycle + Services : What is.a service? Long running task without a UI, Difference between Activity and Service Start and stop services, Lifecyele methods, Foreground services, IntentService class, App priority (critical, high, low), How to create a new Service. + Notifications : hat is a Notification? , Notification Design Guidelines. + Triggering, Scheduling, and Optimizing Background : AlarmManager + Transferring Data Efficiently : Less data, less often! Cell radio life cycle, Job Scheduler. Why to use Job Scheduler instead of SyncManager/SyncAdapter, Difference between alarms and job schedulers. 4. Data - Saving, Retrieving, Loading + Storing Data in your app : Internal versus external storage, Privacy, sharing, security, encryption of your data, Shared Preferences: Store private primitive data in key-value pairs, SQLite Databases: Store structured data in a private database , Store data on the web with your own network server, Fircbase for storing and sharing data in the cloud, Concept : Preferences , What are Settings and Preferences ? , Settings best practices (harder to take away settings than to add, for usability reasons, Storing and retrieving preferences as key/value pairs using SharedPreference, Different Settings types, Settings menu, Using Activity and PreferenceFragments to allow users to set preferences + Store data using SQLite database : Overview of SQLite, OpenHelper Android class , Querying, (dev) Searching (user) databases, Best practices for using databases in Android , Best practices for testing your database ” + Using Content Resolvers to access data : Content Providers and Content Resolvers work together, what isa content provider ?, What isa content resolver ?, How do they work together ?, How to implement and use Content Resolvers * Content Providers : When to implement content providers , How to implement content providers (overview), Content URIs , UriMatcher, Content Provider authorities , Required methods on ContentProvider (query, insert, delete, update), MIME types , Contracts, Making content provider data accessible to other apps by modifying manifest, and protecting data with permissions. + Using Loaders to Load and Display Data: Using loaders to asynchronously load data into an activity or fragment, Benefits of Loaders~-why use them 2, Loader states (started, stopped, reset), Loader Manager, Methods and callbacks to implement in Loaders; loadinBackground(, deliverResult() ‘onStartStopLoading), onReset/Cancelled()) Registering listeners, Using CursorLoader with ContentProviders 5. Polish and Publish + Permissions : The permissions model + Libraries : Using libraries + Widgets : What are widgets ? When to use them and how to implement them + Publishing your App : Different ways to monetize your app (overview only) ‘+ Makingand publishing APKs : Guidelines for publishing in Google Play , Make and sign the APK, Beta test your app, Publish your app to Google Play wo TABLE OF CONTENTS Chapter - 1 Hello World (1 - 1) to (1 - 58) 1.1. Introduction to Android.. - 1-2 1.2. Concept : Create Your First Android App ....1-8 1.3. Create Android Application... woe b= 22 1.4 Concepts : Layouts, Views and Resources. 1-27 14.1 Layout. 1-27 142 UlElements.. 1-28 143 Recourses.. 1-29 144 1D, 1-32 1.45 Layout Manager. 1-35 1.4.6 Inflating the Layout. 1-36 15. Concept : ScrollingView... 1-36 1.6 Concept : Resources to Help You Learn.....1- 38 1.7. Activity and Intent... 1-39 1.8 Implicit Intent ...-. ever = AS 1.9. Debug Your App. 1-53 1.10 Testing Your App. 1-56 Chapter - 2 User Interface (2-1) to (2 - 102) 2.1. Interaction Design for User Input... 2-2 DAL Using Buttons sD 2.1.2 Checkboxes... 2-12 2.1.3 Spinners... 2-18 2.1.4 Changing Keyboards and Input Behaviors. 2-22 2.1.5 Recognizing Gestures... 12-31 2.2 Menu. sonines 2 34 2.2.1 Options Menu and App Bar 2-34 2.2.2 Popup Menu... : 2-38 2.3. Allowing Your Activity to be Added to Other Menus 2-47 2.3.1 Screen Navigation 2-47 2.3.2. Navigation into Your App via Home Screen Widgets and Notifications ......2-50 2.4 Themes and Styles 2-57 2.5 Material Design. 2-62 2.5.1 Material Design Color Palette ..nsun2- 68 25.2 Design Support Library 2-67 25.3. Activity Transitions. 2-72 2.6 Adapt Layout for Multiple Device and Orientation... 2-74 2.6.1 Orientation... 2-74 2.6.2 Resolution... 2-75 2.6.3 How to Create Adaptive Layout Using Resource Folder... 2-76 2.6.4 Different Ways to Create Images that Scale Nicely. 2-78 2.6.5. Images and Images Formats and How They Affect Performance 2-82 2.7 Accessibility...ssnmnnnanemnennnen 2 = 87 2.8 Localization winnie 2.9. Testing the User Interface .... Chapter - 3 Background Tasks (3-1) to (3 - 38) 3.1. Background Task... 3-2 3.1.1 0020The UI thread 3-2 3.1.2. AsyncTask... sone #2 3.1.3 Implementation of an AsyncTask ven 3-3 3.1.4 Limitations of AsyneTask. 3-4 3.2. Connect to the Internet. 3-5 3.2.1 Including Permissions in the Manifest ..3 - 5 3.2.2 Building your URI... wn 3-6 3.2.3. Opening and Closing the Connection.....3 = 6 3.2.4 Parsing the JSON .. 3.3 AsynTaskLoade 331 Intro to AsyncTaskLoader, (vii) 3.3.2 AsyncTaskLoader Callbacks ...nnsmne3 11 3.3.3. Benefits of Loader. 3-11 3.4 Broadcast Receiver. 3-12 3.4.1 Broadcast intents... 3-12 3.4.2 Security Guidelines 3-16 3.5. Services... 3-17 3.5.1 What is a Service ?. 3-17 3.5.2 Start and Stop Services 3-18 35.3. Service Lifecycle. 3-20 3.5.4 Foreground Services. 3-21 3.6 Notification 3-22 3.6.1 What is a notification ?. 3-22 3.6.2 Notification Design Guideline......n03 = 23 3.7. Triggering, Scheduling, and Optimi Background... oe B-27 3.7.1 Alarm Manager.. 3-27 3.8. Transferring Data Efficiently 3-31 3.8.1 Cell Radio Lifecycle 3-31 3.8.2 _JobScheduler. 13-35 Chapter - 4 Data - Saving, Retrieving, Loading (4-1) to (4-24) 4.1. Storing Data in Your App .. 4-2 4.1.1 Shared Preferences. 4-2 4.1.2. SQlite Database... sonnel S 4.2. Store Data using SQLite Database anced “9 4.2.1 SQL Databases 4.9 4.3. Using Content Resolver to Access Data... - 12 4.3.1 What is Content Provider ?. su AD 4.3.2 What isa Content Resolver ? 4-12 4.4 Content Provider... 41d 4.4.1. Implementing a Content Provider... 14 4.4.2 Contract 4-15, 4.43 Using a Content Resolver. 4-18 4.4.4 Permissions in from the Content Provider... 4.4.5 Permissions Client App Requests FFOM USF sonnei se -20 45 Using Loaders to Load and Display Data ...4 - 20 4.5.1 Using Loaders to Asynchronously Load Data into Activity or Fragments 4.22 4.5.2 Using Cursor Loader with Content Provider.... 4-23 Chapter - 5 Polish and Publish (5 - 1) to (5 - 30) 51 5.2 53 54 55 Permissions Libraries .. Widgets enn Publish your Apy Publish your Appl...nesmssnnnnnstn Hello World |Syllabus : Hello World, Concept Create Your First Android App, Concept : Layouts, Views and Resources, Concapt : Seraling Views, Concept : Resources to Help You Leam, Activitios and Intents, The Activity Lifecycle and Managing State , Starting Activities with Implicit Intents, Testing and Debugging, and Backwards Compatility Contents 1.1 Introduction to Android 1.2. Concept ; Create Your First Android App. 1.3 Create Android Application qeat 1.4 Concepts : Layouts, Views and Resource: 1-27 1.5 Concept : ScrollingView 1-36 1.6 Concept : Resources to Help You Learn 1-38 1.7 Activity and Intent... 1-39 1.8 Implicit Intent 1-45 1.9 Debug Your App... 1.10 Testing Your App. ap Android Programming Hello World [4] introduction to Android World is contracting with the growth of mobile phone technology. As the number of users is increasing day by day, facilities are also increasing. Starting with simple regular handsets which were used just for making phone calls, mobiles have changed our lives and have become part of it, Now they are not used just for making, calls but they have innumerable uses and can be used as a Camera , Music player, Tablet PC, T.V. , Web browser etc. And with the new technologies, new software and ‘operating systems are required Operating systems have developed a lot in last 15 years. Starting from black and white phones to recent smart phones or mini computers, mobile OS has come far away. Especially for smart phones, Mobile OS has greatly evolved from Palm OS in 1996 to Windows pocket PC in 2000 then to Blackberry OS and Android ‘One of the most widely used mobile OS these days is, ANDROID. Android is a software bunch comprising not only operating system but also middleware and. key applications. Android Inc was founded in Palo Alto of California, US. by Andy Rubin, Rich miner, Nick sears and Chris White in 2003. Later Android Inc. acquired by Google in 2005. After original release there have been number of updates in the original version of Android. Why Develop Android app ?? There are 7 reason to develop android app. 1) Market Share : (See Fig. 1.1.1) 2) Profitabilit In most app categories, Android apps have been found to be as. profitable (even more profitable in some instances) as iPhone apps, both for initial app purchases and for in-app purchases. Also, with many apps using a free with ads model, as long as the ads are being shown to app users, the app generates income. Blackbery 7" Windows we ios ‘Andtoid Android M103 Windosws. i Blockbery Ill Others Fig. 1.4.4 3) Low Barrier Entry : ‘To develop for 10S devices, a developer must use a Mac. However, Android app development can be done on Windows, Mac and Linux. Also, to register as a developer on the Apple App Store requires a yearly fee of $99, whereas to register as a developer on the Google Play Store requires a one time payment of $25. 4) Google Play Store : Apps deployed to the Google Play store are available for download by users within a few hours, compared to a few weeks for Apple's App Store. Another excellent feature of the Play Store is the ability to release an app as alpha and/or beta releases, which would be available only to members of a selected group of testers, 5) Java: Java is a proven and powerful programming language, used on a wide range of devices and operating systems. Learning Java can open doors for other opportunities, including the al y to develop applications for other operating systems (Windows, Linux) and devices. 6) Android Studi Android studio is an excellent IDE, based on the equally excellent IntelliJ IDE. As the name suggests, Android Studio is an IDE d Android app development. It is blazingly fast and sned and developed specifically for efficient, and you can setup a new Android project for different types of Android apps within seconds. Technical Publications” ~ An up trust for hrowiedvo Android Programming 13 Hello World 7) Portability = Native Android apps are developed using the Java programming language, and can easily be ported to other mobile operating systems like Blackberry, Symbian and Ubuntu. In addition, Android apps can also be ported easily to Chrome Os. Flavours of Android Operating System : ‘Android 1.1 Android 1.5 Cupeake Android 1.6 Donut Android 2.0 and 2.1 Eclair Android 2.2 Froyo Android 2.3 Gingerbread Android 3.0 and 3.1 Honeycomb Android 4.0 Tee Cream Sandwich Android 4.1, 4.2 and 4.3 Jellybean 10. Android 4.4 KitKat 11. Android 5.0 Lollipop 12, Android 6.0 Marshmallow 13. Android 7.0 Nougat 1. Andi 11 Android as the OS was born on the T-Mobile G1 which was extremely powerful for its time. This version of Android showcased its potential but it was best suited for early adopters and gadget freaks. While the GI couldn’t beat the iPhone sales in numbers and revenue, it offered some of the features key features of Android which we still find on our phones. Following, are the features that came with it. + The Android Market was used as a single source of delivery for Android apps and contrary to Apple's, tight restrictions on the App Store, the Android Market served apps without any restrictions. + It came with the Android browser which made surfing the web fun. + It was the first version of Android to offer data syncing with Google. ‘+ It came with Google maps which used GPS to point hot location on a map. This was the beginning of never getting lost again. 2. Android 15 Cupcake Cupcake was the Android version which started the tasty treat naming tradition for Android releases. Fig. 14.2 This was the very first major Android update and was released in May 2009. The most noticeable feature with cupcake was the virtual keyboard support which paced the way for buttonless smartphones of the future. Following are the features that came with it. + It came with shortcuts and widgets on the home screen which allowed infinite ways to customize the home sereen, Video recording was added to the camera along with the ability to directly upload videos to Youtube, ‘The browser got a speed improvement along with copy-paste support. 3. Android 1.6 Donut Android 1.6 Donut was released in October of 2009. It offered a few major improvements. The biggest feature addition was the added support for CDMA which brought a whole new crowed to Android CDMA was the technology used by American mobile networks at the time, Following are the features that came with it. ‘+ It came with support for multiple sereen resolutions and paved the way for Android devices of different screen sizes. tT Technical Publications” ~ An up trust for hrowiedvo Android Programming 1-4 Hello World Fig.1.1.3 + Google Maps Navigation was added with turn by turn satellite navigation support. + Donut included universal search feature which allowed us to pinpoint apps on the phone or searching the web. 4. Android 2.0 and 2.1 Eclair ‘There wasn’t a long wait after the release of Donut, for Eclair to be released. In fact, it was launched just a month after Donut in November of 2009, Eclair Android 2.C Fig. 1.1.4 Eclair 2.1 however, arrived in January 2010 with bug, fixes and new APIs to play with. There weren't any significant new additions in terms of features for users. Following are the features that came with it + Multi-touch support was added to Android, + Web browser received a visual overhaul with a new address bar and thumbnails for a sneak peek. + Eclair brought a unified inbox to Android. Support for multiple Google accounts was added. + Support for searching within text messages. 5. Android 2.2 Froyo Android Froyo was released in May 2010. Fig. 11.5 ‘The major update that came with Froyo was the addition of Flash. Following are the features that came with it + Phone flash could be used in videos too. ‘+ Settings joined contacts and email in backing up to Google’s servers allowing you to automatically restore everything on a new device. + Enhanced Bluetooth compatibility with docks and car speakers, * Portable WiFi hotspot to. share the device's 3G connection with other gadgets. 6 Android 2.3 Gingerbread Gingerbread was released in 2010 but it wasn’t a release which made a lot of noise. Fig. 11.6 Main features included NFC support, SIP for Internet calling, Following are the features that came with it. Tootnical Publications ‘nu trust or knowlege Android Programming 1-5 Hello World + UI overhaul to avoid screen burn-in and improve battery life + Front facing camera support for video calling, + Download manager for keeping an eye on your downloads + Improved on-screen keyboard with shortcuts and a cursor to help with copy paste. 7. Android 3.0 and 3.1 Honeycomb ‘This version of Android is the most disregarded of all. It was released specifically for tablets and never came to the phon Fig. 1.4.7 ‘Honeycomb was launched in May 2011 and it basically expanded Android to support big screens of tablets. Following are the features that came with it, + Several Ul improvements to make use of the large + Hardware buttons are dropped in favor of on-screen buttons, + Web browser introduced tabbed browsing, + Bigger and bolder widgets. + Apps like Gmail and YouTube were redesigned to make use of the large screen 8, Android 4.0 Ice Cream Sandwich Ice Cream Sandwich (ICS) was the first Android version to be May 2011 nnounced at the Google I/O conference in Although there was a long delay of around 7 months till, anyone could use it because the Samsung Galaxy Nexus started shipping only in December. Following are the features that came with it. + The biggest redesign to Android with the Holo theme. + Faster smoother browsing experience. + Multi storage space for apps. + Face recognition for unlocking the phone. Fig. 1.1.8 9. Android 4.1, 4.2 and 4.3 Jellybean Jellybean was released in June 2012 and while the version number wasn’t a huge one, it added a lot of new features. Fig. 1.1.9 Following are the features that came with it. + Google Now, an assistant tool that displays relevant information based on your search history. + Project Butter to support higher frame rates while swiping through menus and home screens, Tootnical Publications ‘nu trust or knowlege Android Programming 16 + Ability to quickly view photos by swiping from the camera to go to the filmstrip. + Widgets realign themselves on adding new ones. + Richer notifications. + New gestures and accessibility features. 10, Android 4.4 KitKat Android 44 KitKat was the last 4.x release and brought some major improvements both internally and visually to Android. Fig. 1.1.10 Tt was released in November of 2013. Following are the features that came with it. Hello World ‘+ Immersive mode for better content consumption. + Better navigation bar for getting in and out of Immersive mode. ‘+ Lock sereen widgets support + New dialer with Caller ID feature + Fullscreen wallpapers. + Emoji keyboard for emoticons. + Unified Hangouts and messaging app. + Better cloud print support. ‘+ Smarter, hands-free Google Now Integration, IL, Android 5.0 Lollipop Android 5.0 Lollipop was announced at Google I/O in May 2014, and so far it’s been the biggest redesign for Android. ‘The biggest improvement that Lollipop brought was the introduction of Material Design which quickly became the uni jed design language implemented across Google products. Following are the features that came with Fig. 1.1.11 Technical Pbleatons” ~An up trust for hrowiedvo Android Programming, 1-7 + Better quick settings support + Enhanced battery life with new Battery Saver mode. + New lock screen. + Smart Lock features via Google Play Services. = Guest mode for device sharing, ‘© App pinning, 12. Android 6.0 Marshmallow While Lollipop was a big feature release, Marshmallow served the purpose of polishing out the rough comers and making the experience of Lollipop even better. It was showcased at Google 1/0 in 2015. Following are the features that came with it = Marshmallow came with Doze for better standby time. ‘+ Official fingerprint support for devices + Support for mobile payments via Android Pay. ‘+ Better permissions model for apps. ‘= Google Now on Tap. + Deep linking of Apps. Fig. 1.1.12 13, Android 7.0 Nougat This brings us to the last and most recent version of Android, and that is Android 7.0 Nougat. Unlike others, Nougat was released way before Google 1/O in the month of March 2016. It brought with it some significant improvements and features. Following are the features that came with it, Hello World Fig. 1.1.13 + Doze on the Go for even better standby time. + Multi Window for using two apps at the same time. + Better Settings app. + Clear all in the recent apps screen. + Direct Reply to notifications. + Bundled notifications + Quick Settings toggles customization Challenges of developing for Android 1. Software fragmentation : There are many Android OS versions which developers find hard to keep up. with when it comes to app development. It is impractical to focus only on the most recent Android version as not all users may have upgraded to the most recent OS, 2. Hardware fragmentation : This becomes a big Android app development challenge since there are nearly 170+ devices running the OS. Each device has different features with respect to keyboard forms, screen size, camera buttons, etc, making it a development nightmare. 3. No software/hardware standardization : The huge number of devices running Android gives rise to another Android app development challenge-lack of Technical Publications” An up twust fr Rrowiedge Android Programming, 1-8 Hello World software/hardware standardization across the devices. This becomes a nightmare for developers as each device has a different function for a different button, 4. Several carriers : Android app development service providers should know that there are many carriers available for the Android OS, each with the freedom to modify the OS for their purposes. This only ‘multiplies the fragmentation problems for developers, 5. Security : Unlike Apple's strict guidelines for app development, no such governance exists for Android apps. Asa result, many malware problems arise and software/hardware fragmentation only makes fixing the problems more difficult. This gives rise to tremendous amounts of security issues. + One of the biggest Android app development challenges for developers is the 6. Market research cost cost behind market research, Understanding the end user key to Android app development, but can require a lot of research, making it costly for developers: 7. Patent issues : Android violation of patent issues. This can become a big, Android app development challenge for developers, ‘The recent lawsuits indicate that several features may be declared as 8. Android market search engine : One of the major Android app development challenges for developers is the Android marketplace. Android has ‘more than 8 million apps on its marketplace today and getting your app visible amongst them is a challenge. As a result, even with a great android app developed, if you don’t pay attention to its promotion, you may lose out on gaining any traction, [2] Concept : Create Your First Android App Overview of the Development Process : First of all you have to setup the android development environment. And then after going for the further Step 1: Setup Java Development Kit (JDK) You can download the JDK and install it, which is pretty easy. After that, you just have to set PATH and JAVA_HOME variables to the folder where you have java and javac. Note for Windows Users : If you installed the JDK in CAldk1.6.0_15 then you will have to add the following two lines in your C:\autoexec.bat fle sot PATH=CA\dk1.6.0_18\binskPATH set JAVA_HOME=C:\\di.6.0_15 Step 2: Android Studio Download the Android studio from the following Link : hitps://developer.android.com/studio/index html after that install it on your system and configure it, Here Lam giving you a steps for configure the Android studio. Android studio presents a splash screen when it starts running : Android G2 S: Fig. 1.2.1 : Android studio's start sereen Technical Pubheatons ‘Anup trust or irowecoe Android Programming, 1-9 Hello World On your first run, you'll be asked to respond to several configuration-oriented dialog boxes. The first dialog box focuses on importing settings from any previously installed version of Android Studio, ‘You can import your settings from 2 prewous version of Stud Inport my settings from a custom k Speaty config folder or instalation home of the previous version of Studio: © 1.40 nt have a previous version of Stusho or Ido not want to enport my setnings Dk Fig. 1.2.2 Import settings If you're like me, and don't have a previously installed version, you can just keep the default setting and click OK. Android Studio will respond with a slightly enhanced version of the splash screen, followed by the Android Studio Setup Wizard dialog box (oO ¢ vol jee Fig. 1.2.3 Validate your Android SDK and development environment setup When you click Next, the setup wizard invites you to select an installation type for your SDK components. For now I recommend you keep the default standard setting, 77 Technical Publications” An up twust fr Rrowiedge Android Programming, 1-10 Hello World Gag 211 Type Fig. 1.2.4 Choose an installation type Click Next and verify your settings, then click Finish to continue. Gag Verty Serting sre Shmtmenscetatcte 04 compen enn Fig. 1.2.5 Review settings The wizard will download and unzip various components. Click Show Details if you want to see more information about the archives being downloaded and their contents, 77 Technical Publications” An up twust fr Rrowiedge Android Programming, 1-11 Hello World ig. 1.2.6 The wizard downloads and unzips Android Studio components If your computer isn’t Intel based, you might get an unpleasant surprise after the components have completely downloaded and unzipped: m2 ceposivory/com/google/' bs roid SUK ie up to dat 10/ ti cebas ~core-8, an: unable & éngeali Intel Mant a does not support required feat YOUr computer does not support hardy Here are some of your options 1) Uae « phys ting 2) Develop on a Windove/aS% computer ¥ shat supporta Yr-x and ®K = (ere or svt) 1 device on Ine pro 3) Develop on 4 Linux complter ShAL aupporeé YE-R of GYM ARM eystem inage ed Hing Android virtual device Gnable to crea create A Fig. 1.2.7 Intel-based hardware acceleration is unavailable 77 Technical Publications” An up twust fr Rrowiedge Android Programming, 1-12 Hello World Your options are to either put up with the slow emulator or use an Android device to speed up development. Finally, click Finish to complete the wizard. You should see the Welcome to Android Studio dialog box : Android Studio © Stara new Andrond Studio project E21 0pen an exsting Android Stud project neck ut pryeet rom Version Control + (Ff Impion projet (Eclipse ADT, Grade ere) ©F Import an Andon code sample © configue- GetHetn + Fig. 1.2.8 Welcome to Android Studio You'll use this dialog to start up a new Android Studio project, work with an existing project, and more. You can access it anytime by double-clicking the Android Studio shortcut on your desktop. Your first Android Studio mobile app The quickest way to get to know Android Studio is to use it to develop an app. Well start with a variation, on the "Hello, World” application: alittle mobile app that displays a "Welcome to Android" message. In the steps that follow, you'll start a new Android Studio project and get to know the project workspace, including the project editor that you'll use to code the app in Part 2. Starting a new project From our setup so far, you should still have Android Studio running with the Welcome to Android Studio dialog box. From here, click Start a new Android Studio project. Android Studio will respond with the Create New Project dialog box shown in Fig, 1.2.9. 77 Technical Publications” An up twust fr Rrowiedge Android Programming, 1-13 Hello World Fig. 1.2.9 Create a new project Enter W2A (Welcome to Android) as the application name and javajeff.ca as the company domain name. ‘You should then see C:\Users\jeffrey\ AndroidStudioProjects\W2A as the project location, Click Next to select your target devices. Fig. 1.2.10 Select your target device categories Android Studio lets you select form factors, or categories of target devices, for every app you create. T would have preferred to keep the default API 1 Android 4.0.3 (IceCreamSandwich) minimum SDK 77 Technical Publications” An up twust fr Rrowiedge Android Programming, 1-14 Hello World setting (under Phone and Tablet), which is supported by my Amazon Kindle Fire HD tablet. Because Android Studio doesn't currently support this API level (even when you add the 4.0.3 system image via the SDK Manager), I changed this setting to API 14: Android 40 (IceCreamSandwich), which is also supported by my tablet. Click Next, and you will be given the opportunity to choose a template for your app's main activity. For now we'll stick with Empty Activity, Select this template and click Next. Fig, 1.2.11 Specity an activity template Next you'll customize the activity = FAR customize the Activity Fig. 1.2.12 Customize your activity = Technical Publications” An up twust fr Rrowiedge Android Programming 1-15 Hello World Enter W2A as the activity name and main as the layout name, and click Finish to complete this step. Android Studio will respond that itis creating the project, then take you to the project workspace, Fig. 1.2.13 Android Studio workspace ‘The project workspace is organized around a menu bar, a tool bar, a work area, additional components that lead to more windows (such as a Gradle Console window), and a status bar. Also note the Tip of the Day dialog box, which you can disable if you like. ‘Accessing AVD Manager or SDK Manager from ‘menu and tool bar To access the traditional AVD Manager or SDK Manager, select Android from the Tools menu followed by AVD Manager or SDK Manager from the resulting Pop-up menu (or click their tool bar icons). AVD- Android Virtual Device About AVDs An AVD contains a hardware profile, system image, storage area, skin, and other properties. Hardware profile ‘The hardware profile defines the characteristics of a device as shipped from the factory. The AVD Manager comes preloaded with certain hardware profiles, such as Nexus phone devices, and you can define and import hardware profiles as needed. You can override some of the settings in your AVD, if needed. To effectively test your app, you should create an AVD that models each device type that your app is designed to support. ‘System image +The AVD Manager helps you choose a system image for your AVD by providing recommendations. It also lets you download system images, some with add-on libraries, like Google APIs, which your app might require. x86 system images run the fastest in the emulator. 77 T Technical Publications” An up twust fr Rrowiedge Android Programming, 1-16 Hello World + Android Wear and Android TV devices tend to run best (and have the largest installed base) on recent releases, while users of Android phones and tablets tend to use slightly older releases, as shown in the API level dashboards. + We recommend that you create an AVD for each API level that your app could potentially support based on the setting in your manifest. For example, you might want to test with all API levels that are equal to and higher than the minSdkVersion setting, By testing with API levels higher than required by your app, you ensure app forward-compatibility when users download system updates, Storage area The AVD has a dedicated storage area on your development machine. It stores the device user data, such as installed apps and settings, as well as an emulated SD card. If needed, you can use the AVD Manager to wipe user data, so the device has the same data as if it were new. Skin An emulator skin specifies the appearance of a device. The AVD Manager provicies some predefined skins. ‘You can also define your own, or use skins provided by third parties. AVD and app features Just as with a real device, for apps to use certains features defined in an AVD, such as the camera, it must have the corresponding setting in the app manifest. See Hardware Profile Properties and AVD Properties for lists of features you can define in your AVDs. ‘Viewing and Managing Your AVDs ‘The AVD Manager lets you manage your AVDs all in one place. ‘To run the AVD Manager, do one of the following : + In Android Studio, select Tools > Android > AVD Manager. + Click AVD Manager in the toolbar. ‘The AVD Manager appears. t me Soweie2] EN 2 pewsouiodid ase Lk bee Dream eT] Ree TS monurvdou onze ana emt 8 TD smn sean om x20) 2k eases SL ee Tl tenn snes toon t2M sry «21 ete 8 bre Fig. 1.2.14 = Technical Publications” An up twust fr Rrowiedge Android Programming, 1-17 Hello World It displays any AVDs you've already defined. When you first install Android Studio, it creates one AVD. If you defined AVDs for Android Emulator 24.0.x or lower, you need to recreate them. From this page you can : + Define a new AVD ot hardware profile. ‘+ Edit an existing AVD or hardware proiile. + Delete an AVD or hardware profile. ‘+ Import or export hardware profile definitions. + Run an AVD to start the emulator. ‘+ Stop an emulator. + Clear data and start fresh, from the same state as when you first ran the emulator. sk, ‘+ Show the associated AVD .ini and .img files on + View AVD configuration details that you can include in any bug reports to the Android Studio team, ing an AVD You can create a new AVD from the beginning, or duplicate an AVD and change some properties. ‘To create a new AVD 1. From the Your Virtual Devices page of the AVD Manager, click Create Virtual Device. Alternatively, run your app from within Android Studio. In the Select Deployment Target dialog, click Create New Emulator. ‘The Select Hardware page appears. Seay ‘Choore a devs definition comet om any mst - <= Fig. 1.2.15 Android Programming, 1-18 Hello World 2. Select a hardware profile, and then click Next. If you don't see the hardware profile you want, you can create or import a hardware profile ‘The System Image page appears. Sac Selecta system image RRR 05 rao citer ses — oe = Serre aah eee gait Se 09 Down mee Andel $1 a" a & PV ovate in tnt tnd cae pe or Cofe A Cust on Ant Fig. 1.2.16 3. Select the system image for a particular API level, and then click Next. ‘The Recommended tab lists recommended system images. The other tabs include a more complete list ‘The right pane describes the selected system image. x86 images run the fastest in the emulator. If you see Download next to the system image, you need to click it to download the system image. You must be connected to the internet to downloa The APT level of the target device is important, because your app won't be able to run on a system image specified in the minSdkVers with an API level that's less than that required by your app, For more information about the relationshi the app manifest fi between system API level and minSdkVersion, see Versioning Your Apps, If your app declares a element in the manifest file, the app requires a system image in which that external library is present. If you want to run your app on an emulator, create an AVD that includes the required library. To do so, you might need to use an add-on component for the AVD platform; for example, the Google APIs add-on contains the Google Maps library. ‘The Verify Configuration page appears. = Technical Publications” An up twust fr Rrowiedge Android Programming, 1 19 Hello World Virtual Device (AVD) ‘en Contguraion| TH peuse sao oe amaeoam oO =. Ghee ene | Fig. 1.2.17 ‘Change AVD properties as needed, and then click Finish. Click Show Advanced Settings to show more settings, such as the skin. ‘The new AVD appears in the Your Virtual Devices page or the Select Deployment Target dialog. To create an AVD starting with a copy: 1. From the Your Virtual Devices page of the AVD. ‘Manager, right-click an AVD and select Duplicate. Orclick Menu. and select Duplicate, ‘The verify configuration page appears. 2. Click Change or Previous if you need to make changes on the System Image and Select Hardware pages. 3. Make your changes, and then click Finish. ‘The AVD appears in the Your Virtual Devices page. Creating a Hardware Profile The AVD manager provides predefined hardware profiles for common devices so you can easily add them to your AVD definitions. If you need to define a different device, you can create a new hardware profile, You can define a new hardware profile from the beginning, or copy a hardware profile as a start. The preloaded hardware profiles aren't editable. To create a new hardware profile from the beginning 1. In the Select Hardware page, click New Hardware Profile. 2. In the Configure Hardware Profile page, change the hardware profile properties as needed, 3. Click Finish. Your new hardware profile appears in the Select Hardware page. You can optionally create an AVD that uuses the hardware profile by clicking Next. Or, click T = Technical Pubheatons ‘Anup trust or irowecoe Android Programming, 1 Cancel to retum to the Your Virtual Devices page or Select Deployment Target dialog To create a hardware profile starting with a copy : 1. In the Select Hardware page, select a hardware profile and click Clone Device. Or right-click a hardware profile and select Clone. 2. In the Configure Hardware Profile page, change the hardware profile properties as needed. 3. Click Finish, Your new hardware profile appears in the Select Hardware page. You can optionally create an AVD that uses the hardware profile by clicking Next. Or, click Cancel to retum to the Your Virtual Devices page or Select Deployment Target dialog. Working with Existing AVDs From the Your Virtual Devices page, you can perform the following operations on an existing AVD : + To edit an AVD, click Edit 7 changes. + To delete an AVD, right-click an AVD and select Delete. Or click Menu. ¥ and select Delete. and make your + To show the associated AVD Jini and .img files on disk, right-click an AVD and select Show on Disk Or click Menu. ¥ and select Show on Disk. + To view AVD configuration details that you can include in any bug reports to the Android Studio team, right-click an AVD and select View Details. Or click Menu. ¥ and select View Detail ‘Viewing logs in the Logeats and AVD. Android Monitor includes a logeat Monitor that displays debug messages. The logeat Monitor displays system messages, such as when a garbage collection occurs, as well as messages that you can add to your app using the Log class. It displays messages in real 20 Hello World time and also keeps a history so you can view older messages. To display the log messages for a particular app 1. Meet the prerequisites and dependencies. Open an app project. Run the app on a hardware device or emulator. Display Android Monitor. Click the logeat tab. Android Manifest File : Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest file provides essential information about your app to the Android system, which the system must have before itcan run any of the app's code. Among other things, the manifest file does the following : + It names the Java package for the application. The package name serves as a unique identifier for the application. + It describes the components of the application, which include the activities, services, broadcast receivers, and content providers that compose the application, It also names the classes that implement each of the components and publishes their capabilities, such as the Intent messages that they can handle. These declarations inform the Android system of the components and the conditions in which they can be launched. + It determines the processes that host the application components. ‘+ It declares the permissions that the application must have in order to access protected parts of the API and interact with other applications. It also declares Technical Pubheatons ‘Anup trust or irowecoe Android Programming, 1 the permissions that others are required to have in order to interact with the application's components, ‘+ It lists the Instrumentation classes that provide profiling and other information as the application runs, These declarations are present in the manifest only while the application is being developed and are removed before the application is published «It declares the minimum level of the Android API that the application requires. # It lists the libraries that the application must be linked against. Here is an example of the manifest file instrumentation /> - catogory /> 21 Hello World ... ... ... < - Create Android Application ‘The first step is to create a simple Android Application using Android studio. When you click on Android studio icon, it will show screen as shown below Technical Pubheatons “ann trust or inawiecge Android Programming, 1-22 Hello World e Welcome to Android Studio a ae ae PR Septet om oninginintopene IF. erencoerspanen SS cha ee se EB error nsec nor, ite ee} Fig. 1.3.1 You can start your application development by calling start a new android studio project. in a new installation frame should ask Application name, package information and location of the project. Peay Fig. 1.3.2 = F Technical Publications” An up twust fr Rrowiedge Android Programming, 1-23 Hello World After entered application name, it going to be called select the form factors your application runs on, here need to specify Minimum SDK, in this, I have declared as API23: Android 6.0(Mashmallow) tthe et yp tna one Saar Fig. 1.3.3 The next level of installation should contain selecting the activity to mobile, it specifies the default layout for Applications. Ene gon Fig. 1.3.4 At the final stage it going to be open development tool to write the application code. 77 Technical Publications” An up twust fr Rrowiedge Android Programming, 1-24 Hello World aus Fig. 1.3.5 Anatomy of Android Application Before you run your app, you should be aware of a few directories and files in the Android project ~ y Di manifests 1B AndroidManifestaml a) » Ex comexampletutoriaspoint7 myapplication Ei comexampletutoriaspintZ myapplication(onsioitTet Ei comerampletutoriaspoint7 myapplication |) y Cares 1 deanable ——__________[ + Blayout Bochner EX mipmap © Bic tauncherpng (5) Se 1B colorsxm! » © dimen 1B stings! B stylesam! YB GxadeSenpts buid grate Pees MyAppenion © buitdgrae (Mode opp) {6 proguard-rle pr B settings grade Proje Se [a local propertis 08 Fig. 1.3.6 = F Technical Publications” An up twust fr Rrowiedge Android Programming, 1 Sr.No. Folder, File and Description 1 Java ‘This contains the java source files for your project. By default, it includes an MainActivity java source file having an activity class that runs when your app is launched using the app icon. 2 res/drawable-hapi ‘This is a directory for drawable objects that are designed for high-density screens. 3 res/layout This is a directory for files that define your app's user interface, 4 resjvalues ‘This is a directory for other various XML files that contain a collection of resources, such as strings and colours definitions, 5 AndroidManifest.xml his is the manifest file which describes the fandamental characteristics of the app and defines each ofits components, 6 Build gradle ‘This is an auto generated file which contains ‘compileSdkVersion, buildToolsVersion, applicationld, minSdkVersion, targetSdkVersion, versionCode and versionName Following section will give a brief overview few of the important application files. The Main Activity File The main activity code is a Java file MainActivity java This is the actual application file which ultimately gets converted to a Dalvik executable and runs your application. Following is the default code generated by the application wizard for Hello World! application ~ package com.example.helloworld; import android.support.v7.app.AppCompatActivity; import android.os. Bundle; public class MainActivity extonds AppCompatActivity { @override protected void onGreate(Bundle savedInstanceState) { super.onCreate(savedinstanceState); 25 Hello World setContentView(Rlayout.activity_main); } y Here, Rlayout.activity_main refers to the activity_main, xml file located in the res/layout folder. The onCreate() method is one of many methods that are figured when an activity is loaded. The Manifest File Whatever component you develop as a part of your application, you must declare all its components in a which the of the application project directory. This file works as an interface between Android OS and your application, s0 if you do not declare your component in this file, then it manifest.xml resides at root will not be considered by the OS. For example, a default manifest file will look like as following file ~ 1,0" encoding="ut-8"7> om. example Hitesh7.myapplication"> activity android:name="MainActivity"> < < Here .. tags enclosed. the the application. Attribute androidsicon will point to the application icon available components related to under res/drawable-hdpi. The application uses. the image named ic_launcher-png located in the drawable folders Technical Pubheatons ‘Anup trust or Irowedoe Android Programming, 1 26 Hello World The tag is used to specify an activity and android:name attritmte specifies the fully qualified class name of the Activity subclass and the android:label attributes specifies a string to use as the label for the activity. You can specify multiple activities using tags. ‘The the filter android.intent.aetion. MAIN to indicate that this activity action for intent is named serves as the entry point for the application. The category for the —_intent-filter_ is named android.intent.category.LAUNCHER to indicate that the application can be launched from the device's launcher icon. The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to the app_name string defined in the strings.xml file, which is. "HelloWorld". Similar way, other strings get populated in the application. Following is the list of tags which you will use in your manifest file to specify different Android application components ~ + elements for activities = elements for services ‘+ elements for broadcast receivers + elements for content providers The Strings File ‘The strings.xml file is located in the res/values folder and it contains all the text that your application uses. For example, the names of buttons, labels, default text, and similar types of strings go into this file. This file responsible for their textual content. For example, a default strings file will look like as following file ~ ‘string name="app_name'»HelloWorld string name="hello_world'>Hello world! MainActivity The Layout File ‘The activity mainxml is a layout file available in res/layout directory, application when building its interface. You will modify that is referenced by your this file very frequently to change the layout of your application, For your "Hello World!" application, this file will have following content related to default layout, wrap_content characters monospace 12pt #0000 In your AndroidManifestxml apply the theme to the activities you want to style elements to your custom theme. These attributes are defined in your styles.am! file. For example, to apply the custom color to the window background, add the following two elements to your custom theme, defined in My Android App/res/values/styles.xml file Technical Publications "anu trust for nowiecge Android Programming, 1 coo Foursquare BB sstestorce ra Facebook ced ol Hope you understood the concept of Style, so now let's try to understand what is a Theme. A theme is nothing but an Android style applied to an entire Activity or application, rather than an individual View. Thus, when a style is applied as a theme, every View in the Activity or application will apply each style property that it supports. For example, you can apply the same CustomFontStyle style as a theme for an Activity and then all text inside that Activity will have green monospace font To set a theme for all the activities of your application, open. the file tag to include the android:theme AndroidManifest.xml and edit the attribute with the style name. For example ~ ‘There are number of default themes defined by Android which you can use directly or inherit them using parent attribute as follows ~ Default Styles and Themes ‘The Android platform provides a large collection of styles and themes that you can use in your applications. You can find a reference of all available styles in the R.style class. To use the styles listed here, replace all underscores the style name with a period. For example, you can apply. the ‘Theme_NoTitleBar theme with “android:style/Theme-NoTitleBar". You can see the following source code for Android styles and themes + Android Styles (styles.xml) hUtps://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/s tylesxml + Android Themes (themes.xml) https://android.googlesource.com/platform/frameworks/base/'/refs/heads/master/core/res/res/values/t hhemes.xml 1.4.4] 1D ‘An Android id is an integer commonly used to identify views; this id can be assigned via XML (when possible) and via code (programmatically.) The id is most useful for getting references for XML-defined Views generated by an Inflater (such as by using setContentView.) Assign ID via XML + Add an attribute of android '@+id/somename" to your view. + When your application is built, the android:id will be assigned a unique int for use in code + Reference your android:id’s int value in code using "Rid.somename" (effectively a constant.) ‘+ this int can change from build to build so never copy an id from gen/package.name/R java, just use "Rid.somename’ (Also, an id assigned to a Preference in XML. is not used when the Preference generates its View.) Assign id via code (programmatically) + Manually set ids using someView-setld (int); ‘+The int must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.) Technical Publications” An up twust fr Rrowiedge Android Programming, 1-33 Hello World ‘+ For example, if creating and numbering several views representing items, you could use their item number. On click Attribute : To define the click event handler for a button, add the android:onClick attribute to the

You might also like