Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
229 views

Android Application Development

Uploaded by

hiteshbharda696
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
229 views

Android Application Development

Uploaded by

hiteshbharda696
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 156

New Edition

MU
Choice Based Credit System (CBCS) with effect from
Academic Year 2022-20023

Android Application
Development
(Skill Enhancement Course (SEC)) (Code : USCS405)

S.Y.B.Sc. (Computer Science)Semester IV


Dr. ShraddhaSable Dr. Srividhya Murali
Nikisha Dakee (Gawand)
TM

Tech Knouwledge
PubliCati0ns
Course Contents:

Unit No of
Topics
Lectures

Introduction to Kotlin: Basics of Kotlin, type


conversions, comments, Kotlin 15

operators, variables in Kotlin, packages, visibility modifiers, control flow


statements, Concept of 0OPS in Kotlin, classes in Kotlin, delegation and
extension functions, the companion object,
Advanced Concepts in Kotlin: declaring and calling functions, parameters, and
arguments in Kotlin, default argument, variable number of arguments, unit
returning function, explicit return type, lambda expression, coroutines,
Collections in Kotlin, Mutable and Immutable Collections, Ranges, type Checks,
casting concept, this expression, Null safety, exception handling, annotations
App Development with Android Studio :Android Architecture, Android
Application Framework, Android Virtual Device, Creating and running First
Android Application, working with Physical Android Device, Adding Kotlin Files
in Android Studio

Basics Of Android : Application Components: Activities, Intent, and Broadcast


Receiver, Services, Fragment, Activity Life Cycle, Content Provider, Widgets, and
Notifications

(Refer Chapter - 1)
15
II Designing Android UI: User Interface (UI), Layout and Its Types, Layout
Themes, Event
Attribute, working with Views, Android UI Controls, Styles and
application, dialog in
Handler, setting up themes in Manifest and from the
activity,using intents, fragments
ImageSwitcher, ListView,
Handle Images, Listview And Menu:ImageView,
menu, Context menu, pop
Menu, and its types, Designing menu in XML, Option
of Views
menu, Screen Navigation,RecyclerView, Interaction
Data binding in Android :AdapterView, Spinner, Gallery view,
AutotextCompleteView, screen orientation, Design the view dynamically

Implementing Data Persistence : Data Storage-Shared Preference, Internal


And External Storage Storing Data Using SQLite Databases, Content Provider.
Firebase Real-Time Data

(Refer Chapters - 2,3,4 and 5)


Unit Topics No of
Lectures
III
Graphics, Animations, and Integrating Media in Android :Drawable Class, 15

Animation in Android, MediaPlayer API and in Android, Mediaplayer and


AudioManger Class,
Interacting With Camera and input gestures : Android Camera, Input
gestures-multiple touch,swipe, drag, scroll, zoom, Recording
Gathering Location Data:

Managing Background Tasks :Broadcaset Receivers, Services, Threads and


Process, AsyncTask, JobScheduler, Manage device Awake State

Deploying Android applications on Google Play-Publishing/Deploy the


application, Versioning, signing Application

(Refer Chapters -6, 7, 8 and 9)

D00
Chapter 1: Introduction to Kotlin 1-1 to 1-79

1.1 Introduction to Kotlin. 1-1


1.1.1 Characteristics of Kotlin ..1-1
1.1.2 Applications of Kotlin. 1-2
1.1.3 Kotlin Setup. 1-2
1.1.4 Kotlin Data Types wo.. 1-6
1.1.5 Kotlin Type Conversions. 1-6
1.1.6 Kotlin Comments
1-7
1.1.7 Kotlin Operators 1-7
1.1.8 Kotlin Variables. 1-8

1.1.9 Kotlin Control Flow Statements. 1-10

1.1.9(A) if statements. 1-10

1.1.9(B) while loop. ... 1-14

1.1.9(C ) do while. 1-14

1.1.9(D) for loop.. 1-15

1.1.9(E) when loop. 1-17

1.1.9(F) Break and Continue.. 1-17

1.1.10 Kotlin Packages .. 1-19

1.1.11 Kotlin visibility modifiers.. 1-19

1.1.12 Kotlin 0OPs Concepts. 1-21

1.1.12(A) Class in Kotlin 1-21

1.1.12 (B) Kotlin Setters and Getters. 1-23

1.1.12(C) Kotlin Constructors. 1-24


1.1.13 Kotlin delegation and extension Functions:. 1-24
1.1.14 The companion object. 1-26
1.2 Advanced Concepts in Kotlin.. s...1-27

1.2.1 Declaring and Calling Functions.. 1-27


