Android Application Development
Android Application Development
MU
Choice Based Credit System (CBCS) with effect from
Academic Year 2022-20023
Android Application
Development
(Skill Enhancement Course (SEC)) (Code : USCS405)
Tech Knouwledge
PubliCati0ns
Course Contents:
Unit No of
Topics
Lectures
(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
D00
Chapter 1: Introduction to Kotlin 1-1 to 1-79
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.
Publtcaticns
Android Application Development (MU_BSC_ Comp.) 3 Table of Contents
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.
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
.5-1
5.1 Data Persistence.
Tchknoulede
PubCations
(MU_BSC_Comp.) 4
Android Application Development
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.
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"/>
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
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.
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
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->{
Returntrue
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
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
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
LoadBroadcastMagager.sendBroadcast This method is used to send broadcasts to receivers that are in the
same app as the sender
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
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
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.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.
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.
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 {
valmyTask = MyTask)
myTask.execute(10)
}
classMyTask {
Publit2tiet
Android Application Development 8-7
.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{
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
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
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
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.
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