This video explains Android Foreground Services, a crucial component for apps that need to perform tasks in the background while the user is aware of the ongoing operation, primarily through persistent notifications.
Mind Map
Click to expand
Click to explore the full interactive mind map • Zoom, pan, and navigate
hey guys and welcome back to a new video
and a new episode of Android basics in
this video I will talk about services
but foreground Services specifically
what that is when you should use these
and most importantly how you should use
these so till now in this Android Basics
playlist We only covered use cases where
our app is actually active where the
user seees something can click some
buttons or maybe also receive some
events from other apps so broadcast what
I what I talked about in the last video
but those were really only to to handle
onetime events very quickly but what if
your app actually needs to run in the
background for example you have a music
player app then the user would normally
expect that your app also plays music
when it's minimized or you have a
running Tracker app that tracks wherever
you you want to have a run then you also
expect that the tracking doesn't stop
when you minimize the app and that's
where so-called Services come into play
a service is an Android component just
like an activity but with a difference
that it doesn't have a user interface
but runs in the background and there an
different types of such services on the
one hand we have General Normal services
but on the other hand as this video is
called we also have the so-called
foreground Services the difference is
that with normal Services the user is
not aware that the service is running
and that your app is doing something in
the background and with foreground
Services the user knows that so for
example if your app just synchronizes
some data periodically it doesn't need
to do that in a foreground service
because the user does not need to be
aware that your app is currently syncing
something on the other hand if your app
is playing music music then the user
should be aware that your app is
actually doing something in the
background by seeing a notification
where the user can also control what the
service is currently doing so they can
pause the music they can skip to the
next song these kinds of things and the
problem now with these normal Services
where the user is not aware that these
run is that they simply can't be
guaranteed to run indefinitely cuz if
the Andro system needs memory it might
just decide to kill your service with
foreground services on the other hand
and that can't happen because they
require that as long as the service runs
the user sees a notification so for
example hey you're curbly having an
active run and this is your time because
the N system then assumes that the user
wants the service to stay active it
won't kill it even if it's low on memory
and that is why nowadays we mainly use
foreground Services when it comes to
using Services because for these
services that just sync some data in the
background that executes some longer
running tasks in the background we have
something called work manager which I
talk about in the next video so it's
just rather rare that you use these
normal General Services there are still
use cases but usually if you use a
service it's a foreground service
nowadays and to get started with that
let's just dive into coding and create a
service class in our root package new
class called yeah let's just call it
running service and we simil a little
running Tracker app here just super
simple with a static information select
class hit enter and here we want to
inherit from service so even though we
are creating a foreground service it
just needs to inherit from service and
inside of the service itself we now
specify what kind of service that is you
can see we need to implement a function
here which is called onbind which
receives an intent and returns an i
binder what is that that function is
used to create something called a bound
service so what you can also do with a
service is you can have one active
instance and multiple components connect
to that single instance and have done
yeah a stream for for communic to
communicate with that service and also
receive such events um or callbacks back
from that service if that is a use case
so if multiple apps need to connect to
one single service for example then you
need this then you also can't use
something like work manager as I will
cover in the next video but we want to
keep it simple here and we just want to
return not so we just say nothing can
actually bind to the service I will show
you different ways of communicating with
a service from an activity but let's
let's keep it simple here so right now
the service obviously doesn't do anything
anything
let's change that let's first of all
Define different commands that our
activity or other Android components can
send to the service on the one hand we
want to decide when we launch the
service or when we start it and want to
decide when we stop it for example if
the run is finished and we do this by
overwriting the onart command function
this is triggered whenever another
Android component sends an intent to
this running service so again intents
are the way how the communication works
or how intentions are specified and send
to the service and this intent can of
course contain data so depending on what
we want to do here we can just use a
different action in our intent so let's
just go down here and specify an Edom
class for the different actions we can
have for this running service and in
this simple example it's just start and
stop but you would potentially have a
lot of these actions depending on what
your service needs to do and then here
on start command before we return we
want to check when the intent
action is now actions. start. two string
then we want to call a function to start
or service which we'll create in a
moment and if it's actions. stop. two
string we want to stop our service in
this case it's very simple to stop
because we don't even need to free up
any resources or so so we don't need to
create a function for that separately we
can just call stop self which will stop
this Services instance starring on the
other hand is a bit more complex so we
need to do something there so let's go
down here and create a private function
to start our service and as I said if we
want to make this foreground service it
needs to come with a persistent
notification because otherwise the user
wouldn't be aware that there's a service
running or that the app isn't doing
something in the background so what we
need to do is we need to call start
foreground and this takes an ID and a
notification this IDE corresponds to the
specific notification so if you want to
update the notification you would just
call this function again with with the
same ID with the updated notification
but let's do it step by step we want to
choose one as the ID here don't choose
zero I've made that mistake before it
won't work it needs to be one at least
and now creating notification is
something we better do up here so we
create that Val notification is equal to notification
notification
compad Builder and with this Builder we
can now construct our very own custom
notification the user will then see when
they swipe down their status bar this
will require the context and as I showed
you in a previous video about context I
also showed you that the service is also
an Android component which inherits from
Context so for this context here we can
also simply pass this um so the service
instance since every service is also a
context it's really the same as an
activity um so we can also get the
application context this way but this
service context is now limited to the
lifetime of the service so every service
also has a normal life cycle just as an
activity it has an on create function
which you can over it has an on Destroy
function you can override just not all
the fancy functions in between from an
activity which relate to the user seeing
something on the screen because
obviously they they don't see anything
here so this Builder function is
deprecated because we also need
something else here and that is a
channel idea so um that corresponds to
something we call notification channels
on Android which we need to create if we
want to show a notification so you can
kind of think of this as a category for
a specific set of notifications so think
of the Instagram app then you might have
a set of notifications that um relate to
receiving a message from from a friend
of yours you might have a category for
yeah if someone liked your post or
interacted with your post and then in
the settings of your Android app the
user can decide whether they want to see
notifications of a specific Channel or
not and then toggle these on Ro off in
our simple example we will just have one
channel here since we only have one type
of notification so let's call this running
running
Channel and then we can now configure
our notification first of all every
single notification needs to have a
small icon which is the icon that will
show with the notification and inside of
the status bar since we don't have an
actual real icon here we can just refer
to our drawable do IC launcher
foreground this will I think just be the
Android icon which every app has by
default you can see it on the left here
the little Android head will now be the
icon for our notification of course you
can import custom icons for that we then
want to have a Content title which will
be the title of our notification so for
example um run is
active we want to have a Content info um
no content text actually which is the
description so here we could for example
show the elapsed time which yeah I will
hardcode here so obviously won't
Implement a timer that would be too much
for this video but if you would have a
timer here uh and every time it updates
to 51 seconds 52 seconds you would just
create the same notification again with
the updated content text and call the
Start program function afterwards there
we we call it build and we have our
notification which we can then pass to
start foreground right here and we don't
have any issues anymore right now again
thises won't do anything because we need
to start this service from our activity
by sending an intent to the service
class with the start action defined
since that will then call or a start
function this won't work yet because we
don't have this running channel that we
declar the IDE off here because we
actively need to create that when our
app is actually launched and we
typically do that in our application
class so in on create of our application
class so just once um when the app boots
up so let's create such a class in a
package let's call it running app for
example select class make that inherit
from application I showed you that
before in the context video and here on
create which is just called when our app
launches for the first time or at least
our instance of the app launches for the
first time if you close it and reopen it
then on create will be called again and
these notification channels were
introduced um since Android Oreo so we
need to check if our device is actually
running on Android Oreo because before
That these channels aren't needed and we
do that with build. ver. STK in to check
the SDK version and if that's greater
than or equal to build version
codes. for Oreo then we only declare
such a channel here which is a
notification Channel and this is now
pretty simple the ID needs to be the
same as we defined in our um
notification the name is simply running
notifications uh this is just what the
user will see in their app settings when
they check what kind of notifications
your app actually sends and in
importance so how high your notification
will display and how prominent it will
be to the user if it maybe comes with a
sound or vibration um let's just choose
notification manager that important high
you can see you can choose something
here Low Max default let's choose High
then we need to get a so-called system
service so just a service that comes
directly from the Android operating
system um since showing a notification
is obviously something your app isn't
allowed to do so the Android system
provides a service for that which your
app can then use and that is called the
notification manager we can retrieve
this with get system service by
specifying a name and that is just
notification um actually it's context.
notification service um that is the name
of the Serv we want and we specify the
typee that is a notification manager um
doesn't that
work okay let's do it differently by
saying as notification manager so we
just cast the results to notification
manager because the function could
potentially return different types of
service and don't confuse these Services
here with the service recreated um this
is not a thing that always runs in the
background it's just a service the
operating system provides for you to use
such functionality outside of your app
such as as showing notifications so we
then say notification manager create
notification Channel and we pass in our
Channel and if we Now launch this it
will still not work on the one hand we
need to go to our manifest because
whenever we create such an Android
component such as a broadcast receiver
on a service and activity we need to
register it here for broadcast receivers
only if it's static but for services we
always need to register these here
inside of our application tag so below our
our
activity we can then have a service and
we specify the name it already suggests
here as a running service and we can
already close this of course if your
service can only receive a certain type
of intents you can also just Define an
intent filter in it but in our case we
just want to send any type of intentor
service and something we need with
forrun Services is a permission or
actually two permissions so I haven't
made a video about permissions
specifically in this Android Basics uh
playlist because I have a quite detailed
video about permissions on Android
already which I will link somewhere up
here on the description I hope I don't
forget that but whenever your app wants
to do something that is potentially
considered sensitive or sensitive action
then you need to Define that as a
permission so for example if your app
needs access to the camera um because
Android obviously wants to limit that
your app can take unlimited photos of
wherever the user is so the user needs
to know that your app actually uses the
camera and the same for using the
microphone for accessing the file system
but also for launching a foreground
service and for showing notifications so
if we scroll up we want to go here and
specify so-called users information on
the one hand foreground service and that
just specifies that our app uses the
foreground service that is not so
dangerous or sensitive permission so the
user doesn't need to actually confirm
that they are okay with launching a
foreground service but we need to
specify it so the user can see in Google
Play what the app uses or what the app
um what kind of permissions it needs but
we also want to specify another user
permission to post notifications which
is such a sensitive permission which the
user needs to request starting from yeah
some kind of newer Android version at
least and I will really keep this super
simple here to request this because um
properly requesting permissions on
Android is quite a pain and quite a lot
of work um and because this is not the
focus of this video to properly request
permissions I will do it super simple
here and just have a simple call when we
launch our main activity I showed you
this call before I think in a video but
it's in the end activity compat that
request permissions we pass in our
activity we pass in the permission array
we want to request and this case it's
manifest permission post notifications
again we don't need to request the um
other permission for forrun services but
we also want to have a request code in
case you want to respond to that
permission request and see what the user
answered but again I want to keep this
simple and also here you can see it
complained um because this post
notification permission is only needed
for devices running on uh API level 33
and up so we can simply add a check
again build
version um import build Alt Enter SDK in
is um greater than or equal to version
codes S I think it should be so if we
move this in here then no actually what was
was
it tyu it's actually T I always confuse
these codes so let's put in terisu and
there we go and if you now think now it
will finally work nope I have to
disappoint you again one more thing we
need to do and that is we need to take
our application class and also register
that that our manifest since that's also
kind of an Android component and we need
to tell our Manifest this is our
application class so we simply go to
application specify name and it already
tells us hey you might want to use the
running app so let's choose that and now
we actually have everything we need to
properly launch and use a forr service
but still we don't have a button that
actively launches it because right now
it's just a class in our code but it's
not actively used and for that to change
that we going to go to main activity and
replace our UI code here with a column
to just display two buttons um on top of
each other so we might just Center these
for example we first of all say hey we
want to fill the whole sides of our
screen with that column we want to have
a horizontal alignment of Center
horizontally and also vertical
arrangement of Center and then in here
we can put two buttons when the first
button is clicked we now want to send an
intent from this activity to our service
to launch it so we want to say intent
the action of that intent will now be
the action that we need to attach here
to start our service so it would be running
running
service. actions.
start to string since it's an enum we
need to convert it to a
string then we say that also in this
time instead of saying start activity we
say start service there's also start
forground service but these don't really
make a difference here um you can also
use start service and just pass the
intent we created with that start action
we can then give this button a
text of start service or start run for
example if we're still in the context of
a running Tracker app we copy this
button paste it below and replace the
action with stop here this might beit
confusing here since you still use start
service to stop it but start service is
really just used to deliver the intent
we're creating here it does not have
anything to do with how the service
interprets in uses that intent so if the
service decides okay if it's actually
that action then I stop myself then
that's completely up to the service so
now let's change this text to stop run
and finally try to run this I hope it
will work if we take a look here in our
device so as soon as the app boots up
you will see this permission request
that is working fine so we obviously
want to say allow because otherwise we
can't use our F service since it needs
to come with a notification so let's
click allow now we have our two buttons
to start and stop our run if I click
Start run a little bit laggy here then
our app crashes um let's take a look and
lock at why that is maybe I missed
something oh yes I actually did miss
something of course we need to specify
where to send this intent to CU right
now we just specified an action but we
need to specify the service class so
let's just cut this action out here and
we specify the application context and
our service class so running service
Double C class of java and that we can
specify the action separately here and
set it to this can then again copy this
intent paste it here and just replace
the action with stop let's relaunch this
and hopefully it will now work the
permission is already accepted so the
request won't come again if we now click
Start run then the first time it can
sometimes take a little moment um but it
at least doesn't crash anymore and there
it is you can see we get a notification
the run is active and this is now
persistent so even if we close our app
or minimize it then I'm not sure if we
close our app oops um let's try that if
we close our app then yeah the
notification is still active so um the
app will remain active with that forun
service and if we relaunch this again to
see it um and we launch the
service with start run then this time we
get it immediately for some reason and
then click stop run we should not see
the notification anymore because our
service is cancelled or stopped you can
see it disappeared so that is working
perfectly fine now but before you go I
have two more things that you have to
know about foreground services on the
one hand if we take a look in our
manifest there are different types of
foreground Services which we can specify
here by having the foreground service
type if we Ty this then it suggests the
different options that we have here so
camera connected device location mic
phone phone call so with that if you
have one of these types of forground
service so for example if your forground
service is used to keep a phone call
Active if it's used to track the user's
location then you need to select these
types because by default Android is
quite restrictive for example if you
want to track the user's location in the
background and it only allows that with
a foreground service because then the
user knows that the app is currently
tracking the location if the service is
active but that only works if you
specified as such a service that is used
to track location or if it needs to
access the user's camera in the
background for example if you have a
video calling app or so and the users in
the background then the service might
need to access the user's camera so
depending on what your service does you
might want to take a look at these
actions and if it does something yeah
that goes in the sensitive Direction
then definitely um check these types
here and assign the right type to your
service and the other thing that many
people don't know about forrun Services
is that the service if the service is
running that also automatically means
means that your app is active so you
don't need to put all your source code
inside of the service class that your
app should do in the background because
as long as the service is active your
app's process will also be active so all
classes that are instantiated in your
app that are being used all view models
they will also be active and the code in
it will work so I would really only use
the service class here to communicate
with a service to update the
notification and to really just do what
this service needs to do but for example
for displaying the timer for tracking
the user's location in this case here I
would create separate classes that your
service might use and just call some
functions on because in my early days as
an developer I met the mistake and I put
everything the service did inside of
this class and this can sometimes grow
to th000 2,000 5,000 lines of code in
just this class and it becomes
unmaintainable so I hope you enjoyed
this and the next video we will talk
about work manager and what that is how
it compares to foreground services so
thanks for watching if you enjoyed this
definitely leave a subscribe to not miss
the next video and all future videos
there will be two new videos every
single week have an amazing rest of your
week see you back in the next video bye-bye
Click on any text or timestamp to jump to that moment in the video
Share:
Most transcripts ready in under 5 seconds
One-Click Copy125+ LanguagesSearch ContentJump to Timestamps
Paste YouTube URL
Enter any YouTube video link to get the full transcript
Transcript Extraction Form
Most transcripts ready in under 5 seconds
Get Our Chrome Extension
Get transcripts instantly without leaving YouTube. Install our Chrome extension for one-click access to any video's transcript directly on the watch page.