1.2.2 Parameters and Arguments 1-28
1.2.3 Default Arguments. 1-29

1.2.4 Variable Number of Arguments.. 1-33


1.2.5 Unit-returning Function. . 1-34
1.2.6 Explicit return types 1-35

1.2.7 Lambda Expression. 1-35


1.2.8 Coroutines. 1-36

1.2.9 Collections in Kotlin 1-37

TechKneleë
PubIicattons
(MU_BSC_Comp.) 2
Android Application Development
1.2.10 Mutable and Immutable Collections.
Table otConte
1.2.11 Ranges..
1.2.12 Type Checks.

1.2.13 casting Concept.

1.2.14 This Expression.


1.2.15 Nullsafety
1.2.16 Exception Handling. 1-4
1.2.17 Annotations......
App Development with Android Studio.
134
1.3

1.3.1 Android Architecture.


.1-55
1.3.2 Android Application Framework.
.16]
1.3.3 Android Virtual Device....
1-62
1.3.4 Creating and running First Android Application 1-63
1.3.5 Working with Physical Android Device.. .1-69
1.3.6 Adding Kotlin Files in Android Studio. .1-71
1.4 Basics of Android
.1-72
1.4.1 Application Components 1-73
1.4.1(A) Activities... 1-73
1.4.1(B) Intent.. 1-73

1.4.1(C) Broadcast Receiver. .1-73


1.4.1(D) Services ...1-73
1.4.1(E) Content Providers. 1-74

1.4.1(F) Widgets. 1-75

1.4.1(G) Notifications. 1-75

1.4.1(H) Fragment. 1-75

1.4.1(1) Activity Life Cycle... .1-76

Chapter 2: Designing Android UI 2-1 to 2-18

2.1 User Interface (UI).. 2-1

2.2 Layout and its types. 2-1

2.2.1 Types of layouts. 2-2

2.3 Layout attributes.


2-7
2.4 Working with views.
2-8
2.5 Android UIControls.
as..2-10
2.6 Styles and Themes.
..2-13
2.7 Event Handler.

Publtcaticns
Android Application Development (MU_BSC_ Comp.) 3 Table of Contents

Setting up themes in Manifest and from the application.. ...2-15


2.8

Dialog in activity. ..2-16


2.9

Using intents ..2-17


2.10

Using Fragments.. ..2-18


2.11

Chapter 3 : Handle Images, Listview And Menu 3-1 to 3-8

Image View.......... ..3-1


3.1

ImageSwitcher .3-3
3.2

3.3 ListView.
3-5
3.4 Menu and its types..
Designing menu in XML .3-6
3.5
.3-7
3.6 Screen Navigation
3-8
3.7 RecyclerView.

Chapter 4: Data binding in Android 4-1 to 4-9

4-1
4.1 Android Adapter.
4-2
4.2 AdapterView...
4-4
4.3 Spinner (Dropdown List).
4-5
4.4 Gallery View....
4-5
4.4.1 Attributes of Gallery View..
4-6
4.4.2 Methods Of Gallery
4-8
4.5 AutoCompleteTextView.......
4.5.1 Important methods of Auto CompleteTextView... .4-8

Screen orientation. ....4-9


4.6
.4-9
4.7 Design the view dynamically..
Chapter 5: Implementing Data Persistence 5-1 to 5-12

.5-1
5.1 Data Persistence.

5.2 Internal and External storage .5-5


eena 5-6
5.3 SQLite Database . .
5.4
.5-7
Content Provider......

Working of the Content Provider. .5-9


5.4.1

5.4.2 Operations in Content Provider. .5-9


esn.5-10
5.6 Firebase Realtime Data

5.6.1 Features of Firebase Realtime Database... .5-11

Structuring the Realtime Database ... 5-11


5.6.2

5.6.3 Writing/Inserting data into Firebase Realtime Database. .5-12

Tchknoulede
PubCations
(MU_BSC_Comp.) 4
Android Application Development

Chapter 6: Graphics, Animations, and Integrating Media


in Android Table ofCo
6.1 Drawable.
6.2
Animation inAndroid

6.3 Media player API.


6.4 Audio Manager.

Chapter7: InteractingWith Camera and input gestures

7.1 Android Camera 74t07


7.1.1 Using Intent.

7.1.2 Using Camera API...


