MASTER OF COMPUTER        APPLICATIONS          SEMESTER V    MOBILE APPLICATION        DEVELOPMENT              MCA652
CHANDIGARH UNIVERSITY  Institute of Distance and Online Learning                     Course Development Committee    Prof. (Dr.) R.S.Bawa  Pro Chancellor, Chandigarh University, Gharuan, Punjab                                             Advisors    Prof. (Dr.) Bharat Bhushan, Director – IGNOU  Prof. (Dr.) Majulika Srivastava, Director – CIQA, IGNOU    Programme Coordinators & Editing Team    Master of Business Administration (MBA)  Bachelor of Business Administration (BBA)  Coordinator – Dr. Rupali Arora           Coordinator – Dr. Simran Jewandah    Master of Computer Applications (MCA)    Bachelor of Computer Applications (BCA)  Coordinator – Dr. Raju Kumar             Coordinator – Dr. Manisha Malhotra    Master of Commerce (M.Com.)              Bachelor of Commerce (B.Com.)  Coordinator – Dr. Aman Jindal            Coordinator – Dr. Minakshi Garg    Master of Arts (Psychology)              Bachelor of Science (Travel &Tourism Management)  Coordinator – Dr. Samerjeet Kaur         Coordinator – Dr. Shikha Sharma    Master of Arts (English)                 Bachelor of Arts (General)  Coordinator – Dr. Ashita Chadha          Coordinator – Ms. Neeraj Gohlan    Academic and Administrative Management    Prof. (Dr.) R. M. Bhagat                 Prof. (Dr.) S.S. Sehgal  Executive Director – Sciences            Registrar    Prof. (Dr.) Manaswini Acharya            Prof. (Dr.) Gurpreet Singh  Executive Director – Liberal Arts        Director – IDOL    © No part of this publication should be reproduced, stored in a retrieval system, or transmitted in any form     or by any means, electronic, mechanical, photocopying, recording and/or otherwise without the prior     written permission of the authors and the publisher.                                                  SLM SPECIALLY PREPARED FOR                                                            CU IDOL STUDENTS         Printed and Published by:                     TeamLease Edtech Limited                          www.teamleaseedtech.com                             CONTACT NO:- 01133002345    For: CHANDIGARH UNIVERSITY                                                                                    2                    Institute of Distance and Online Learning                                                CU IDOL SELF LEARNING MATERIAL (SLM)
First Published in 2021    All rights reserved. No Part of this book may be reproduced or transmitted, in any form or by  any means, without permission in writing from Chandigarh University. Any person who does  any unauthorized act in relation to this book may be liable to criminal prosecution and civil  claims for damages. This book is meant for educational and learning purpose. The authors of  the book has/have taken all reasonable care to ensure that the contents of the book do not  violate any existing copyright or other intellectual property rights of any person in any  manner whatsoever. In the event the Authors has/ have been unable to track any source and if  any copyright has been inadvertently infringed, please notify the publisher in writing for  corrective action.                                          3    CU IDOL SELF LEARNING MATERIAL (SLM)
CONTENTS    Unit - 1: Android Basic Structure ..............................................................................................5  Unit - 2: Building Blocks.........................................................................................................21  Unit - 3: Fragments ..................................................................................................................36  Unit - 4: Ui-Widgets ................................................................................................................71  Unit - 5: Ui Controls ..............................................................................................................103  Unit – 6 : Layout Manager, Adaptor......................................................................................123  Unit - 7: Android Menu .........................................................................................................141  Unit - 8: Android Alarm,Drag And Drop Activity ................................................................167  Unit - 9: Multimedia ..............................................................................................................181  Unit - 10: Device Connectivity ..............................................................................................229  Unit - 11: Data Storage-1.......................................................................................................244  Unit - 12: Data Storage-2.......................................................................................................269  Unit - 13: Android Web-Services ..........................................................................................303  Unit - 14: Deployment ...........................................................................................................314  Unit - 15: Updating Existing Deployed Application .............................................................327                                          4    CU IDOL SELF LEARNING MATERIAL (SLM)
UNIT - 1: ANDROID BASIC STRUCTURE    Structure     1.0 Learning Objectives   1.1 Introduction   1.2 Android Platform   1.3 Android Architecture   1.4 Android Stack   1.5 Dalvik Virtual Machine   1.6 Android vs. other mobile platforms   1.7 Summary   1.8 Keywords   1.9 Learning Activity   1.10 Unit End Questions   1.11 References    1.0 LEARNING OBJECTIVES    After studying this unit, you will be able to:      ● Define Android and its Functions      ● Get knowledge about Android Architecture      ● Describe working of Android Stack       ● Differentiate between Android vs. other mobile platforms        ● Describe how to Link Activity to the Intents    1.1 INTRODUCTION    An Operating System (OS) manages pc resources, together with a pc's hardware (together  with reminiscence and methods) and its software program. Android is a fast-transferring  operating system primarily based totally at the Linux kernel, which includes about 12 million  code linesKotlin is the brand new and secure programming; and while the Android studio  became released, it have become the authentic programming.. Android makes use of a  custom-designed digital machine to optimize reminiscence and hardware sources in a mobile                                          5    CU IDOL SELF LEARNING MATERIAL (SLM)
environment. Like Android OS, Google additionally backs up Chrome OS. Android OS is for  embedded platforms, and Chrome OS is for Cloud-primarily based totally platforms.    If you're using smartphones going for walks on Android, you is probably privy to the use of  all of the programs. Some of the local Android programs are e mail consumer, SMS control  application, a complete PIM (personal information management) suite, a Web Kit-primarily  based totally internet browser, a tune player, and a photo gallery. The third-celebration  programs are games, photo, and video-associated apps. Apart from the Android cell phones,  the alternative embedded gadgets together with tablets, netbooks, television, set-pinnacle  boxes, and vehicles have Android Operating System. The hardware varies on every Android  device. These hardware variations help in writing device-unbiased code.    The benefits of android are; it adopts quickly, can reuse it, it has a Free and open-supply  SDK, and it helps operations to more than one platforms. The issues related to the Android  Operating machine are - Fake Applications, problems withinside the history methods, and  one version of OS crashing with the alternative OS.    In 2003, a start-up organization named Android, Inc. advanced Android. In 2005, Google  bought Android for improvement paintings and made it to be had as loose and open-supply  software program. Later in 2007, a collection of enterprise human beings shaped an Open  Handset Alliance to boost up cell innovation and offer a higher person enjoy. Google  efficiently driven the Android platform to the leading edge in some years.    But, ever surprise how the programs are advanced. In this chapter, we're looking to search out  growing cell programs. Writing programs in Android calls for Java Framework, however now  no longer Java. Another beneficial device for improvement is Extensible Markup language  (XML) that's used to explain information sources. Android is a vacation spot for an extensive  variety of beneficial libraries and equipment to construct wealthy programs. For the third-  party software developers, Google assists in lots of forms as Android Development Tool  (ADT) Plug-ins for Eclipse.    1.2 ANDROID PLATFORM    What is Android?    Android is an open-source, Linux-primarily based totally software program stack that  consists of the operating system, middleware, and a software framework for constructing  programs. Many hardware producers can now personalize Android due to no constant  hardware or software program configurations for his or her extensive variety of products, like  Game consoles, Digital cameras, Sensors, BT. Consequently, Android advanced past its  creativeness and created a platform for software developers.    We can say that Android is the maximum effective working machine withinside the  marketplace. Storage, connectivity, internet browser, media, flash and hardware support,                                          6    CU IDOL SELF LEARNING MATERIAL (SLM)
multi-tasking, tethering, multi-contact, and messaging are Android capabilities. The  following listing of capabilities are precise to Android, and won't be to be had on different  cellular software platforms. They are Google maps programs, history services, programs,  shared information and inter-procedure communication, Wi-Fi Direct, and Android Beam.                               Virtual  Compatibility  Compatability                            Machines    Definition     Test suite                                        Document                                          (CDD)      Software                          Android                                                   Linux  Development                                                                                 operating                                                                                              sysytem   Kit (SDK)                                                                                               Kernel    Opensource                                              An   Libraries                                         Application                                                     framework                                       An User                                       Interface                                      Framework                                   Figure 1.1: Parts of Android    Input information for Android customers the use of touch screens. Acoustic Resistive,  Capacitive, and Surface Acoustic waves are plenty of display touch techniques. All Android  gadgets use resistive or capacitive technology. The programming languages used to enhance  Android programs are Java and Kotlin. Google loves Kotlin due to the fact it's far the  authentic language of Android improvement. Android has a fixed of API libraries, and  maximum third-celebration programs are written with the equal APIs, run simultaneously.  These APIs encompass hardware access, video recording, location-primarily based totally  services, background services, map-primarily based totally functions, associated facts, inter-  system communications, Bluetooth, NFC, and 2D and 3Dimensions.    Android Application Structure    Android OS is constructed just like the following images. Images are saved in solid flash  reminiscence and are protected while strength drops.    Bootloader: Start loading the boot image for the primary time.    BootImage: Kernel & RAM.    Image System: Android working machine platform and apps.    Image information: User information is saved in strength cycles.    Image recovery: Files used to construct or update an application.                                      7                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
Radio image: Radio stack files.    Overview of the Android app    The Android application creates Tasks, Services, Content Providers, and Objectives.  Functions are elements of building a user interface (UI). We know more about jobs in recent  categories. Services are short-lived and may be closed at any time. Services run behind the  scenes, and Tasks operate before the scenes.    Content providers share data stored on a device used by many applications. Stream recipients  display messages to the user in response to the action.    Android versions    Figure 1.2: Different Android Versions    1.3 ANDROID ARCHITECTURE    Android Operating System architecture components support mobile device needs and are  categorised into five sections in four main layers: Linux kernels, Libraries, Android Runtime,  Application Framework, and Applications.        ● Applications    Applications form the upper layer in the Android architecture. The applications you write are  included in this layer. It has pre-installed applications like home, contacts, camera, gallery,  etc.,                                            8    CU IDOL SELF LEARNING MATERIAL (SLM)
● Application Framework    Application Framework provides several elementary classes that are used to create an  Android application by the developers. It enables hardware access and directs the user  interface with application sources. Which includes different services like the activity  manager, notification manager, view system, package manager etc.        ● Application runtime    The components of the environment are, Dalvik virtual machine (DVM ) and core libraries.  With the help of the core libraries, developers write Android Apps. DVM is a virtual machine  that is specially adapted for Android. It assures that a device can efficiently run.        ● Libraries    The code segment of Android is present in this layer. It includes various C/C++ libraries, and  Java-based libraries, such as Media, Graphics, Surface Manager, OpenGL, etc.,        ● Media library give support to play, record audio and video formats.      ● The responsibility of a surface manager is to provide access to the display.      ● SGL, OpenGL are cross-language, cross-platform application program interfaces             (API) used for 2D and 3D graphics.      ● SQLite provides database support, and Free-Type provides font support.      ● Web-Kit is a web browser engine which provides all the functionality to display web             content and simplify page loading.      ● SSL is a technology which build an encrypted link between a web server and web             browser.      ● Linux Kernel    Linux Kernel handles all the available drivers required for the runtime, such as display  drivers, camera drivers, Bluetooth drivers, audio drivers and memory drivers etc. The Linux  Kernel acts as a layer between the hardware devices and the other Android architecture  components, which is responsible for memory, power, appliances, etc.                                          9    CU IDOL SELF LEARNING MATERIAL (SLM)
Figure 1.3: Android Architecture    Source:https://www.geeksforgeeks.org/android-architecture/    1.4 ANDROID STACK    Android became created withinside the open-source kernel of Linux. One predominant  purpose for selecting this kernel became that it supplied validated key capabilities for  enhancing the Android app. The capabilities of the Linux kernel are:    1. Security:    Linux kernel manages safety among machine and machine.    Memory Management:                                                                         10                       CU IDOL SELF LEARNING MATERIAL (SLM)
It manages reminiscence control for that reason giving us the liberty to enhance our apps.  Process Management:  Manages the process well, assign sources to methods every time they want them.  4.Net Stack Network:  Manages network connectivity.  5.Driver Model:  Make positive the app is running. Hardware manufacturers can construct their drivers in  Linux build.  Libraries:  Running on the pinnacle of the kernel, the Android framework is constructed with plenty of  materials. It has numerous C / C ++ libraries with many open-source equipment as:  1. Android operating time:  The android operating time incorporates the primary Java and ART libraries (Android  Runtime). Older variations had Dalvik operating time.  2. Open GL (portraits library):  This interface-language, cross-platform software application interface (API) is used to supply  2D and 3-D laptop graphics.  3. Web Kit:  This open-supply browser engine gives all of the capability to show internet content material  and simplify web page loading.  Newsgroups:  These libraries let you play and report audio and video.  5.Locket Socket Layer (SSL):  These libraries are to be had for Internet safety.    1.5 DALVIK VIRTUAL MACHINE | DVM    As we probable are conscious the superior JVM is advanced and offers terrific reminiscence  to the executives. Be that because it may, it must be advanced for low-fuelled hand held  devices additionally.  The Dalvik Virtual Machine (DVM) is an android digital gadget advanced for mobileular  phones. It enhancements the digital gadget for reminiscence, battery life, and execution.                                          11    CU IDOL SELF LEARNING MATERIAL (SLM)
Dalvik is a name of a city in Iceland. The Dalvik VM became composed via way of means of  Dan Bornstein.    The Dex compiler modifications over the elegance facts into the .dex record that unexpected  spike in call for the Dalvik VM. Various elegance files are modified over into one dex record.    We must see the incorporating and bundling degree from the source record:    Let's see the compiling and packaging procedure from the source file:                   Figure 1.4. compiling and packaging process from the source file  The javac device aggregates the java source record into the elegance report.  The dx device takes all of the elegance files of your software and creates a solitary .dex  report. It is a degree specific apparatus.  The Android Assets Packaging Tool (aapt) handles the bundling cycle.    1.6 ANDROID VS. OTHER MOBILE PLATFORMS    An superior mobileular developer can choose exclusive levels likewise but growing for  Android is a part less complicated and commendable. As a designer, all people can create  programs for the Android marketplace. Point is:  • No confirmation is required.                                          12    CU IDOL SELF LEARNING MATERIAL (SLM)
• Software Development Kit (SDK) is liberated from fee and is savvy sufficient to refresh  itself with few ticks.    • Development weather may be Windows, Linux, or Mac OS.    • Android marketplace is there for move of your programs.    • No outsider endorsement is wanted for the appropriation of programs withinside the  marketplace.    • You want a functioning internet affiliation and preference to realise, this is it!!!    • Start gaining from any location and any location, would not make any difference.    Some different transportable SDK can likewise be applied for getting to know and procuring,  for what purpose to choose android? Here is a part of the first rate highlights which make  android critically enticing and that they are:    • The programs downloaded from the marketplace and those with which the system became  transported are given equal significance.    • Windows may be made into your programs out of your very own telecellsmartphone's  domestic display via way of means of using stay backdrops, devices, and so on    • It reacts while the restrict event occurs like while a pre-determined place indicates up, the  system advises the client.    • Google Maps is the best hit on this situation.    • Open-source degree with thousands of checks which makes expectancies soak up facts  little.    How approximately we find out now no longer many contrasts amongst Android and  different prestigious levels, in particular, iOS, Blackberry, and Windows.    ANDROID VERSUS IOS    Both Android and iOS are riding elements withinside the marketplace of mobileular phones.  How approximately we pen down multiple contrasts among them.    • Android is the maximum extensively applied mobileular phone degree on earth and it's far  used by numerous system manufacturers like LG, Samsung, HTC, and so on iOS is applied  noticeably on Apple devices like iPad, iTouch, Apple TV, and so on                                                                                        13                        CU IDOL SELF LEARNING MATERIAL (SLM)
• Android allows the usage of devices, which display the programmed refreshed information.  iOS has a column of programs on the home display.  • Varieties of Android devices are available with contrasting sizes and device capacities. The  consumer can choose any of them as indicated via way of means of his/her necessity and  monetary plan.  iOS is obtainable simply on Apple devices and they'll in wellknown be costly.  • Users can go to non-android devices via GTalk.  iOS would not provide the nearby speak software to non-apple clients.  • Google chrome is obtainable on Android devices. They may be integrated with IOS devices.  iOS has Safari as a web browser which is not available for an Android system.  • Android allows far off instalments with Near subject correspondence, that's attainable via  way of means of Google wallet.  iOS offers a Passbook software, which messes approximately charge/card cards, but would  not allow far off transportable instalments.  • Android programs may be changed in C, C++, and JAVA. Anybody can down load SDK  and start generating for nothing. Clients can down load a big wide variety of programs freed  from charge.  • Android SDK is obtainable for all levels: PC, Mac, and Linux. It is an open and loose  degree.  iOS SDK is obtainable for Mac because it were. It is a close degree.    • Android system's battery can surely be supplanted.    IOS battery cannot be supplanted, henceforth one wishes to maintain the charger organized  for the module.    • Android has the second one largest software shop. Applications want everyday updates  which once more contrasts amongst numerous sorts of Android.    iOS has the most important software shop. The equal replace is wanted for all devices.    As android is tied up with Google's modern situation it's far the primary impetus in the back  of maximum sizeable people converting from iPhone to Android.    ANDROID VERSUS BLACKBERRY                                          14    CU IDOL SELF LEARNING MATERIAL (SLM)
Both android and blackberry are extreme contenders however they serve severa prerequisites.  We must pen down fine variations    • a complete touch show display enjoy may be delighted with android. Special system makers  set their very own interface at the top of the important android layer for example Samsung  has its TouchWiz, Motorola has moto blur, and so on    Most blackberries do not have a hint interface apart from hurricane and torch at the same time  as this article have become composed.    • in the instance of customization of the residence show display, android is a victor in the  marketplace. It allows severa domestic displays.    Blackberry is horrible in customization.    • android is a hint-primarily based totally framework and henceforth path is treated via way  of means of the use of shopping for and selling, tapping, and squeezing. They likewise have a  home show, again key, and so on, which shifts from one maker to another.    Blackberry offers a tune cushion to the direction. More seasoned blackberries had trackball  for the direction.    • android is a dedicated a part of in-activity programs and exclusive cool to-do-matters  programs. But Gmail, most messages want to be checked intermittently.    Blackberry is devoted to a sturdy correspondence agency. At anything factor an e-mail drops  withinside the inbox, the consumer is knowledgeable.    • android's market is first-rate while contrasted with the blackberry save.    • android programs require common updates.    Blackberry is consistent.    • android is an open-deliver degree so it very well may be changed or hacked with none  hassle. This is the reason regular updates are introduced simply so bugs can be consistent.    Blackberry uses its on worker and therefore, it's miles substantially gotten. But, on the off  hazard that employee comes up short, the issue is inescapable and it might require days to  healing the mistake.    Blackberries are usually affordable for individuals who are insured groups and need  consistent correspondence. Android offers a big patron enjoy.                                                                                                                  15                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
Android as opposed to domestic home windows    Windows have an company with Nokia. As we as a whole realise now Nokia is enabled with  the useful resource of Microsoft and it surpassed the Symbian os and placed itself in the  market. We have to pen down precise focuses about the two of them.    • an android gadget makes use of an android working system and it's far open-deliver.    Domestic home windows mobile phone uses domestic home windows strolling framework  that could be an aggregate of the open and close framework.    • android clients are allowed to choose any software program from the market and engineers  do now no longer understand a selected affiliation the save you consumer's pinnacle fees.  Say, a google map may be utilized by an understudy or a rancher to apprehend his/her  vicinity.    Home domestic home windows aim programs in moderate of give up patron.    • android machine boots itself inner more than one moments.    Home home windows telephone want to be truly booted in seconds, anyways, the set spec  will now no longer be met.    • sd card of an android device is replaceable.    The sd card can't be supplanted. With SkyDrive, you may have allotted storage.    • android applications can be a part of themselves and provide information or enables  amongst degree correspondence.    Window's phone permits every software to open in a sandbox so one-of-a-type quantities of  the running framework are left undisturbed.    • android's applications shop is noticeably widespread.    They have were given the littlest but fastest developing applications to maintain.    Home windows phone may be carried out if protection is the number one problem and  android can be implemented on the off danger which you simply want your telephone to act  savvy enough like a telephone must do.                                          16    CU IDOL SELF LEARNING MATERIAL (SLM)
1.7 SUMMARY       • Android engineering is a product pile of parts to assist cellular telephone needs.          Android programming stack carries a Linux kernel, a collection of c/c++ libraries that          are exposed thru an application structure administrations, runtime, and application.    Following are the most important components of android engineering the ones are             a. Programs           b. Android framework           c. Android runtime           d. Platform libraries           e. Linux kernel       • In those segments, the Linux kernel is the primary part in android to offer its running          framework capacities to portable and Dalvik virtual device (DVM) which is          answerable for walking a flexible application.       • A respectable android advancement information status quo requires a comprehension          of the general engineering of android. Android is finished as a product stack          engineering comprising of a Linux bit, a runtime climate and evaluating libraries, a          utility machine, and a bunch of uses. Packages are overwhelmingly written in java or          kotlin and arranged down to bytecode layout inside the android studio fabricate          weather. At the point when the application is as a result delivered on a gadget, this          bytecode is organized somewhere close to the android runtime (art) to the nearby          configuration utilized by the CPU.       • The vital objectives of android engineering are execution and effectiveness, both in          utility execution and inside the execution of reuse in the application plan.    1.8 KEYWORDS        • Media library- give support to play, record audio and video formats.      • Surface manager- The responsibility of a surface manager is to provide access to the             display.      • SQLite- SQLite provides database support, and Free-Type provides font support.      • Web-Kit- is a web browser engine which provides all the functionality to display web             content and simplify page loading.      • SSL- SSL is a technology which build an encrypted link between a web server and             web browser.                                          17    CU IDOL SELF LEARNING MATERIAL (SLM)
1.9 LEARNING ACTIVITY    1. Draw a comparative chart for different types of Operating System with features.  ___________________________________________________________________________  ___________________________________________________________________  2. Compare Dalvik Virtual Machine | DVM.  ___________________________________________________________________________  _____________________________________________________________    1.10 UNIT END QUESTIONS    A. Descriptive Questions  Short Questions        1. What is android?      2. What is the Android SDK?      3. What are the distinct variations of android os which you bear in mind?      4. Call the languages supported for android development.      5. What are the blessings of the android working device?    Long Questions      1. Explain in detail Android Architecture?      2.What are the different tools available in Android development? Explain them.      3. What is Android runtime?      4. What are the advantages and disadvantages of Android?      5. How Android different from IOS?    B. Multiple Choice Questions  1. Which section provides a key component called Dalvik Virtual Machine?        a. Libraries      b. Android Runtime      c. Application Framework      d. Applications                                          18    CU IDOL SELF LEARNING MATERIAL (SLM)
2. Which of the following libraries provides access to the application model and is the       cornerstone of all Android applications?      a. android.app      b. android.content      c. android.database      d. android.widget    3. Top Layer is known as?      a. Libraries      b. Android Runtime      c. Application Framework      d. Applications    4. Bottom layer is known as?        a. Libraries      b. Linux kernel      c. Application Framework      d. Applications    5. Android operating system is a stack of software components which is roughly divided       into how many layers?      a. 2      b. 3      c. 4      d. 5    Answers  1-b, 2-a, 3-d, 4-d, 5-c    1.11 REFERENCES    Reference Books                                                                                             19    CU IDOL SELF LEARNING MATERIAL (SLM)
• Khoshafian, et al. (1990). Object orientation: Concepts, Languages, Databases. New      York: John Wiley & Sons    • Thornsby, J. (May 2016). Android UI Design. Packt Publishing. Morris, J. (Feb      2011). Android User Interface Development - Beginner’s Guide. UK. Packt      Publishing    Websites    • https://enos.itcollege.ee/~jpoial/allalaadimised/reading/Android-UI-Design.pdf  • https://www.techotopia.com/index.php/Understanding_Android_Views,_View_Group        s_and_Layouts  • https://www.tutorialspoint.com/software_architecture_design/user_interface.htm  • https://www.wideskills.com/android/building-user-interface/listening-to-ui-        notifications-in-android  • https://developer.android.com/guide/fragments/lifecycle                                          20    CU IDOL SELF LEARNING MATERIAL (SLM)
UNIT - 2: BUILDING BLOCKS                                                                   21    Structure   2.0 Learning Objectives   2.1 Introduction   2.2 Activities        2.2.1 Activity Life Cycle   2.3 Services        2.3.1 Services Life Cycle   2.4 Content Providers   2.5 Broadcast Receiver   2.6 Intents   2.7 Summary   2.8 Keywords   2.9 Learning Activity   2.10 Unit End Questions   2.11 References    2.0 LEARNING OBJECTIVES    After studying this unit, you will be able to:      ● Learn building blocks in android      ● Implement activities and its life cycle      ● Describe about services and its life cycle      ● Explain Content Providers      ● Evaluate Broadcast Receiver      ● Implement Intents                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
2.1 INTRODUCTION    Building blocks or application components of an Android application defines the behaviour  of the application. Each Android application has four types of components; each component  plays a specific role and has its own lifecycle. They are described below.    2.2 ACTIVITY    Interest is a UI provided as a show display with which a patron communicates. For example,  assuming you open a media participant utility, the display that helps you to play, stop, next,  or past the track is an interest. An interest can each be geared up into the entire display or can  skim over unique screens. An android software should have precise sports associated with  every different. The absolute first interest that renders at the display withinside the wake of  starting the software is known as the default interest.    Movement is commonly a solitary display that the customer sees at the device at one time.  Software generally has various Activities, and the patron flips backward and forward among  them. Consequently, wearing sports are the maximum apparent piece of your utility.    Very much like a website comprises numerous pages, so does android software program  include severa Activities. Truly, like a website has a \"touchdown web page,\" an android  utility has an \"essential” movement, generally, the simplest that is proven first whilst you  dispatch the software program. What's more, very similar to a website wants to provide a  form of course amongst particular pages, an android software wishes to do likewise.    On the net, you may hop from an internet page on one internet site on-line to a web page on a  few different. Additionally, in android, you could be taking a gander on the motion of one  software program, but now no longer lengthy after you could begin any other movement in a  completely remoted software. For instance, withinside the occasion in that you are to your  contacts utility and making a decision to message an accomplice, you may dispatch the  movement to form an immediately message withinside the messaging software.    2.2.1 Activity Life Cycle    Dispatching a movement can be very luxurious. It'd embody making any other Linux  interaction, designating memory for all the UI devices, increasing each one of the devices  from XML formats, and putting in the entire display. Considering the truth that we're doing a  ton of hard work to dispatch an motion, it would be a loss to truly throw it out as quickly  because the consumer leaves that show. To stay farfar from this waste, the energetic life-style  cycle is overseen with the resource of the interest supervisor.    The motion supervisor is responsible for making, obliterating, and overseeing Activities. As  an instance, whilst the patron starts off evolved a software program curiously, the hobby  supervisor will make its activities and located them onto the show. Later on, whilst the                                          22    CU IDOL SELF LEARNING MATERIAL (SLM)
customer switches monitors, the hobby manager will glide that beyond movement to a  retaining vicinity. Thusly, if the patron wishes to go back to an extra seasoned movement, it  has a bent to start all of the greater rapidly. More hooked up wearing activities that the patron  hasn't applied in some time may be obliterated to free extra place for the at present dynamic  one. This tool is supposed to help enhance the velocity of the UI and therefore beautify the  overall client revel in.    Programming for Android is reasonably not quite similar to programming for some  extraordinary situations. In android, you emerge as reacting greater to specific changes  withinside the situation of your software program rather than using that alternate yourself. It's  miles an overseen, holder-based weather-like programming for java applets or servlets. In this  manner, as regards to an active life cycle, you do not will say what express the movement is  in, but you've got were given a whole lot of freedoms to mention what takes area throughout  the adjustments from one us of a toother. Figure 2.1 suggests the states that motion can pass  thru. Figure 2.1 shows the states that action can go through.                                          Figure 2-1. Activity life cycle    Starting state    When an асtivity doesn’t exist in memory, it's miles in а beginning country. While it’s  starting up, the асtivity will move via а entire set of саll bасk techniques that you as а  develорer have an орроrtunity tо fill оut. Eventuаlly, the асtivity will be in а running  stаte.                                          23    CU IDOL SELF LEARNING MATERIAL (SLM)
Preserve in mind that this transition from stаrting country tо going for walks stаte is  оne оf the mоst expensive орerаtiоns in terms оf соmрuting time, and this  additionally at once аffeсts the bаttery life оf the tool. This is the exасt reаsоn why we  dоn’t аutоmаtiсаlly destrоy асtivities thаt аre nо lоnger shоwn. The consumer might  wаnt tо соme bасokay tо them, sо we keeр them аrоund fоr а even as..    Running stаte    The асtivity in а Running stаte is the оne thаt is сurrently оn the sсreen аnd  interасting with the person. We аlsо sаy this асtivity is in fосus, meаning thаt аll  user interасtiоns—suсh аs tyрing, tоuсhing the sсreen, аnd сliсking buttоns—аre  hаndled through this оne асtivity. аs suсh, there is оnly оne going for walks асtivity  аt аbig apple given time.    The running асtivity is the оne thаt hаs рriоrity in phrases оf getting the memоry  аnd resоurсes it wishes tо run аs quiсkly аs роssible. This is beсаuse аndrоid wаnts  tо mаke sure the walking асtivity is ziррy аnd resроnsive tо the consumer    раused stаte    When аn асtivity is nоt in fосus (i.E., nоt interасting with the person) but  nonetheless visible оn the sсreen, we sаy it’s in а раused stаte. This is nоt а tyрiсаl  sсenаriо, beсаuse the deviсe’s sсreen is usuаlly smаll, аnd аn асtivity is either tаking  uр the whоle sсreen оr nоne аt аll. We оften see this саse with diаlоg bоxes thаt  соme uр in frоnt оf аn асtivity, саusing it tо beсоme раused. аll асtivities gо  thrоugh а раused stаte rоute tо being stоррed.    раused асtivities nevertheless hаve excessive рriоrity in phrases оf getting memоry  аnd оther resоurсes. This is beсаuse they аre visible аnd саnnоt be remоved frоm the  sсreen withоut mаking it lооokay very strаnge tо the person.    Stоррed stаte    Whilst аn асtivity is nоt seen, but nonetheless in memоry, we sаy it’s in а stоррed  stаte. Stоррed асtivity соuld be brоught bасk tо the frоnt tо beсоme а walking  асtivity аgаin. оr, it соuld be destrоyed аnd remоved frоm memоry.    The tool keeрs асtivities аrоund in а stоррed stаte beсаuse it is probable thаt the  consumer will nevertheless wаnt tо get bасokay tо thоse асtivities sоme time sооn,  аnd relaxationаrting а stоррed асtivity is fаr сheарer thаn stаrting аn асtivity frоm  sсrаtсh. Thаt is beсаuse we аlreаdy hаve аll the оbjeсts lоаded in memоry аnd  simрly hаve tо convey it аll uр tо the fоregrоund.    Stоррed асtivities саn be remоved frоm memоry аt аny роint..    Destrоyed stаte                                          24    CU IDOL SELF LEARNING MATERIAL (SLM)
а destrоyed асtivity is nо lоnger in memоry. The асtivity mаnаger deсided thаt this  асtivity is nо lоnger wished аnd hаs remоved it. Befоre the асtivity is destrоyed, it  саn рerfоrm сertаin асtiоns, suсh аs sаve аthe huge apple unsаved infоrmаtiоn.  Hоwever, there’s nо guаrаntee thаt yоur асtivity will be stоррed рriоr tо being  destrоyed. It is роssible fоr а раused асtivity tо be destrоyed аs properly. Fоr thаt  reаsоn, it is higher tо dо imроrtаnt wоrk, suсh аs sаving unsаved dаtа, stop rоute tо  а раused stаte rаther thаn а destrоyed stаte.    2.3 SERVICES    A Servive service is a software component that runs withinside the records and does now no  longer want any patron interface. For instance, in case you are using a web browser and  determine to down load a record, then the report might be downloaded withinside the history  whilst you maintain your interplay with the net browser. This is being achieved because of an  utility problem known as a service. An activity can begin a service. You can also bind an  issuer to an interest to have interaction with it.    2.3.1. Service life cycle    Also, the Service life cycle is greater or much less controlled through manner of the  developer, and not loads thru the machine. Therefore, we as developers want to apprehend to  run our services just so they don’t consume shared reasserts unnecessarily, which  incorporates the CPU and battery.                                          Figure 2.2. Service life cycle    2.4CONTENT PROVIDERS    A content provider is a component that manages the utility information saved in an SQLite  database, document system, on the net, or every other garage place accessed by your utility.  Using the content provider different programs can get entry to or regulate the statistics of  your utility. For instance, the android gadget can offer contact data to the messaging app  through the content material issuer. It's also useful in handling and querying the non-public  statistics of the app.                                                                          25    CU IDOL SELF LEARNING MATERIAL (SLM)
Although small quantities of records can be handed between programs through intents,  content material providers are a whole lot better suitable for sharing continual information  between probably massive datasets. As such, the content company API nicely adheres to the  crud precept. The parent underneath illustrates how the content company’s crud interface  pierces the application barriers and lets in other apps to connect to it to proportion data..                                          Figure 2.3 Content provider    The android device uses this mechanism all the time. As an instance, a contacts company is a  content material issuer that exposes all user touch facts to diverse applications. Settings  company exposes device settings to diverse programs, which consist of the integrated settings  software. Media hold is responsible for storing and sharing various media, inclusive of  pictures and track, throughout diverse packages. The figure under illustrates how the contacts  app uses contacts issuer, a completely separate software program, to retrieve data  approximately users’ contacts. The contacts app itself doesn’t have any touch data, and the  contacts company doesn’t have any patron interface.                                          26    CU IDOL SELF LEARNING MATERIAL (SLM)
Figure 2.4 Contacts application using Contacts Provider to get the data    This separation of data garage and the real user interface software offers greater flexibility to  mash up various parts of the gadget. As an example, a user could install an alternative address  book software that uses equal records as the default contacts app. Or, he should set up  widgets on the house display screen that permit for clean changes within the machine  settings, along with turning on or off the Wifi, Bluetooth, or GPS features. Many telephone  manufacturers take gain of content material carriers to feature their personal packages on top  of trendy android to improve basic user revel in, which includes the experience.    Content providers are pretty simple interfaces, with the standard insert(), replace(), delete(),  and query() strategies. These methods look loads like general database methods, so it is pretty  easy to put in force a content company as a proxy to the database. Having stated that, you are  much more likely to use content material carriers than write your very own.    2.5BROADCAST RECEIVERS    A published receiver is used to broadcast the bulletins to the complete device whether or not  it's miles a notification to the popularity bar to alert the consumer or it's far a message to  some other utility or interest. As an instance, in case you either get hold of a notification on  the repute bar approximately final touch of down load or receiving a textual content message  approximately the new replacement of the app, it happens due to the printed receivers. Even,  a broadcast receiver can begin a carrier at the incidence of a predefined event.    The machine itself publicizes occasions all the time. For instance, while an SMS arrives, a  name is available in, the battery runs low, or the system gets booted, all the occasions are  broadcasted, and any quantity of receivers might be prompted by means of them.                                          27    CU IDOL SELF LEARNING MATERIAL (SLM)
In our Twitter app instance, we need to start the replace carrier as soon as the gadget starts off  evolved up. To do this, we are able to join the publication that tells us the gadget has finished  booting up.    You could additionally send your personal publicizes from one part of your application to  another, or to a very exclusive application.    Broadcast receivers themselves do not have any visible representation, nor are they actively  jogging in memory. However, when triggered, they get to execute some code, along with  starting an interest, a service, or something else.    2.6 INTENTS    Intents are messages which is probably sent most of the important constructing blocks. They  cause hobby to start up, tell an issuer to start or prevent, or are definitely proclaims. Intents  are asynchronous, that means the code that sends them doesn’t have to look forward to them  to be completed. Cause perhaps express or implicit. For a selected purpose, the sender  sincerely spells out which precise problem have to be at the receiving quit. In an implicit  intent, the sender specifies the kind of receiver. For instance, your interest should ship a  reason pronouncing it truely desires someone to open up a web web page. If so, any utility  that is able to setting out a web net web page should “compete” to complete this motion. If  you've got competing packages, the device will ask you which of them ones you’d like to  apply to finish a given movement. You can moreover set an app due to the default. This  mechanism works very in addition for your laptop surroundings, for example, whilst you  downloaded firefox or chrome to replace your default internet explorer or safari internet  browsers. This form of messaging permits the patron to replace any app at the device with a  custom one. For instance, you would possibly want to down load tremendous SMS software  program or any other browser to update your modern-day ones.                                          28    CU IDOL SELF LEARNING MATERIAL (SLM)
Figure 2.5. Intents    2.7 SUMMARY    App components are the important building blocks of an android app. Everything is a get  entry to factor through which the tool or someone can enter your app. Some components rely  upon others.    There are 4 particular kinds of app components:             • Activities             • services             • broadcast receivers             • content material carriers    Every kind serves an exceptional cause and has an exceptional lifecycle that defines how the  thing is created and destroyedApp components are the important constructing blocks of an  Android app. Each issue is an access factor thru which the gadget or a consumer can input  your app. Some components rely on others.    Activities    An activity is the access thing for interacting with the user. It represents a unmarried show  with a private interface. For example, an e-mail app would possibly have one interest that  suggests a listing of new emails, each different interest to compose an e mail, and any other  hobby for studying emails. Despite the truth that the sports activities work together to shape a  cohesive client enjoy withinside the e mail app, anybody is unbiased of the others. As such, a  one-of-a-type app can begin any character of those sports if the email app lets in it. As an  example, a virtual digital digicam app can begin the interest in the e-mail app that composes  new mail to allow the character to share a photograph. An interest allows the subsequent key  interactions among gadget and app:    • preserving in track with what the client currently cares approximately (what's on-show  display) to make certain that the tool maintains strolling the process this is web website  hosting the hobby.    • understanding that formerly used techniques contain matters the consumer may also  moreover move lower back to (stopped sports activities), and consequently greater  particularly prioritize maintaining the ones procedures round.    • assisting the app cope with having its method killed so the consumer can move lower back  to sports with their previous country restored.                                                       29                 CU IDOL SELF LEARNING MATERIAL (SLM)
• providing a manner for apps to enforce consumer flows amongst each different, and for the  tool to coordinate those flows. (the maximum conventional example proper right here being a  share.)    You put into effect an activity as a subclass of the Activity class    Services    A service is a desired purpose access factor for maintaining an app jogging withinside the  historic beyond for all forms of motives. It is a part that runs in records to perform lengthy-  running operations or to perform paintings for a long way-off processes. A carrier does no  longer provide a private interface. As an example, a service might probable play song in the  historic beyond even as the client is in a one-of-a-type app, or it would fetch data over the  network without blockading user interaction with an interest. Another thing, including an  hobby, can start the service and permit it to run or bind to it as a way to engage with it. There  are absolutely very first rate semantics services that tell the gadget approximately a manner to  control an app: began out offerings inform the gadget to hold them taking walks till their art  work are completed. This can be to sync some portions of facts withinside the historic beyond  or play a tune even after the person leaves the app. Syncing information withinside the  historic beyond or playing tune additionally represent wonderful forms of started out  offerings that alter how the tool handles them:    • track playback is something the client is at once privy to, so the app tells the gadget this via  way of means of pronouncing it desires to be foreground with a notification to tell the person  about it; on this case, the tool is privy to that it has to strive in reality hard to preserve that  carrier's way running because of the truth the client may be unhappy if it's miles going away.    • an normal background carrier is not something the consumer is at once privy to running, so  the gadget has greater freedom in managing its way. It can allow it to be killed (after which  restarting the carrier someday later)    Bound services run due to the fact some different apps (or the gadget) has stated that it  desires to rent the service. This is basically the service providing an API in any other way.  The gadget because of this is aware of there may be a dependency amongst those techniques,  so if method a is positive to carrier in gadget b, its miles conscious that it wants to keep  method b (and its carrier) strolling for a. Similarly, if the gadget a is something the character  cares approximately, and then it additionally is aware of to deal with way b as something the  person moreover cares about. Because in their flexibility (for better or worse), offerings have  turn out to be out to be an in fact beneficial constructing block for all varieties of better-  diploma gadget principles. Stay wallpapers, notification listeners, show savers, input  methods, accessibility services, and lots of different centre gadget functions are all  constructed as services that programs put into effect and the tool binds to when they should  be running.                                          30    CU IDOL SELF LEARNING MATERIAL (SLM)
Broadcast receivers    A broadcast receiver is part that lets in the device to deliver activities to the app out of the  doorways of an ordinary character go together with the flow, permitting the app to answer to  device-huge broadcast announcements. Due to the truth broadcast receivers are each different  properly described get entry to into the app, the gadget can deliver pronounces even to apps  that are not currently strolling. So, for example, an app can time desk an alarm to publish a  notification to tell the consumer about an upcoming event... And via way of means of manner  of turning in that alarm to a posted receiver of the app, there may be no want for the app to  stay strolling till the alarm is going off. Many publicize originate from the device—as for  example, a published saying that the show display has become off, the battery is low, or an  image become capture. Apps also can provoke broadcasts—for example, to allow unique  apps to apprehend that some data were downloaded to the tool and are available for them to  use. Despite the truth that broadcast receivers do not show someone interface, they will create  a standing bar notification to alert the character at the same time as a broadcast occasion takes  location. Greater typically, although, a published receiver is handiest a gateway to different  components and is supposed to do a completely minimal amount of labour. For example, it  might schedule a method carrier to carry out some works based totally at the event with the  mission scheduler    A broadcast receiver is carried out as a subclass of the printed receiver and each broadcast is  added as a purpose object. For greater data, see the broadcast receiver class.    Content providers    A content provider manages a shared set of app information that you could store in the record  device, in an SQLite database, at the web, or on a few different continual storage location that  your app can get entry to. Thru the content material material company, unique apps can query  or regulate the records if the content material corporation allows it. For example, the android  tool offers a content material issuer that manages the client's contact facts. As such, any app  with the right permissions can query the content provider, which incorporates contacts  settlement. Statistics, to take a look at and write data about a particular guy or woman. It's a  long way tempting to consider a content material company as an abstraction on a database  due to the fact there is lots of API and useful resource built into them for that common  purpose. However, they've got a completely unique middle purpose from a gadget-format  attitude. To the tool, a content material issuer is an access thing into an app for publishing  named data gadgets, identified with the useful resource of a URI scheme. As a consequence,  an app can determine the way it desires to map the facts it carries to a URI namespace,  handing out those URI to unique entities which can, in turn, use them to get admission to the  data. There are a few unique matters this lets in the gadget to do in handling an app:    • assigning a URI might now no longer require that the app live taking walks, so URI can  persist after their proudly owning apps have exited. The tool best needs to make certain that                                          31    CU IDOL SELF LEARNING MATERIAL (SLM)
an owning app is still taking walks at the same time as it has to retrieve the app's records from  the corresponding URI.  • those URI moreover offer an crucial satisfactory-grained protection model. As an example,  an app can location the URI for an image it has at the clipboard however is going away with  its content material provider locked up in order that different apps can't freely get admission  to it. While a second app attempts to get admission to that URI on the clipboard, the gadget  can allow that app to get proper of access to the facts via a short URI permission deliver in  order that it's miles allowed to get entry to the data handiest in the back of that URI, but not  anything else withinside the second app.    Content vendors are useful for studying and writing facts this is private to your app and no  longer shared.    2.8 KEYWORDS        • Activity-An activity is a class that represents a single screen      • View-A view is the UI element such as button, label, text field etc. Anything that you             see is a view      • Intent-Intent is used to invoke components      • Service-Service is a background process that can run for a long time.      • Content Provider-Content Providers are used to share data between the applications    2.9LEARNING ACTIVITY    1. Create an activity life cycle that displaces a proper message in log cat.    ___________________________________________________________________________  _____________________________________________________________    2. Why do you manage the logic component and the design component one by one? Which  kind of files incorporates the common-sense element and design component?    ___________________________________________________________________________  _____________________________________________________________    3. What's an. Apk report? What are the ingredients of it? How is it created? Provide an  explanation for.    ___________________________________________________________________________  _____________________________________________________________  4. Discover and explain the contents of the “res” folder.    ___________________________________________________________________________  ___________________________________________________________                                          32    CU IDOL SELF LEARNING MATERIAL (SLM)
2.10 UNIT END QUESTIONS                                                                     33    A. Descriptive Questions  Short Questions        1. What is Activity?      2. What is Broadcast receiver?      3. What are Intents?      4. What are the Services?      5. What are the Content Provider?    Long Questions      1. What is the core building blocks of Android?      2. What is an Activity in Android? What is its lifecycle?      3. Whatare the need of AndroidManifest.xml in Android?      4. What are a Services in Android? What is its lifecycle?      5. What are Intents? Explain them?    B. Multiple Choice Questions  1. What is Pending Intent in android?       a. It is a kind of an intent     b. It is used to pass the data between activities     c. It will fire at a future point of time.     d. None of these    2. What are the layouts available in android?     a. Linear Layout     b. Frame Layout     c. Table Layout     d. Relative Layout     e. All of these    3. How to stop the services in android?     a. finish()                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
b. system.exit().  c. By manually  d. stopSelf() and stopService()    4. How many applications are there in a given task in android?     a. Two     b. One     c. Many     d. Zero    5. What are the wake locks available in android?     a. PARTIAL_WAKE_LOCK     b. SCREEN_DIM_WAKE_LOCK     c. SCREEN_BRIGHT_WAKE_LOCK     d. FULL_WAKE_LOCK     e. FULL_WAKE_LOCK    Answers:  1-c, 2-e, 3-d, 4-c, 5-e    2.11 REFERENCES    Reference Books    • Khoshafian, et al. (1990). Object orientation: Concepts, Languages, Databases. New      York: John Wiley & Sons    • Thornsby, J. (May 2016). Android UI Design. Packt Publishing. Morris, J. (Feb      2011). Android User Interface Development - Beginner’s Guide. UK. Packt      Publishing    Websites    • https://enos.itcollege.ee/~jpoial/allalaadimised/reading/Android-UI-Design.pdf  • https://www.techotopia.com/index.php/Understanding_Android_Views,_View_Group        s_and_Layouts  • https://www.tutorialspoint.com/software_architecture_design/user_interface.htm                                                                    34                             CU IDOL SELF LEARNING MATERIAL (SLM)
• https://www.wideskills.com/android/building-user-interface/listening-to-ui-      notifications-in-android    • https://developer.android.com/guide/fragments/lifecycle                                                                                   35    CU IDOL SELF LEARNING MATERIAL (SLM)
UNIT - 3: FRAGMENTS    Structure     3.0 Learning Objectives   3.1 Introduction   3.2 Types of fragments   3.3 Fragment Life Cycle   3.4 Summary   3.5 Keywords   3.6 Learning Activity   3.7 Unit End Questions   3.8 References    3.0 LEARNING OBJECTIVES    After studying this unit, you will be able to:      • Implement Fragments      • Describe the types of fragments      • Understand Fragment Life Cycle      • Brief working with fragments      • Know importance of fragments    3.1 INTRODUCTION    Fragment components encapsulate an individual segment of the user interface. They may be  crucial whilst the developer has to build or optimize a software person interface for multiple  display sizes or devices  A fragment is a reusable magnificence imposing a part of an activity. A fraction generally  defines part of a user interface. Fragments ought to be embedded in activities; they cannot run  independently of activities.                                          36    CU IDOL SELF LEARNING MATERIAL (SLM)
Figure 3.1. Fragment’s activities    Understanding Fragments    Here are the crucial matters to apprehend approximately fragments:        • a fragment is a mixture of an XML format report and a java class similar to a hobby.      • using the assist library, fragments are supported returned to all applicable android             variations.      • fragments encapsulate perspectives and good judgment in order that its miles less             difficult to reuse within activities.      • fragments are standalone additives that can contain perspectives, occasions, and logic.      • Inside a fragment-oriented structure, sports become navigational containers which are             typically accountable for navigation to different activities, imparting fragments, and           passing records.    Importance of Fragments    There are numerous use cases for fragments but the most not unusual use instances include:        • reusing view and good judgment components - fragments allow re-use of               components of your display screen along with perspectives and event good               judgment again and again in exceptional approaches throughout many disparate               activities. For instance, the use of the identical listing throughout distinctive facts               sources inside an app.                                          37    CU IDOL SELF LEARNING MATERIAL (SLM)
• tablet support - regularly inside apps, the pill model of activity has an extensively               different layout from the cellphone version which is different from the television               version. Fragments enable tool-unique activities to reuse shared factors whilst also               having variations.        • display screen orientation - frequently inside apps, the portrait model of activity               has a notable one-of-a-kind layout from the landscape model. Fragments permit               both orientations to reuse shared factors whilst additionally having differences.    Organizing your Code    Inside a fraction-heavy app, we need to recall to arrange our code according to architectural  pleasant practices. Interior of an app that makes use of fragments significantly, we need to  keep in mind that the position of pastime shifts.    Activities are navigation controllers broadly speaking responsible for:        • navigation to different activities via intents.      • supplying navigational components which include the navigation drawer or the view                 pager.      • hiding and displaying relevant fragments the use of the fragment supervisor.      • receiving records from intents and passing records between fragments.      • Fragments are content controllers and include maximum perspectives, layouts, and                 occasion good judgment such as:      • layouts and perspectives displaying relevant app content.      • occasion coping with good judgment related to relevant views.      • view state control common sense such as visibility or mistakes coping with.      • triggering of network requests thru a purchaser object.      • retrieval and storage of information from patience thru model gadgets.    To reiterate, in a fragment-primarily based structure, the sports are for navigation and the  fragments are for perspectives and common sense.    Usage    Defining a Fragment    A fragment, like an activity, has an XML report and a java class that represents the fragment  controller.    The xml document is much like another report, and can be named fragment_oof.Xml.  Consider them as a partial (re-usable) activity:    <?Xmlns version= \" 1.0 \" encoding= \" utf-8 \"?>    <LinearLayout xmlns: android= \" http://schemas.Android.Com/apk/res/android\"    Android: layout_width=\"match_parent\" android: layout_height=\"match_parent\"                                          38    CU IDOL SELF LEARNING MATERIAL (SLM)
Android: orientation=\"vertical\" >    <TextView  Android:id=\"@+id/textView1\"  Android: layout_width=\"wrap_content\"  Android: layout_height=\"wrap_content\"  Android: text=\"TextView\" />  <Button  Android:id=\"@+id/button1\"  Android: layout_width=\"wrap_content\"  Android: layout_height=\"wrap_content\"  Android: text=\"Button\" />  </LinearLayout>  The java controller for a fraction looks as if:  Import android.Fragment.App.Fragment;  Public magnificence fragment extends fragment       @override  Public view oncreateview (layoutinflater inflater, viewgroup determine, bundle  savedinstancestate)  // defines the xml report for the fragment  Return inflater.Inflate(r.format.Fragment_oof, parent,false);  // any view setup have to occur right here.       @override  Public void onviewcreated (view view, package deal savedinstancestate)  // setup any handles to view objects here  // edittexteto = (edittext) view. Findviewbyid(r.Identity.Eto);  Embedding a Fragment in an Activity  There are two approaches to add a fraction to an activity: dynamically the usage of java and  statically using XML.  Earlier than embedding a \"guide\" fragment in interest make certain the interest is modified to  extend from fragment activity or appcompatactivity which adds help for the fragment                                          39    CU IDOL SELF LEARNING MATERIAL (SLM)
supervisor to all android version. Any activity the use of fragments should make sure to  increase from fragment acitivity or appcompatactivity:  Import android. appcompat.App.Appcompatactivity;  Public magnificence MainActivity extends appcompatactivity  // ...  Statically  To feature the fragment statically, definitely embed the fragment within the interest's xml  layout document:  <?Xml version= \"1.0\" encoding= \"utf-8\"?>  <LinearLayout xmlns:  android=\"http://schemas.Android.Com/apk/res/android\"  Android: layout_width=\"match_parent\"  Android: layout_height=\"match_parent\"  Android: orientation=\"vertical\" >    <fragment  Android: name=\"com. Example1.Android. OFragment\"  Android:id=\"@+id/oFragment\"  Android: layout_width=\"match_parent\"  Android: layout_height=\"match_parent\" />    </LinearLayout>    Dynamically  The second manner is via adding the fragment dynamically in java the use of the fragment  manager. The fragment manager and the fragment transaction assist you to upload, put off  and replace fragments within the format of your activity at runtime.  In this example, you need to add a \"placeholder\" container (generally a body layout) to your  interest wherein the fragment is inserted at runtime:    <?XML  version= \"1.0\"                                                          40                    CU IDOL SELF LEARNING MATERIAL (SLM)
encoding= \"utf-8\"?>  <LinearLayoutxmlns: android=\"http://schemas.android.com/apk/res/android\"  android: layout_width=\"match_parent\"  android: layout_height=\"match_parent\"  android: orientation=\"vertical\" >  <FrameLayout  android:id=\"@+id/your_placeholder\"  android: layout_width=\"match_parent\"  android: layout_height=\"match_parent\">  </FrameLayout>    </LinearLayout>  and then you can use the Fragment Manager to create a Fragment Transaction which allows  us to add fragments to the FrameLayout at runtime:  // Begin the transaction  FragmentTransaction ft1 =getSupportFragmentManager(). beginTransaction();  // Replace the contents of the container with the new fragment  ft1.replace(R.id.our_placeholdr,new oFragment());  // or ft1.add(R.id.our_placeholdr, new oFragment());  // Complete the changes added above  ft1.commit();  If the fragment should always be within the activity, use XML to statically add the fragment  but in more complex cases be sure to use the Java-based approach.    3.2TYPES OF FRAGMENTS    Basically, fragments are divided as three stages as shown below.  1. Single frame fragments –    Single frame fragment is designed for small screen devices such as handheld  devices(mobiles) and it should be above the android 3.0 version.    Example    This example will explain to you how to create your own Fragments. Here we will create two  fragments and one of them will be used when the device is in landscape mode and another  fragment will be used in the case of portrait mode. So, let's follow the following steps to  similar to what we followed while creating Hello World Example −                                                                              41    CU IDOL SELF LEARNING MATERIAL (SLM)
Step Description    1 You will use Android Studio IDE to create an Android application and name it          as MyFragments under a package com.example1.myfragments, with blank Activity.    2 Modify main activity file MainActivity.java as shown below in the code. Here we will          check orientation of the device and accordingly we will switch between different          fragments.    3 Create a two java files PM_Fragment.java and LM_Fragement.java under the          package com.example1.myfragments to define your fragments and associated          methods.    4 Create layouts files res/layout/lm_fragment.xml and res/layout/pm_fragment.xml and          define your layouts for both the fragments.    5 Modify the default content of res/layout/activity_main.xml file to include both the          fragments.    6 Define required constants in res/values/strings.xml file    7 Run the application to launch Android emulator and verify the result of the changes          done in the application.    Following is the content of the modified main activity file MainActivity.java −             42  package com.example1.myfragments;  import android.app.Activity;  import android.app.FragmentManager;  import android.app.FragmentTransaction;  import android.content.res.Configuration;  import android.os.Bundle;  public class MainActivity extends Activity {                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
/** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);        Configuration config = getResources().getConfiguration();    FragmentManager fragmentManager = getFragmentManager();                                     43  FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();        /**        * Check the device orientation and act accordingly        */      if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {          /**           * Landscape mode of the device          */  LM_Fragementls_fragment = new LM_Fragement();  fragmentTransaction.replace(android.R.id.content, ls_fragment);  }else{          /**           * Portrait mode of the device          */  PM_Fragementpm_fragment = new PM_Fragement();  fragmentTransaction.replace(android.R.id.content, pm_fragment);        }  fragmentTransaction.commit();      }  }  Create two fragment files LM_Fragement.java and PM_Fragment.java  Following is the content of LM_Fragement.java file −  package com.example1.myfragments;                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
import android.app.Fragment;  import android.os.Bundle;  import android.view.LayoutInflater;  import android.view.View;  import android.view.ViewGroup;    public class LM_Fragement extends Fragment {    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle    savedInstanceState) {      /**        * Inflate the layout for this fragment      */      return inflater.inflate(R.layout.lm_fragment, container, false);      }  }  Following is the content of the PM_Fragement.java file −  package com.example1.myfragments;    import android.app.Fragment;  import android.os.Bundle;  import android.view.LayoutInflater;  import android.view.View;  import android.view.ViewGroup;    public class PM_Fragement extends Fragment {                                                44    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle    savedInstanceState) {      /**                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
* Inflate the layout for this fragment      */      return inflater.inflate(R.layout.pm_fragment, container, false);    }  }  Create two layout files lm_fragement.xml and pm_fragment.xml under res/layout directory.  Following is the content of lm_fragement.xml file −  <?xml version=\"1.0\" encoding=\"utf-8\"?>  <LinearLayout  xmlns:android=\"http://schemas.android.com/apk/res/android\"  android:orientation=\"vertical\"  android:layout_width=\"fill_parent\"  android:layout_height=\"fill_parent\"  android:background=\"#7bae16\">    <TextView  android:layout_width=\"fill_parent\"  android:layout_height=\"wrap_content\"  android:text=\"@string/landscape_message\"  android:textColor=\"#000000\"  android:textSize=\"20px\" />    <!-- More GUI components go here -->    </LinearLayout>                                                                             45  Following is the content of pm_fragment.xml file −  <?xml version=\"1.0\" encoding=\"utf-8\"?>  <LinearLayout  xmlns:android=\"http://schemas.android.com/apk/res/android\"  android:orientation=\"horizontal\"                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
android:layout_width=\"fill_parent\"  android:layout_height=\"fill_parent\"  android:background=\"#666666\">    <TextView  android:layout_width=\"fill_parent\"  android:layout_height=\"wrap_content\"  android:text=\"@string/portrait_message\"  android:textColor=\"#000000\"  android:textSize=\"20px\" />  <!-- More GUI components go here -->  </LinearLayout>  Following will be the content of res/layout/activity_main.xml file which includes your  fragments −  <?xml version=\"1.0\" encoding=\"utf-8\"?>  <LinearLayoutxmlns:android=\"http://schemas.android.com/apk/res/android\"  xmlns:tools=\"http://schemas.android.com/tools\"  android:layout_width=\"fill_parent\"  android:layout_height=\"fill_parent\"  android:orientation=\"horizontal\">  <fragment  android:name=\"com.example1.fragments\"  android:id=\"@+id/lm_fragment\"  android:layout_weight=\"1\"  android:layout_width=\"0dp\"  android:layout_height=\"match_parent\" />  <fragment  android:name=\"com.example1.fragments\"  android:id=\"@+id/pm_fragment\"  android:layout_weight=\"2\"                                          46    CU IDOL SELF LEARNING MATERIAL (SLM)
android:layout_width=\"0dp\"  android:layout_height=\"match_parent\" />  </LinearLayout>  Make sure you have following content of res/values/strings.xml file −  <?xml version=\"1.0\" encoding=\"utf-8\"?>  <resources>  <string name=\"app_name\">My Application</string>  <string name=\"landscape_message\">This is Landscape mode fragment</string>  <string name=\"portrait_message\">This is Portrait mode fragment></string>  </resources>  List fragments − framework's ListFragment is supported by Static library version prior to  Android 3.0.  The basic implementation of list fragment is for creating list of items in fragments                                          Figure 3.2. List in Fragments    Example    This example will explain you how to create your own list fragment based on arrayAdapter.  So let's follow the following steps to similar to what we followed while creating Hello World  Example −                                          47    CU IDOL SELF LEARNING MATERIAL (SLM)
Step Description    1 You will use Android Studio to create an Android application and name it          as SimpleListFragment under a package com.example1.ts7.myapplication, with blank          Activity.    2 Modify the string file, which has placed at res/values/string.xml to add new string          constants    3 Create a layout called list_fragment.xml under the directory res/layout to define your          list fragments. and add fragment tag(<fragment>) to your activity_main.xml    4 Create a List_Fragment .java, which is placed at java/List_Fragment .java and it          contained onCreateView(),onActivityCreated() and OnItemClickListener()    5 Run the application to launch Android emulator and verify the result of the changes          done in the application.    Before coding we will initialize the string constants in                                    48  string.xml file  <?xml version=\"1.0\" encoding=\"utf-8\"?>  <resources>  <string name=\"app_name\">List_Fragment_Demo</string>  <string name=\"action_settings\">Settings</string>  <string name=\"hello_world\">Hello world!</string>  <string name=\"img_desc\">imgdesc</string>    <string-array name=\"Planets\">  <item>Sun</item>  <item>Mercury</item>  <item>Venus</item>                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
<item>Earth</item>  <item>Mars</item>  <item>Jupiter</item>  <item>Saturn</item>  <item>Uranus</item>  <item>Neptune</item>  </string-array>    </resources>  Following will be the content of res/layout/activity_main.xml file. Containing linear layout  and fragment tag.  <?xml version=\"1.0\" encoding=\"utf-8\"?>  <LinearLayout  xmlns:android=\"http://schemas.android.com/apk/res/android\"  android:layout_width=\"match_parent\"  android:layout_height=\"match_parent\"  android:orientation=\"vertical\" >    <fragment  android:id=\"@+id/fragment1\"        android:name=\"com.example1.ts7.myapplication.List_Fragment \"  android:layout_width=\"match_parent\"  android:layout_height=\"match_parent\" />    </LinearLayout>  Following will be the content of res/layout/list_fragment.xml file. it contained linear  layout,list view and text view  <?xml version=\"1.0\" encoding=\"utf-8\"?>  <LinearLayout  xmlns:android=\"http://schemas.android.com/apk/res/android\"                                                                      49                          CU IDOL SELF LEARNING MATERIAL (SLM)
android:layout_width=\"match_parent\"  android:layout_height=\"match_parent\"  android:orientation=\"vertical\" >    <ListView  android:id=\"@android:id/list\"  android:layout_width=\"match_parent\"  android:layout_height=\"wrap_content\" >  </ListView>    <TextView  android:id=\"@android:id/empty\"  android:layout_width=\"match_parent\"  android:layout_height=\"wrap_content\" >  </TextView>  </LinearLayout>    the following will be the content of the src/main/java/List_Fragment .java file. before writing  to code, need to follow few steps as shown below        • Create a class List_Fragment and extend it to ListFragment.      • Inside the onCreateView() method, inflate the view with the above-defined             list_fragment XML layout.      • Inside the onActivityCreated() method, create an arrayadapter from resource ie using             String array R.array.planet which you can find inside the string.xml and set this           adapter to listview and also set the onItem click Listener.      • Inside the OnItemClickListener() method, display a toast message with the Item name           which is being clicked.    package com.example1.ts7.myapplication;                                                     50  import android.annotation.SuppressLint;  import android.app.ListFragment;  import android.os.Bundle;                                                          CU IDOL SELF LEARNING MATERIAL (SLM)
                                
                                
                                Search
                            
                            Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
 
                    