How to Track Your Users Location in the Background in Android - Android Studio Tutorial

  Переглядів 67,752

Philipp Lackner

Philipp Lackner

Рік тому

Tracking the user's location in Android is often needed when your app is minimized. Thanks to foreground services that works really well and without many restrictions. In this video I'll show you how.
⭐ Get certificates for your future job
⭐ Save countless hours of time
⭐ 100% money back guarantee for 30 days
⭐ Become a professional Android developer now:
pl-coding.com/premium-courses/
💻 Let me be your mentor and become an industry-ready Android developer in 10 weeks:
pl-coding.com/drop-table-ment...
Subscribe to my FREE newsletter for regular Android, Kotlin & Architecture advice!
pl-coding.com/newsletter
Join this channel to get access to perks:
/ @philipplackner
Get the source code for this video here:
github.com/philipplackner/Bac...
Join my Discord server:
/ discord
Regular programming advice on my Instagram page: / _philipplackner_
Checkout my GitHub: github.com/philipplackner
You like my free content? Here you can buy me a coffee:
www.buymeacoffee.com/philippl...

КОМЕНТАРІ: 167
@muhammadirfanrajput8400
@muhammadirfanrajput8400 Рік тому
Android gives continuous pain by continuous changing android SDK
@ChrisAthanas
@ChrisAthanas Рік тому
Its a constant clusterfuck for sure
@SEMPERFIDELIS7
@SEMPERFIDELIS7 10 місяців тому
It sure is one hell of a shame!
@sahilkanabar8605
@sahilkanabar8605 Рік тому
How can I be so lucky I just had a project with background tracking and here it is by best teacher like him on youtube .❤
@yeinsonjosesernahuamani9542
@yeinsonjosesernahuamani9542 Рік тому
friend how would it be sent to a node.js server?
@sahilkanabar8605
@sahilkanabar8605 Рік тому
@@yeinsonjosesernahuamani9542 sorry i could not understand you.
@yeinsonjosesernahuamani9542
@yeinsonjosesernahuamani9542 Рік тому
@@sahilkanabar8605 How do I send the location to a server in node.js?
@user-eh2el2mt2n
@user-eh2el2mt2n Рік тому
@@yeinsonjosesernahuamani9542 use retrofit?
@BapeRuLLZ
@BapeRuLLZ Рік тому
I think we may be able to improve upon the DefaultLocationClient class by putting all the locationmanager checking methods and also the context extension function into usecase classes that are wrapped by interfaces and the DefaultLocationClient class would depend upon those. That way you could unit test the class better by providing different mock implementations for the interfaces so if you would want to write a test case that checks the output if for example the gps is enabled but the location is not, then that way you could easily do that. It might be overkill but I think every unit test in itself could seem like an overkill. Just my two cents.
@halvtysk
@halvtysk Рік тому
Nice video, we have this setup in our app, albeit implemented before the introduction of flows. If you "take requests" for future videos, I would love to see your approach to handling automatic startup of these types of services when a BLE device is present. Our devices requires physical activation and for our app to be ready for this, we have to keep a sticky notification at all times which is ugly. There are workarounds to use "companion devices", but the support for proximity to BLE devices seems limited to the latter two (?) Android versions. It would be interesting to see how you would handle the "do stuff when in proximity"-approach for both newer Android devices as well as for older.
@juansuarez5216
@juansuarez5216 Рік тому
Congrats!! Really good tutorial, well explained and keeping it as simple as possible
@lifebylazy
@lifebylazy Рік тому
"To provide a streamlined experience for short-running foreground services, devices that run Android 12 or higher can delay the display of foreground service notifications by 10 seconds, with a few exceptions. This change gives short-lived tasks a chance to complete before their notifications appear." - Android Docs, if anyone was curious about that weird delay behavior
@Giulyozz
@Giulyozz Рік тому
hi philip, great video, I was wondering if you had any suggestion for using a default location listener instead of fused location, i need my app to work without play services, thanks
@mukammart379
@mukammart379 Рік тому
Hello! Can we unit test for FusedLocationProviderClient using mock? or we have to write ui test for it?
@EmanNollase
@EmanNollase Рік тому
nice tutorial. qq, what is the difference between foreground service vs WorkerManager?
@AnkitKumar-dd8fo
@AnkitKumar-dd8fo 7 місяців тому
Adding foregroundServiceType="location" in Manifest file is very crucial for foreground service to run even if app is closed in higher android version.
@aviksutar
@aviksutar Рік тому
Can you make a tutorial on complex survey form using json. Mean to say that the form is dynamically created from server end json response with multiple different layouts like rating bar, editext, radiobutton, spinners
@KhadijaHameed-bx2mt
@KhadijaHameed-bx2mt Рік тому
you r going to catch 100k soon :D i noticed it from the 2 days it add +100 on regular but today it +200 so soon 😃👏
@chabbishreels1983
@chabbishreels1983 Рік тому
What a great video, helps A LOT in the beginning.
@panagiotisangelosisiris6315
@panagiotisangelosisiris6315 7 місяців тому
Hi Phillip! Can I take the coordinates from this foreground service and print them also on screen, somehow?
@sercanyigit3292
@sercanyigit3292 Рік тому
Hi Philip what theme are you using ?
@McIntoch666
@McIntoch666 Рік тому
Location not updated
@Adam0001
@Adam0001 Рік тому
Thank you Philipp🔥 Could you make a tutorial about How to observe new data in the backgroud and then fire a notificarion. BEST WISHES
@erzhananarkulov9826
@erzhananarkulov9826 Рік тому
awesome! I would like to ask what if I want to share location with my backend and see other users location of my app. is it a good if you request to server every second to update location? How uber taxi app handle it, for example? Thanks
@maximooze3196
@maximooze3196 Рік тому
send(location), exactly how khabib said it. Thanks again @Philipp
@skarloti
@skarloti Рік тому
Beautiful and clear Thanks!
@omarhaddad980
@omarhaddad980 10 місяців тому
I found that calling `stop()` before even attempting to start will cause a problem. The reason I'm sharing this is because I'm trying to implement a `restartLocationTracking()` feature. It's essentially a location tracking refresher that involves calling `stop()` and then `start()`. This feature is particularly important when developing a Hybrid cross-platform app using Ionic and Capacitor. Is there a way to check if the (location is being tracked) before we call `stop()`?
@learner5439
@learner5439 Рік тому
Thank you Philipp for this wonderful video.
@EmanNollase
@EmanNollase Рік тому
Also can I make request a tutorial: would possible to make tutorial about swipetodismiss(compose) but the catch is will wait for the server result before it will dismiss or not?
@yaddogaming
@yaddogaming Рік тому
How we can make a code editing app or a code compiler (with jetpack compose) , pls make a video on this 🙏
@PrabhatPandey-jk6ur
@PrabhatPandey-jk6ur Рік тому
Thank you brother, you made our life easy.
@elgracko
@elgracko Рік тому
Oh, this worked perfectly, thanks!! you have no idea how much this helps!! I'm definetly buying you that coffee, right now|
@chndraja
@chndraja Рік тому
Hi Philip, I ran into a issue, where my foreground service is closed after sometime in some OEM. Any idea on how to solve this issue.
@rarespetrusamartean5433
@rarespetrusamartean5433 Рік тому
Thanks man, I got really stumped by needing to declare the service type in the manifest. Everything else was flawless and worked but as soon as I closed the app, it would stop sending locations to my server, which frustrated me to no end to the point where I resorted to youtube. Thanks again, this has been very annoying.
@berkc5323
@berkc5323 11 місяців тому
Why did you use launch { send() } instead of trySend()? Is it okay to launch a new coroutine every time that location callback triggers?
@dhiraj.20
@dhiraj.20 Рік тому
Nice tutorial, Thanks Philipp
@xITRicKsHooTzIx
@xITRicKsHooTzIx Рік тому
Hi, another wish I would like to see is background push notifications. I always had problems with that and the implementation is getting harder from experience. Thanks!
@jeromet
@jeromet Рік тому
Check out tutorial using Firebase!
@jopadjr
@jopadjr 5 місяців тому
1.3K+...Thanks Philipp. Great tutorial !! Would you mind adding Google Map series in your premium course?
@roshanpvarghese4280
@roshanpvarghese4280 Рік тому
Just wondering why you didn't go with Work manager's long running worker for this?
@yugmewada4339
@yugmewada4339 Рік тому
I am working on android kotlin food delivery project i have order tracking screen in which path will be drawn and customer can track the driver’s location application support is 6-12 than what will the best way to do above defined job? I have to send updated lat long to api to suggest me accordingly
@michaelremme8319
@michaelremme8319 Рік тому
Really really great, what you did. It was exactly what i was searching for ( for nearly a week of search ). Transfer into java was not that complicated. I have one question: why are you building the NorificationChannel inside the Application? I found some others, which are building it inside the Service directly. In that way it seems that they are recreating it with each location update. Cause of this?
@RK-lv9qc
@RK-lv9qc 7 місяців тому
I dont think it's possible , for creating UI we need to request through mainactivity and we need to build a channel before our activity gets paused or destroyed , so we need to make use of application class , one other way is to use the Mainactivity and build the channel there
@ChrisAthanas
@ChrisAthanas Рік тому
Very nice and thorough explanation!
@PhilippLackner
@PhilippLackner Рік тому
Thank you!
@jansk598
@jansk598 7 місяців тому
Hi,does the foreground service run also when device is locked and in sleep mode?
@ameentehseen6900
@ameentehseen6900 Рік тому
Finally ! thank you Philipp
@deepfuchsia7204
@deepfuchsia7204 11 місяців тому
Hey Philipp, thanks for the video and the code. I had problems with foreground service and your code worked perfectly fine. I have an additional question tho. Let's say we want to render a map and a polyline which would render something like a path using the list of locations gathered over time. The map is rendered inside a @Composable. What's the best way to pass the location data from the service into the @Composable, so it can render the path?
@hegde421201
@hegde421201 11 місяців тому
use arcgis polyline API
@berkc5323
@berkc5323 11 місяців тому
did you find a nice way? I am actually trying to find a way to use the location in a Fragment. I need to pass it to something like a StateFlow and collect it in the Fragment.
@salmaK20012
@salmaK20012 11 місяців тому
YOU ARE A LIFE SAVER!
@kiruthigat0152
@kiruthigat0152 8 місяців тому
Hi philipp,Could you please upload a video on monitor geofence
@ahmedelaswly1231
@ahmedelaswly1231 Рік тому
Thank You , it was so clear
@dalveersinghdaiya2844
@dalveersinghdaiya2844 Рік тому
Exceptional content
@mustafaammar551
@mustafaammar551 Рік тому
Very cool video Thank You Bro Wish you all the best
@siddharthp2061
@siddharthp2061 25 днів тому
Nice tutorial ! How are you handling requesting permissions from user ?
@juarez.roberto
@juarez.roberto Рік тому
This video is gold !!
@retechitsolution2564
@retechitsolution2564 7 місяців тому
Thank its good prectice for me. But one my question How to send location on pho server
@onlinemarketing9865
@onlinemarketing9865 Рік тому
Sir,, Please help me.. I have faced a problem.. My app previous update version was only 10 megabyte. But now I have added some features,, the size jumped to 25 MB, which is not possible because I have added very small amount of code... When I cancled all and go to previous version by github using version control; it also showing 25MB in released version,,, which was 10MB..
@SengKuz
@SengKuz Рік тому
Nice video, Thank you for your source code. it has useful to my develop about show location.
@lihan7257
@lihan7257 Рік тому
How to learn your coding style , so beautiful.
@abdullahtutun
@abdullahtutun 6 місяців тому
You haven't used the ACCESS_BACKGROUND_LOCATION permission in the project. Would this cause any issues when uploading the app to Google Play?
@user-ng3kf4cs4d
@user-ng3kf4cs4d 4 місяці тому
I know i m kinda late but what IDE did you use and what programming languages?
@TidelxD
@TidelxD Місяць тому
Thank You Philip you are the best
@bleuforcedz6727
@bleuforcedz6727 Рік тому
Can u do tutorial on how to make a background service cant be killed by battery optimization?
@Uz_Mobile_Developer
@Uz_Mobile_Developer Рік тому
Pls can you make vedio about canvas and using 3d objects in android
@DrakotMetal
@DrakotMetal Рік тому
why don't you use IntentService? what you include in it runs on the background by default
@rajeevthakur4916
@rajeevthakur4916 4 місяці тому
I have tried you other videos also and done each step to replicate the same but still having the issue that the notification is easily removeable by just swiping. With the foreground service i want to show a persistent/static/non-removeable notification which includes the stop button to directly stop the foreground service from the notification. By this the user will not have to open the app and the app will not be running in the background when the user dont want it to. I have tried .setOngoing etc but still not solution. Waiting for you response ..........
@florianaleman9120
@florianaleman9120 Рік тому
Hey great tutorial. I have some trouble getting the location in background idf i dont implement the code for the notifications. Is it possible ?
@sedraopamp
@sedraopamp 10 місяців тому
I've tested with different devices (Samsung S20, Motorola G42 and Pixel 6a), and LocationManager provides a location every 10 minutes in the background. I've not found an approach to reduce this time. However, you must add background location permission in the manifest and request it to the user. Coarse and Fine location will only work in foreground.
@luizfelipemontuaniesilva1371
@luizfelipemontuaniesilva1371 4 місяці тому
Is it possible to set the notification importance to LOW and set it silent without impacting the service?
@GirishKumar-vj6yy
@GirishKumar-vj6yy Рік тому
Thanks Bro😊
@flowzk921
@flowzk921 Рік тому
Great Video!
@Uz_Mobile_Developer
@Uz_Mobile_Developer Рік тому
Thanks for usefull vedio.
@faxmodem2397
@faxmodem2397 Рік тому
Hello, how can we save this information and send it to the backend? And the second question is how can we send an alarm to the backend when the user turns off the GPS
@raojilani3103
@raojilani3103 Рік тому
thank you thank you so much for this help
@fredericoamigo
@fredericoamigo Місяць тому
Good video, and I'm one of your biggest fans, but unfortunately the user location updates really really slow. Also. Is this a bit too complex? Is there an easier way to do this?
@joaopaulopop
@joaopaulopop Рік тому
Thank you very much!
@sahilkanabar8605
@sahilkanabar8605 Рік тому
can we track location after user take out our app through recent?
@_WT_WhiteKnight7YT_
@_WT_WhiteKnight7YT_ Рік тому
thank you so much dude you're a god
@Cyber-lw1bi
@Cyber-lw1bi 21 день тому
Hi cool video but how do i make it that the camera of the google map follows the user's GPS position?
@galihgaharditama7432
@galihgaharditama7432 Рік тому
Link github of the source code is wrong, can you update it? Thanks..
@user-dq7ti9zt4p
@user-dq7ti9zt4p Рік тому
miui kills the foreground service, if battery optimization is enabled and autorun is disabled, I restart the service using FCM, if the device has stopped sending data durin some time, this is not the best solution, but working one
@alirehman842
@alirehman842 Рік тому
How you check service is stopped for sending notification
@pranjalisrivastava6170
@pranjalisrivastava6170 Рік тому
How to play navigation sound when navigation started to confirm that voice directions are working in android studio?
@ManishDubeyAndroid
@ManishDubeyAndroid Рік тому
Can’t we extend LifecycleService and use lifecycleScope instead of creating own coroutineScope with supervisor?
@Salehalanazi-7
@Salehalanazi-7 Рік тому
Yup That's even better :)
@JonuGurjar
@JonuGurjar 8 місяців тому
Hi Phillip, I was seeking the same solution but it's not working when app gets killed, can you please add something
@mohaimensarker
@mohaimensarker Рік тому
Will the location will change with moving the device?
@vishwanathkumbar3083
@vishwanathkumbar3083 Рік тому
We have alternative solution for location tracking.we can use listenableworker and show notification
@krepkovmeste
@krepkovmeste Рік тому
It was very informative, but it's not entirely clear where all the code comes from ... I'm beginner in android dev, only know web development and everything is much simpler and clearer there It would be cool if a video appeared on UKposts on how to make a full-fledged gps tracker with sending the received data to the server in MySQL and authorization, or at least there were normal lessons that would teach you how to use the original source to master mobile development...
@cernaruka
@cernaruka 4 місяці тому
Great, thanks a lot
@marvelrivera1194
@marvelrivera1194 8 місяців тому
Nice one
@omarhaddad980
@omarhaddad980 11 місяців тому
at 08:40 I think there must be an OR instead of and AND in the line 24 where you check gps and network
@PhilippLackner
@PhilippLackner 11 місяців тому
No, if one of these is enabled GPS can be used
@omarhaddad980
@omarhaddad980 10 місяців тому
@@PhilippLackner Great video BTW, and now I get it, so the phone can get location using the network also besides the the Gps sensor itself, in this case I would rename the variable isNetworkEnabled to isNetworkLocationEnabled. but of course this is a personal preference. thanks a lot for the help
@danishranjan9208
@danishranjan9208 Рік тому
it work on my pc thx bro vеry much
@yugmewada4339
@yugmewada4339 Рік тому
Why you have used flow? Why you cant used mutable live data of Location?
@hossamqandel5303
@hossamqandel5303 Рік тому
Philipp ♥️
@Uz_Mobile_Developer
@Uz_Mobile_Developer Рік тому
Hi Philip
@Tech1st
@Tech1st Рік тому
can't we running after close the app?
@yeinsonjosesernahuamani9542
@yeinsonjosesernahuamani9542 Рік тому
How do I send the location to a node.js server?
@zlash7
@zlash7 Рік тому
The link below "Get the source code for this video here" is wrong
@additionalaccount4974
@additionalaccount4974 8 місяців тому
everything is fine but the location is hella inaccurate. i need very precise location please help
@roshkaalex
@roshkaalex Рік тому
Hi Philipp. What about ACCESS_BACKGROUND_LOCATION permission? Should we use this permission for tracking in background?
@NathanMeadeWSG
@NathanMeadeWSG Рік тому
I had to. Also for Android 13 devices you will need to prompt the user to "Allow all the time" for the location permissions of the app.
@sedraopamp
@sedraopamp 10 місяців тому
Fine and coarse locations will only work in foreground since Android 11. Access_Background_Location is a must BUT these android versions reduce location updates to report them every 10 minutes in my tests with different manufacturers in the background.
@roshkaalex
@roshkaalex 10 місяців тому
@@sedraopamp we had the same results... i thought that this permission will resolve background tracking issues... but still we have empty zone on the map
@sedraopamp
@sedraopamp 10 місяців тому
@@roshkaalex You need also to disable battery optimization e.g. Samsung S20 stops the location manager if that feature is enabled, no matter if background location permission is allowed.
@Cyber-lw1bi
@Cyber-lw1bi 22 дні тому
Hello... Am I the only one with the problem that the gps location does not change? So if i try to set a virtual gps location in extended controls, the app will continue to print out the original location until the whole emulated smartphone has been restarted. And then again, only the one location that has been set before the device restart is continuously printed out...
@trevortrevose9124
@trevortrevose9124 Рік тому
Heard facebook tracks user search history and keystrokes is this possible or a myth
@RadhaVaddireddy
@RadhaVaddireddy Рік тому
showing 'create(): LocationRequest' is deprecated. Deprecated in Java' message, please suggest how to resolve this issue.
@MrYehiawy
@MrYehiawy Рік тому
Build
@hydernotes
@hydernotes 2 місяці тому
Will it keep running it I terminate the app?
@hasnainahmad8295
@hasnainahmad8295 2 місяці тому
val request = LocationRequest.create() .setInterval(interval) .setFastestInterval(interval) stopForeground(true) --- deprecated Sir, create(), setInterval(), and setFastestInterval() methods are deprecated now. Plz guide for alternatives.
@jackc-gw7630
@jackc-gw7630 2 місяці тому
have you found a way to update location continuesly?
@rithulraj3348
@rithulraj3348 Рік тому
Is it possible to track location when the app is killed?
@pranav7478
@pranav7478 Рік тому
Philip how long we can run ? please reply
@PhilippLackner
@PhilippLackner Рік тому
Until you're out of breath
@purplehazer417
@purplehazer417 Рік тому
@@PhilippLackner hahahahaha xd
@jackc-gw7630
@jackc-gw7630 2 місяці тому
Hey. The location doesnt seem to update continesly anymore?
@EntertheBlackDragon
@EntertheBlackDragon Рік тому
Column will not render, not sure what that's about.
@mondoshigua
@mondoshigua Рік тому
🇨🇴🧔🏻👍🏼🤝🏼 Saludos desde Colombia.
@avinashgupta4038
@avinashgupta4038 5 місяців тому
the code not working, can you please make another video on this topic
Foreground Services - Android Basics 2023
22:22
Philipp Lackner
Переглядів 59 тис.
GADGETS VS HACKS || Random Useful Tools For your child #hacks #gadgets
00:35
I'm Coding for 13 Years to Find Out About THIS
2:04
Philipp Lackner
Переглядів 10 тис.
Deep Linking in Jetpack Compose
4:15
Daniel Atitienei
Переглядів 3,6 тис.
Making Our Service a Foreground Service - MVVM Running Tracker App - Part 12
20:21
The ONLY Thing to MASTER as an Android Developer (And Why 99% FAIL!)
1:46
Philipp Lackner
Переглядів 18 тис.
Most overpowered way to build mobile apps?
8:33
Beyond Fireship
Переглядів 675 тис.
Get current location in Android Studio | Kotlin
7:30
Coding Adventure
Переглядів 19 тис.