7.1.3 Camera Class..
1.
7.2 Input Gestures...
7.3 Long Preass, Fling.
7.4 Drag and Drop..
7.5 Transfrom Gesture
7.6
Recording..
Chapter 8: Managing Background Tasks
&-1 to &8
8.1
Managing Background Tasks. 8-1
8.1.1 Broadcast Receiver.. -8-1
8.1.2 How to receive Broadcast
.81
8.1.3 Register Receiver.. .8-2
8.1.4 Sending Broadcast... -8-2
8.2
Services.... .8-2
8.3 Threads and Process 8-4
8.3.1 Threads. 8-4

8.3.1(A) Types.. 8-9

8.3.2 Process..
8.4 AsynTask, 8-6
8.5 JobScheduler. 8-7
8.6 Manage device Awake State. .8-7

9-1 to93
Chapter 9: Deploying Android applications on Google Play
9.1 9-1
Publishing.
9.1.1 Configure app for release. 9-1

9-2
9.1.2 Releasing the app.
9-2
9.1.3 Versioning..
9-2
9.1.4 Signing Application..

TechKnowledgë
UbicationS
7
UNIT - III
Interacting With
Camera and input gestures
Syllabss

Android amera, Input gestures-multiple touch, swipe, drag, scroll, zoom, Recording

allowing
The Android framework includes support for various cameras and camera features available on devices,
you to capture pictures and videos in your applications.

7.1 Android Camera

They are two ways, in which user can use camerain any application
Using existing android camera application in our application
Directly using Camera APlprovided by android in our application
7.1.1 Using Intent
Intent intent new
Intent(android.provider. MediaStore.ACTION _IMAGE_CAPTURE);
startActivity (intent)
7.1.2 UsingCamera API
The Android framewerk supports capturing images and video through the android.hardware.camera2 API The
android.hardware.camera2 is the primary API to control the camera. It helps to take picture or videos while
building camera application.
In addition tothis we should set the camera permission and storage permission, camera feature in the manifest
file.
<uses-permission android:name="'android.permission.CAMERA" />
<uses-featureandroid:name="android.hardware.carnera"/>
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

7.1.3 Camera Class

Camera class is used to control device camera. The Camera class is used to set image capture settings, start/stop
for video.
preview,snap pictures, and retrieve frames for encoding
To take pictures with this class, use the following steps:
1. Obtain an instance of Camera from open (int).
2. Get existing (default) settings with getParameters().
and
3. If necessary, modify the returned Camera. Parameters object
callsetParameters (android.hardware.Camera.Parameters).
Android Application Development 7-2
Interacting With Camera and input gestures
CallsetDisplayOrientation(int) to ensure correct
4
orientation of preview.
5 Pass the initialized SurfaceHolder to setPreviewDisplay(android.view.SurfaceHolder). Without a surface, the
camera will be unable to start the preview.
6. CallstartPreview) to start updating the preview surface. Preview must be started before you can take a picture.
7 calltakePicture

