IntentService on Android Oreo

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys welcome to coding and flow in this tutorial we will learn how to run an intentservice in android but before you watch this video make sure to watch my foreground service tutorial first because there I explain some stuff that is necessary to understand this video and the foreign service tutorial you'll learn how a normal services work and there I also explained the nth word over your background execution limits which play a role for intent services as well you can find the foreign service tutorial when you click on the little I in the top right corner so make sure to water it first and then come back to this video okay so what is an intent service the intent service is just a subclass of the normal service RIF the difference that it executes all the incoming work on the background thread rarest enormous service once on the main thread so it's just a convenience class that makes threading in services easier it handles all the incoming work sequentially one after another and when it's finished executing all the work it automatically stops it serve and since intent services are just services the same Android Oriole background execution limits apply which means that we can't run it as a normal background service because the system were either killed or throw an exception and the recommended alternative is to use the job intent service and stealth and a job intent service works like this on API level 25 and lower it just starts a normal background in ten servers and on Android or way onwards it uses the job schedule instead I have a tutorial on job scheduler as well which you can also find in the top right corner but you don't have to watch this one and then almost all cases you should now use the job intent service and I will make a separate tutorial on the job intent service represen and when it's done you can also find it in the top right corner but in this video we will take a different approach here we will also run our intent service as a normal background service on API level 25 and lower but on aurilla onwards we will run a foreground service instead just like in the foreign service tutorial and over a job this has the benefit that it's guaranteed to start immediately and it also doesn't get interrupted whereas a job can get deferred when the devices in lower memory situations or when a device falls into doors which happens when the screen has been off for a while so only if your service really has this high priority and can't get the third you should use a foreign service otherwise please use a job in ten service instead okay so we start with a new Android surah project and the same as in the Foreign Service tutorial we have to create a notification Jennifers because an android oreo and higher we can show a notification without the notification channel so we right-click on our package and create a new java class which we call app and it extends application we click okay and I'm just going to we paste the content of this class because I explained all of this in the Foreign Service tutorial so if you want you can pause the video and type it out or I turn ative li you can find a link to the code of this example in the description box below and next let's take care of our layout so we go into our activity main.xml fire here we are removed as texture and then we changed a constraint layout into a linear layout which we give the orientation vertical a padding of 16 deep here and a gravity of center and in here we were put in edit text in the button the button will start a service and over the edit text we can send some data to the service this is pretty similar to what we did in the foreground service tutorial to rewrite opening angle bracket edit text match Penrith wrap content height we give it a hint which was a input and in ideas we can find it later on Java code and was called an ID at Plaza de / recolored edit text input and below we put a button opening angle bracket button metro pan bread for app content height but of course you can build its layout anywhere you want it will have a text that says start service and an onclick attribute which we'll call the start service method which we will create and our main activity later we press ctrl I del to rearrange everything and we don't need a stop service button here because as I already explained the service will stop itself when all its work is finished ok that's already it for the layout now we create our service so again we have red click on our package and create a new Java class let's colored example in 10 servers and it has to extend surprise in 10 service don't change anything else and click OK get the warning because we have to overwrite on end the intent so we click on this line then we click on the little red light bulb and on implement methods we keep on Enderlin and selected and click ok and here's a little bug because it tries to import the annotation from the Android X package but I'm still using the old support libraries so instead I delete this and right at nullable but in the future you will use Android X dependencies by default so they should not be necessary but we still have a warning because we also have to provide a constructor so again we click on this line on the lightbulb create constructor matching super we can delete this comment here and we have to pass a string name to the superclass constructor this is just a simple tech for debugging purposes so we can delete this as a argument and pass it directly and it will just have the same name as our class example in tens of us again this is just for debugging purposes we will also create a constant we type PR SF which is a life template for a private static final and we want to create a string constant which we caltech in capital letters and it will contain the same example intentservice as a string this is just the tag that we will use for our log messages later and if you remember from the Foreign Service tutorial that we had to implement a method called unbind even though we didn't use it and here the intents of a superclass takes care of this so we don't have to implement this method ourselves because we don't use it anyways since it's only for Bourne services which is a wholly different topic also we don't overwrite on start command here instead we overwrite on handle intent where we get past intent and this is where we do our work because this will be executed on the background thread and the same as in on start command we can use this intent to send data to the servers and use it to process our background work each incoming intent is executed sequentially one after another on one single thread if you need multiple threads at the same time in your servers then you have to extend the service class directly because the intent service can't do that however in most cases a single thread should be sufficient and intensives is very easier to use than handling this thread in yourself and we will start by showing a simple log message as soon as this method gets executed so rewrite log dear it automatically uses our tag here and this will just say on Enderlin tenth then we will get the data from our intent that we will later send over from our main activity this will be the input in our edit text to rewrite string input equals intent dot get string extra and we have to give a dig here for which reassembly write input extra and the same as in the Foreign Service tutorial we want to real work in here instead we will just freeze a threat to simulate work so recreate a for-loop birthday for a life template let's say we run it ten times we will show a lock message in each round here as well and it will display our input then - like this as a string and i--i for the number for each round and then we simply freeze the thread resistant clock don't sleep for 1000 milliseconds or one second so this on handle intent will run for 10 seconds and then it will handle the next intent or if it was the last one it will stop itself and call on destroy and this method doesn't have a return value but if you remember in enormous levels we had to return something from on start command which defined what happens when the system kills the service due to low memory here we handle this a bit differently and said we have to work Haarlem method from the constructor which is called set intent we delivery and here we have to pass a boolean true or false thought was the equivalent of start non-sticky in a normal service which means that when the system kills a service it won't be are created again true as the equivalent of start we deliver intent which means that the service will be started again and the last intent will be a deliver to one handle intent so if you want to make sure that the service get started again you have to pass set intent redelivery true ok and the same as an enormous service we can overwrite on create and on destroy in oncreate we were Sherlock message as well to see when this method is called and this time we will also create our notification here in the Foreign Service tutorial we created our notification in on start command because we changed the message of the notification from the input that we sent over but this time our notification will always show the same text so we can create it one time in oncreate and since we only want to show this for our notification on Oreo and higher we first check if built dot version dot SDK and is greater or equal to build that version codes dot or then we want to display our notification the same as in the foreign service tutorial notification notification equals new notification dot builder we pass this for the context since this is the context as well and the notification channel idea which is such an idea concerned we press I tender to importance this consent is in our app class and we don't put a semicolon here yet because now we want to continue building our notification dot said content title which resembles a example intentservice dot set content text which was the running for example it doesn't really matter we have to set a small icon for which I have prepared this adorable dot I see Android and last week I thought built to create as notification and then to start a foreign service we can start for grant has an idea which has to be higher than zero and a notification this will turn the service into a foreign service but just on aurilla onwards okay and we are almost done as you can see setting up an intentservice is not very complicated but one more thing we can do is we can activate a wakelock as soon as our service starts a wakelock will keep the CPU of the phone running when the screen is turned off which makes sense if you know that your servers could keep running when the user already locks the phone and we do this in oncreate as well let's put it here and to acquire a wakelock rewrite power manager colors power manager equals then we have to cast the top our manager and Kyle get systems lewes berry press the power 0 is constant for our wakelock we create a member variable up here private we type in wakelock which looks like this and recolored wakelock back into a war on create method here we assigned this wakelock toward power manager does new way clock then repairs power manager dot the hard way clock which is a concerned and partial way clock means that the screen can still turn off we just want to keep the CPU running comma and then we have to pass a tag which is just for debugging purposes we have to pass a string folders and when we write something like this we actually get a warning because the stack should follow a certain naming convention which would contain a colon so we can write something like this example AB : way clock now the warning disappears and didn't be simp wakelock dot acquire and this will now keep the cpu on here we get a warning because in most cases you heard you was a different acquire method where you have to pass a number and this number defines a time off for the wakelock in milliseconds so this would be ten minutes and the timeout is there to make sure that you don't accidentally keep this way clock after you are done because the way clogged drains the battery of the phone here we believe it out because we will release it later and there won't be anything that can go wrong but in real abuse it really provides that your timeout and how large this number is depends on how long your work is expected to run so if you know it won't take longer than 10 minutes past six hundred thousand milliseconds here when we acquired our way clock we will show another lock message which was a wakelock acquired okay perfect and now important after acquiring this reg lock we also has to release it we do this a non destroyer first we will show another lock message on destroyer then we want to release our wake lock wakelock dot release and another lock message which was a rare clock released and that's it for were intent service again you can find a link to the code of this example in the description box below if it is confused you take a look at it again and now we simply take care of our main activity where we will start a service so over into our mainactivity.java fire this will be very quick and simple we create a member variable for our edit text let's color the edit text input we assign it as usual and uncreate will find you by idea and then we overwrite our start service methods public we can see color from XML wild recorded the start service and we have to pass a view via because you colored from XML here we want to get the input from our edit text as a string as a text input get text to a string and then we want to start our service and sender string over so we create an intent let's call it service intent equals new intent list for the context and the name of the class we want to start which of course is our example intent service dot class then we put our input string into our service intent with dot plot extra we have to give it the same name as we did over in our service class which was input extra and the value is our input string and then we simply start our service like in the foreign service tutorial I'm gonna use context combat dot start for crowns levels which will automatically use start for current service on aurilla onwards and start service on no API levels and again if you want to know what the difference between these two is you have to watch the Foreign Service tutorial he repairs context and our service intent and that's it and now we only have to make some entries into our manifest file and then we are done so we go into our androidmanifest.xml file we have to add two promotions at the top of an angle bracket uses permission the first one is for the wakelock and the second one is a new promotion that we need in android paya and onwards for the foreground service in previous versions this was necessary but if we try to restore the foreign service on pipe with Otto's permission we will get an exception so make sure to add us then we go into our application tag and define Android color name where we pass our app to specify that we want to use our own app class as the wrapper around this application and lastly we have to register wall service itself below the activity closing tag opening angle bracket service and here we already get a suggestion example intend service slash crossing angle bracket and we are done so let's test it okay so I have started the app on API level 28 now I'm gonna start the service three times as soon as I click start service we should see a notification and I've also opened locket where we should see some output so I'm gonna start it one two three we can see oncreate we o'clock acquired on handle intent now it's running appears our position notification which we can swipe off after second on handle intent and the third one and as you can see only after the last intent on destroy or scold and the way clock was released so the three intense eyesand were executed sequentially one after another a a beer a visa and now that it's finished our notification automatically disappeared because the service automatically stopped it serve we don't have to take care of this like we had to do it in a normal service and all of this was executed on a background thread so we could still use our app where the service is doing its work in the real app this is whatever task you want to execute in the background on API levels lower than 26 we would not have a notification because there we started as a normal background service but of course you can start your service as a foreign service on these slower API levels as well for this you simply have to remove the zip track and just can't start for grant in any case and the benefits of a foreground service over a normal background service are that it's less likely to be killed in low memory situations and it's also not affected by doors the phone files into those mode when it has been laying around for a while with the screen turned off and when this happens our egg locks that we acquire are actually ignored so this doesn't work anymore in those mode however this is not the case for ads that have a foreign service running refer foreign service we keep our way clock and the CPU running so which kind of service you want to use depends on your use case but now you know how to use intent service in Android and make sure to subscribe to the channel to not miss the job intents of this video take care you
Info
Channel: Coding in Flow
Views: 46,478
Rating: 4.9407406 out of 5
Keywords: intentservice, intentservice android, intentservice in android tutorial, intentservice vs service, intentservice example, intentservice vs jobintentservice, intentservice foreground, intentservice startforeground, intentservice android o, android intentservice, android intentservice tutorial, android intentservice startforeground, android intentservice vs service, android intentservice vs jobintentservice, intent service, intent services in android, intent service vs service
Id: Oenqq3ZCo9Q
Channel Id: undefined
Length: 19min 24sec (1164 seconds)
Published: Sat Nov 17 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.