Condroi d.hardware.
PictureCallback, Camera.ShutterCallback,PictureCallback)
android.hardware.Camera. android.hardware.toCcapture
amera.Piactphoto
ureCallback,android.hardwar.Camera.
o After taking a picture, preview display will have stopped. To take more photos, call startPreview) again first.
9. Call stopPreview) to stop updating the preview surface.
10 Call release) to release the camera for use by other applications.
11. The following is a sample snippet for accessing camera and capturing picture in kotlin
fungetCameralnstance0:Camera?{
returntry
Camera.open(0// attempt to get a Camera instance
}catch (e:Exception){
1/Camera is not available (in use or does not exist)
null//returns null if camera is unavailable

valcaptureButton:Button=findViewByld(R.id.button _capture)
captureButton.setOnClickListener{
/get an image from the camera
mCamera?.takePicture(null,null, picture)

Camera features

It is also necessary to check the availability of camera features as not all the features are supported by android.
availability of camera features by getting an instance of a camera's parameters object, and checking the relevant
methods

Android supports a wide array of camera features such as picture format, flash mode, focus settings, and many
Parametersobiect
more. Most camera features can be accessed and set using the through Camera.
tis necessarvto check the camera feature availability it 1s one by getting an instance of a camera's parametere
obiect we can check the availability of camera reatures bY getting an instance of a camera's parameters obiect
methods
and checking the relevant
focus mode feature is available or not
Thefollowing code helps to check whether auto
valparams:Camnera.Parameters?=camera?.parameters
valfocusModes:List<String>?=params?.supportedFocusModes
if(focusModes?.contains(Camera.Parameters.FOCUS_MODE_AUTO)==true)f
1/Autofocus mode is supported

Tech
p
Kaowledge
shAt i0n5
Interacting With Camera and input gestures
Android Application Development 7-3
Most camera features are activated and controlled using a Camera.Parameters object. You obtain this object hy

first getting an instance of the Camerai object, calling the


getParamneters() method.
val params: Camera.Parameters? = camera?.parameters
params?.focusMode=Camera.Parameters.FOCUS MODE_AUTO
camera?.parameters= params
Some of the other features include
Metering areas -, Set one or more areas within an image to use for focus
Focus areas -Specify one or more areas within an image for calculating white balanco
focus. metering and white balance
Face detechon -ldentify human faces within a niclure and 1se them for
Time lapse video-Record francs with set delays torecord a time lapse video
7.2 Input Gestures

Gestures willallow users to interact with an app via touch gesture. Android gestures can be divided into the
following categories:
Navigation gestures: User can move aroundthe application
Action gestures : This allow the user tocomplete an action.
Transrorm gestures : These allow the user to change an element's size, position and rotation, for example
pinching to zoom into an image or map.
Touch Gesture

When a user places one or more fingers on the touch screen, and your application interprets that pattern of
touches as a particular gesture. This includes tap, double-tap, pinch, swipe,drag, long press and fing.
The gesture starts when the user first touches the screen, continues as the system tracksthe position of theuser's
finger(s), and ends by capturing the final event of the user's fingers leaving the screen.
A MotionEvent also describes the touch event's state, via an action code. These are some of the action code used:
ACTION_DOWN. This state indicates that a touch event has started. This is the location where the pointer
first makes contact with the screen.
ACTION_MOVE. This contains the pointer's most recent X and Y coordinates, along with any intermediate
points since the last DOWN or MOVE event.
ACTION_ UP. Touch event has finished is indicated by this state.
The MotionEvent objects transmit the action code,and axis values to the onTouchBack)event callback method.

7.3 Long Preass, Fling

Android also provides GestureDetector class for detecting common gestures like long press,fling.scroll etc.
GestureDetector. OnGestureListener notifies users when a particular touch event has occurred It is required to
override onTouch Event) method, and pass along all observed events to the detector instance.
overridefunonTouchEvent(event:MotionEvent):Boolean{
returnif(mDetector.onTouchEvent(event)){
true

Jelse{
super.onTouchEvent(event)

Publt(otios
Android.Application Development
7-4
Drag and Drop Interacting With Camera and input gestures
7.4
on operation fora
touch gesture is to use it to drag an
the user drag an on-screen image. Note the
object across the screen. The
following: following snippet lets
In adrag (or scroll)
operation, the app has to keep track of the original
fingers get placed on the screen pointer (finger), even if additional
The following snippet enables a user to
drag an object around on the screen
overridLetefunonTouchEvent
/ the (ev:MotionEvent
ScaleGestureDetector ):Boolean{
inspect events.all
mScaleDetector.onTouchEvent(ev)
val action
=MotionEventCompat.getActionMasked (ev)
when(action){
MotionEvent.ACTION_DOWN->{
MotionEventCompat.getActionlndex(ev).also
1/Remember where we started (for {pointerlndex->
dragging)
mLastTouchX=MotionEventCompat.getX(ev,pointerindex)
mLastTouchY=MotionEventCompat.getY(ev,pointerlndex)
|/Save the ID of this pointer (for dragging)
mActivePointerld=MotionEventCompat.getPointerld (ev,0)

MotionEvent.ACTION_MOVE->{
1/Find the index of the active pointer and fetch its position
val (x:Float, y:Float)=
MotionEventCompat.findPointerindex(ev,mActivePointerld).let
//Calculate the distance moved
(pointerindex->
MotionEventCompat.getX(ev,pointerlndex) to
MotionEventCompat.getY(ev,pointerlndex)

mPosX+=X-mLastTouchX
mPosY+=y-mLastTouchY

invalidate0

/Remember thistouch position for the next move event


mLastTouchX= x
mLastTouchY= y

MotionEvent.ACTION _UP,MotionEvent.ACTION_CANCEL->
mActivePointerld= INVALID_POINTER_ID

Tech K
Interacting With Camera and input
Android Application Development 7-5 gestures
MotionEvent.ACTION POINTER UP->{

MotionEventCompat. getActionIndex(ev).also {pointerlndex->


MotionEventCompat.getPointerld(ev,pointerlndex)
takelf{it ==mActivePointerld)
?.run {
//This was our active pointer goingup. Cho0se a neW
//active pointer and adjust accordingly.
valnewPointerlndex=if(pointerlndex==0)1else0
mLastTouchX=MotionEventCompat.getX(ev,newPointerlndex)
mLastTouchY=MotionEventCompat.getY(ev,newPointerlndex)
mActivePointerld=MotionEventCompat.getPointerld(ev,newPointerlndex)

Returntrue

7.5 Transfrom Gesture

ScaleGestureDetector to pinch zoom in or zoom out imagview in android application.


In general terms, detecting pinch gestures involves the following three steps :
Declaration of a new class which implements the SimpleOnScaleGestureListener interface including the required
onScale(0, onScaleBegin() and onScaleEnd) callback methods.
Creation of an instance of the ScaleGestureDetector class, passing through an instance of the class created in step
1as an argument.
Implementing the onTouchEvent() callback method on the enclosing activity which, in turn, calls the
onTouchEvent) method of the ScaleGestureDetector class.
The following snippet shows the code for scrolling and scaling:
privatevalmCurrentViewport-RectF(AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX, AXIS_ YMAK)
privatevalmContentRect:Rect?=null

overridefunonTouchEvent(event:MotionEvent):Boolean{
returnmScaleGestureDetector.onTouchEvent[event)
I|mGestureDetector.onTouch Event(event)
||super.onTouch Event[event)

**
* The scale listener, used for handling multi-finger scale gestures.
*/
Tech Knouledge
PubltaticnS
Android,Application Development
7-6
Interacting With Camera and input gestures
privatevalmScaleGesturel,istener=object:ScaleGestureDet ctor.SimpleOnScaleGestureListener){
**
*This is the active focal
*yariable but kept
pointin terms of the viewport. Could be a
here to minimize per-frame local
allocation's.
privatevalviewportFocus=PointF)
privatevarlastSpanX:Float=0f
privatevarlastSpanY:Float=0f
|/Detects that new
pointers are going down.

overllaaissdtteSSfpanX=s
returntrue
upanY=snonScacclalaleBeeGesGeseginttuu(srrceeaDetDetleGeeectctstoourrr..cceururDerreetentntctSSopanXpanYr:ScaleGestureDetector):Bo lean{
overvalridefspanX:
unonScalFloate=(sscalcaleeGesGesttuurreDet
eDeteectctoorr.:SccalurrenteGesSpanXtureDetector):Boolean{
valspanY:Float=scaleGestureDetector.currentSpanY
valnewwidth:Float-lastSpanX/ spanX*mCurrentViewport.w idth)
valnewHeight:Float=lastSpanY / spanY*mCurrentViewport.height)
valfocusX:Float=scaleGestureDetector.focusX
valfocusY:Float=scaleGestureDetector.focus Y
|/ Makes sure that the chart point is within the chart
region.
1/See the sample for the implementation of hitTest0).
hitTest(focusX, focusY,viewportFocus)

mContentRect?.apply {
mCurrentViewport.set(
viewportFocus.x-newWidth*(focusX- left) / width),
viewportFocus.y-newHeight*(bottom -focusY) / height(),
0f,
0f
)

mCurrentViewport.right-mCurrentViewportleft+newWidth
mCurrentViewport.bottom=m CurrentViewport.top-+newHeight
display.
// Invalidates the View to update the
ViewCompat.postlnvalidate0nAnimation(this@InteractiveLineGraphView)

lastSpanXspanX
lastSpanY=spanY
Interacting With Camera and input
Android Application Development 7-7
gestures
returntrue

a
In addition to this android Zoom Control is a class that bas some set of methods that are used to contral
zoom functionality.
Methods

show) : shows the zoom controls on the App UI.


hide() : hide the zoom controls on the App Ul.
setOnZoomlnClickListener(OnClickListenerlistener) : This method is invoked when Zoom In button is
pressed.

setlsZoomOutEnabled (booleanisEnabled) :To enable or disable the zoom out functionality.


Setzoomspeed(ong speed):To set the zoom speed of the zoom that is being done with zoom controls

7.6 Recording
Recording class is used for currently active recording, An active recording is created by starting a pending
recording with start. Either stop or close can be called when it is desired to stop the recording.
class Recording: AutoCloseableis the class used for recording in android.
Some of the methods are start), stop(0, resume0, close) and pause0.

Review Questions

Q. 1 Explain in detailabout Camera class.


Q. 2 Write a note on camera features.

Q.3 What is gesture,explain types of input gestures.


Q. 4 Explain in detail about motion gestures.
Q.5 Discuss on Transform gestures.

DOO
8
UNIT - III
Managing Background Tasks
Syllabus
Rroadcaset Receivers, Services, Threads and
Process, AsyncTask,
JobScheduler, Manage device Awake State

8.1
Managing Background Tasks
8.1.1 Broadcast Receiver
This is used to listen to
system-wide broadcast events or intents.
When any of these events occur it brings the application into action by
performing a task. either creatinga status bar
notification or
Example include ending a low battery message or
screen turned off message to the app etc.
Generally, we use Intents to deliver broadcast
events to other apps and Broadcast
notifications to let user know that broadcast event occurs. Receivers use status bar
Broadcast Receiver is implemented as a subclass of Broadcast Receiver and each broadcast is
an Intent object. delivered as
We can register an app to receive only few
broadcast messages based on our requirements.
When a new broadcast received, the system will
check for specified broadcasts have
that it will routes the broadcasts to the apps. subscribed or not based on
There are mainly two types of Broadcast Receivers:
StaticBroadcast Receivers: These types of
Receivers are declared in the manifest file and works even if
app is closed. the

Dynanic Broadcast Receivers : These types of receivers work only if the app is active or
minimized
8.1.2 How to receive Broadcast
It is done by two ways
1. registering a broadcasts using android application manifest file (AndroidManifest.xm), We neod
specify <receiver> element in apps manifest file likeas shown below.
<receiver android:name=". SampleBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BO0T_COMPLETED"/>
<fintent-filter>
</receiver>
8-2
Managing Background Taske
Android Application Development
2. Another way is to register a receiver dynamically
To register broadcast receiver we need to extend our class using BroadcastReceiver and need to implement

a onReceive(Context, Intent)method like as shown below


class MyReceiver :BroadcastReceiver(){

override fun onReceive(context: Context, intent: Intent) |


is receiving
/TOD0: This method is called when the BroadcastReceiver
l an Intent broadcast.

throw UnsupportedOperationException("Not yet implemented")

8.1.3 Register Receiver


Register receiver by calling registerReceiver()

8.1.4 Sending Broadcast


Broadcasts can be sent in apps using three different ways,those are
Method Description
receiver at time
Send ordered broadcast (Intent, string)|This method is used to send broadcasts to once

sendBroadcast (Internet) This method is used to send broadcast to all receivers in an


undefined order

LoadBroadcastMagager.sendBroadcast This method is used to send broadcasts to receivers that are in the
same app as the sender

The following code demonstrates how to send broadcast


Intent).also {intent ->
intent.setAction("com.example.broadcast.MY_NOTIFICATION")
intent.putExtra("data", "Nothing to see here, move along.")
sendBroadcast(intent)

sendBroadcast(Intent) method.
we can create our own custom broadcastS using intents.using

8.2 Services
background and does not
Service is an application component that can perform long-running operations in the
A
provide a user interface.
switches to another application.
Service might continue running for some time, even after the user
Interact with a content provider.
It is used in Network transactions, Play music, Perform file l/0,

Types
Notification. Foreground services continue running
Foregroundservices are noticeable by the user. It displays a
even when the user isn't interacting with the app. eg. audio app.
BE Tech Kaouledge
Pubt atiops
AndroidApplication Development 8-3
Background service performs an Managing Background Tasks
operation that isn't directly
noticed by the user. For
compaction. example, storage
Bound-service offers a client-server interface that allows
serrvices have 2 possible components to interact with the service
In android, paths tocomplete its life cycle namely
Started and Bounded.
Started| Service (Unbounded Service)
1.
ice will be initiated when an
application component calls the startService)method. Once
service can run continuously in the
initiated, the
background even if the component is destroyed which was responsible for the
ctart of the service. Two options are available to stop the execution of
service:
By calling stopService) method,
The service can stop itself by using stopSelf) method.
Callto
startService()

onCreate()

onStartCommand()

Service Active
running Lifetime

The service is stopped


by itself or a client

onDestroy()

Service
shut down
Unbounded
service

Fig. 8.2.1

2 Bounded Service
componntr
in a client-server interlace. By folowing this path, android application
It can be treated as a server
fetch results.
send requests to the service and can
can component binds itself with a service by
termed as bounded when an application thamea
A service is
the execution or this servnce, all the components must unbind
stop
calling bindService)method. To method.
using unbindService()
from the service by
8-4
Managing Background Tasks
Android Application Development

Call to
bindService()

onCreate()

onBind()

Active
Clients are bound
Lifetime to service

All clients unbind by calling


unbindService()

onUnbind()

onDestroy()

Service
shut down

Bounded
servíce

Fig. 8.2.2
which is extending the class Service. Some of the
A user-defined service can be created through a normal class
methods are onStartCommand),onBind),onCreate),onUnbind) etc.

8.3 Threads and Process

8.3.1 Threads
operations without interrupting the
Thread is a lightweight sub-process that provides us a way todo background
User Interface (UI).
Single thread is created when the app is launched.
main thread. The main thread's primary role
The thread which is created by the runtime system is known as the
is to handle the UI.

All threading components belong to one of two basic categories.


The fragment or activity attached threads : activity/fragmentis
these are terminated as soon as the
bound to the lifecycle of the activity/fragment and
destroyed. Thread components under thiscategory are AsyncTask, Loaders.
The fragment or activity not attached threads :
They can run beyond the lifetimeof the activity or fragment from which they were spawned.
Thread components under this category are Service, Intent Service.

Publitatlons
AndroidApplication Developrment 8-5
Managing Background Tasks
8.3.1(A)Types
thread in
of android. They are
el have 5 ypes
We
hread :When the app is launched the first
thread of execution called the "Main
Thred :Every app in Android has its own Thread".
thread which is responsible for running the UI
acts The UI thread is where all of our
app components (like activities,
objects, like view
broadcast receivers) are created. services, content providers, and
Worker Thread : The worker thread is a background
thread. The worker threads are created separately, other
than threads like the UIthread.
Any Thread:The annotated method can be called
from any thread.
Binder Thread : Binder thread represents a separate thread of service. The
binder is a mechanism that provides
inter-process communication.
Example
val t1 =Thread(Runnable{
//Some Activity

val t2
= Thread(Runnable{
1/Some Activity

8.3.2 Process
Aprocess is a program in execution. To accomplish a task, a process needs resources. For instance, CPU fle.
memory, etc. Resources are allocated to processes in two stages i.e., the stage when process was created or
dynamically allocate the process while they are running.

Program Execution Process

Fig. 8.3.1 : Process

different states at any given time:


A process can be any one of five

1. Foreground process:The app you're


using is considered the foreground process.
foreground, but 1s still aftecting what you see on vour seveen
2. Visible process: A visible process isnt in the
screen.
process: A service process 0sn't tied to any app that's visible on your
3. Service
the user.
process : Background processes are not currently visible to
4. Background
process doesn't contain any app data anymore
empty
J. Empty process : An

ETech Kaouledge
Pub|:àtio
Managing Background Tasks
8-6
Android Application Development

8.4 AsyncTask
instruction in the
In Android, AsyncTask (Asynchronous Task) allows
users to run the background and then
synchronize again with our main thread.
main thread.
Ithelps to communication betweenbackground thread to
AsyncTask class are defined below :
The basicmethods used in an android The h2eis
method contains the code which needs to be executed in baCkground. I
dolnBackground(): This
methods used in an android AsyncTask class are defined beloW:
background.
which needs to be executed in
olnBaCkground() :This method contains the code
background processing start
onPreExecute) : This method contains the code which is executed before the
o processing. The basir
dolnBackground method completes
onPostExecute) : This method is called after
methods used in an android AsyncTask class are defined below :
be executed in background.
olnBackground):This method contains the code which needsto
are given belowW :
The three generic types used in an android AsyncTask class
Params:The type of the parameters sent to the task upon execution
background computation
Progress:The type of the progress units published during the
Result: The type of the result of the background computation
The below example shows the implementation kotlin code of asynctask
classMainÁctivity :AppCompatActivity0 {

override fun onCreate(savedinstanceState: Bundle?) {


super.onCreate(savedinstanceState)
setContentView(R.layout.activity_main)

valmyTask = MyTask)
myTask.execute(10)
}

classMyTask {

override fun onPreExecute){


super.onPreExecute0

override fun dolnBackground(vararg params: Void?): String? {


l/...

Publit2tiet
Android Application Development 8-7

Override fun onProgressUpdate(values: Int?) {


Managing Background Tasks
super.onProgressUpdate(values);

override fun onPostExecute(result: String?)


super.onPostExecute(result)
1/...

.5 JobScheduler
Used for intelligent scheduling of background tasks. It is based
on. conditions, not atime schedule. The job
scheduler is a more intelligent alarm manager.
We can create a JobScheduler by extending a class from
JobService. Modern Android applications should use
the JobScheduler API. Apps can schedule jobs while
letting the system optimize based on memory, power, and
connectivity conditions.
classMy]obScheduler :JobService0{

override fun onStart]ob(p0: JobParameters?): Boolean{


returnfalse
}

override fun onStopJob(p0: JobParanmeters?): Boolean{


returnfalse
}

User need to override 2 methods onStartJobb)and onStoplob0.When the job starts onStartJobO is called. When
the service is running and some of the criteria are not Satisty1ng the service then the android svstem wil

automatically callonStop Job.


We have 2 main classes which is used to create jobs:
Iobinfo - The class is an abstraction that hides the task that needs to be done and the conditionsunder whiaka
tasks will get executed. As I explained earlier, this is our contract with the JobScheduler.
Joblnfo.Builder -Create your contract with the JobScheduler service using this builder.

8.6 Manage device Awake State


will first dim, then turn off the screen, and
ultimately turn off the CPU.
When we leave an Android device idle, it
quickly getting drained. Yet there are times when
This helps the device's battery from your application might
require a different behavior:
RE Tech Kaowlede
Android Application Development 8-8 Managing Background Taske
turned on.
need to keep the screen
Apps such as games or movie apps may
Other applications may not need the screen to remain on, but they may require the CPU to keep running until a

critical operation finishes.

Keep the screen on


FLAG_KEEP_SCREEN_ON in your activity (and only in an activity novse
The best way to do this is to use the
service or other app component).
classMainActivity:Activity(0{

overridefunonCreate(savedlnstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity _main)
window.addFlags(WindowManager.LayoutParams.FLAG _KEEP_SCREEN_ON)

The main advantage of the technique is it doesn't require special permission, and the platform correctly
manages the user moving between applications, without your app needing to worry about releasing unused
resources.

Another way to implement this is in your application's layout XML file, by using
the android:keepScreenOn attribute:
<Relativelayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout height="match_parent"
android:keepScreenOn="true">

</RelativeLayout>
Keep the CPU on

Inorder tokeep CPUon we use a PowerManager system service feature called wake locks. Wake locks allow
your application to control the power state of the host device.
To use awake lock, the first step is toadd the WAKE LOCKpermission to your application's manifest file :
<uses-pernmissionandroid:name="android.permission.WAKE_LOCK"/>
Review Questions

Q.1 Write a note on Broadcast Receiver


Q.2 What is a service,explain in detail
Q.3 Discuss on Threads & Process
Q. 4 What is Async Task explain
Q. 5 Write on the steps to keep the device awake
9 Deploying Android Applications
UNIT - III
on Google Play
Syllabus
Publishing/Deploy the application, Versioning,signing Application

9.1 Publishing
- Publishing is the general process that makes your Android app
available to users
Steps to publish the app
Prepare app for release
Release the app
Prepare your Confiqure, build, and test
application your application in release mode
for release
Publishing
Release your Publicize, sell, and distribute
application your application to users

Fig. 9.1.1:Publishing
Prepare
This involves the following steps :
1. Configure app for release
2. Generate signed APK
3. Run alpha and beta tests

9.1.1 Configure app for release


to optimize the app, The huild
The configuration tasks involve basic code cleanup and code modiication tasks ho
tasks serve as a final check, helping ensure that
process is similar to the debug build process. Testing
real-world conditions.
performs as expected under their Android-noYONod .
need to create arelease-ready package that users can install and run on
First we e
APK ile - compiled source code, resources. manifct
components as the debug
It contains the same own certifcate a
debug APK file, the release-reaay Arh Iie is Signed With your
However unike the
tool.
optimized with the zip align
Deploying. Android applications on
Android Application Development 9 -2
Googe Play
9.1.2 Releasingthe app
Wecan release the app in any one of the following ways
app marketplace such as Google Play.
on your ownwebsite
sending an app directly to a user.
9.1.3 Versioning
Versioning is acritical component of vour anp ungrade and maintenance strategY.

Importance of versioning
their devices and the e
User needs to know the information about the annversion that is installed on
versions available for installation.

To determine compatibility and identify dependencies


Apublishing service may also need to check the app version to determine compatibility and establish
upgrade/downgrade relationships.
The following information needs to be set in gradle
android{
namespace = "com.example.testapp"
compileSdk = 33

defaultConfig {
applicationld = "com.example.testapp"
minSdk= 24
targetSdk = 33
versionCode = 1
versionName "1.0"

Along with the above information verSIon values and minsdk and
targetsdk can also be set.
9.1.4 Signing Application
Android requires that all APKs be digitally signed with a certificate before they are installed on a device or
updated.
Android App Bundles, you need to sign your app bundle with an upload key before uploadin8 it tothe Play
Console, and Play App Signing takes care of the rest. For apps distributing using APKs on the Play Storeoron
other stores, you must manually sign your APKs for upload.
Android Application Development 9-3 Deploying Android applications on Google Play

Steps to
signin google app
Generate an upload key and keystore
1.
app with your upload key
2. Signyour
3. Configure Play App Signing
4. Upload your app to Google Play
E Prepare and roll out release of your app

Review Questions
o.1 Write a note on publishing and steps involved in publishing
a. 2 What is versioning give its importance
Q.3 Write a note on Signing an app

ODO

You might also like