How to Observe Internet Connectivity in Android - Android Studio Tutorial

  Рет қаралды 46,691

Philipp Lackner

Philipp Lackner

2 жыл бұрын

In this video you'll learn how you can monitor whether the user is connected to the internet or not. Works for both Compose and XML projects :)
⭐ 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...
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/Obs...
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...

Пікірлер: 127
@sijanneupane
@sijanneupane 21 күн бұрын
Philipp, I'm sorry for hovering over the internet for a while and not coming directly to your playlist to search for this topic. You're always a lifesaver.
@aoh1996
@aoh1996 2 жыл бұрын
I was googling this question a few days ago and now you've made a tutorial. Just in time, thanks!
@chinenye_ikpa
@chinenye_ikpa 2 жыл бұрын
This is timely. Thanks a lot for the thorough breakdown on how and why.
@leonelp9593
@leonelp9593 Ай бұрын
this is why i love this channel so much, when you are wondering about a specific thing for ur app, you just come here and know that philipp will explain the best aproach for that thing lol 😎
@pr0adam
@pr0adam 2 жыл бұрын
great video. did this recently myself the same way. callback flows are great also trivialized a lot of the Network Service Discovery code
@alco8864
@alco8864 2 жыл бұрын
It's a useful demo for handling the context depend resource by callbackflow ❤️
@jarkow
@jarkow 2 жыл бұрын
Your timing couldn't be better. 2 hours ago client approached me for a feature which requires to watch the internet connection state. Thank you so much!
@miladhashemzadeh5626
@miladhashemzadeh5626 2 жыл бұрын
He has the Great timing belive me
@top10channels31
@top10channels31 2 жыл бұрын
You can use live data i am always use in my project
@miladhashemzadeh5626
@miladhashemzadeh5626 2 жыл бұрын
@@top10channels31 it's deprecated lets don't talk about it
@tyler07830
@tyler07830 Жыл бұрын
@@miladhashemzadeh5626 live data is not depricated
@emmanuelmtera5936
@emmanuelmtera5936 2 жыл бұрын
Phillip i was finding a solution like this, thanks brother.
@mrsoommy9162
@mrsoommy9162 2 жыл бұрын
Great tutorial! I would love to have a video which will expand this knowledge to Ethernet connection observer via broadcast receiver for Android boxes!
@aymericloos3070
@aymericloos3070 Жыл бұрын
Thank you for your superb explanation ! You're certainly the best KZfaq's Android guy !
@PhilippLackner
@PhilippLackner Жыл бұрын
Thanks!!
@soumyaranjan6485
@soumyaranjan6485 2 жыл бұрын
Awesome tutorial Phill
@MaxWeninger
@MaxWeninger 2 жыл бұрын
Very nice. Exactly what I needed right now 😂
@232techtalk
@232techtalk Жыл бұрын
Hi Philip thanks for this video. I am trying to implement this in my application that uses hilt for DI. I have a custom Interceptor that adds some auth header before the request is being processed, but my application crashes as soon as it opens. How can I catch the error and send it to the user? Thank you
@RiccardoGabellone
@RiccardoGabellone 2 жыл бұрын
Great job Philipp!! 💪🏻
@PhilippLackner
@PhilippLackner 2 жыл бұрын
Thanks!!
@letscode29
@letscode29 Жыл бұрын
Good Explanation . Thank you
@tejastidake6897
@tejastidake6897 Жыл бұрын
Thank You for making video in Kotlin 🙏
@ankitverma3932
@ankitverma3932 2 жыл бұрын
Much needed 💙
@keepgoingman5829
@keepgoingman5829 2 жыл бұрын
It's very useful! thank you!
@anudeepananth
@anudeepananth Жыл бұрын
Nice video.... Thank u so much for this....
@antonioguerra8703
@antonioguerra8703 2 жыл бұрын
Hey bro I have a question, Have you thought about doing an updated augmented reality course, perhaps with the scene view library on udemy or I don't know if on any platform? Because the scene form is no longer maintained and it is a world with a lot of potential but little explored. Thank you.
@talhac2796
@talhac2796 Жыл бұрын
Should i use sync adapter to synchronize my local db with server?
@davidscammell9823
@davidscammell9823 Жыл бұрын
Thank you for your great content, however I seem to get an issue with this - my App doesn't fire when you first hook up the flow and you have no internet - I was expecting it to show 'Unavailable' as it does with 'Available'...
@de.mirgorod
@de.mirgorod Жыл бұрын
Same problem. DId you solve it somehow?
@mohinithakkar2172
@mohinithakkar2172 Жыл бұрын
@@de.mirgorod Same issue. Did you get an answer how to solve it?
@kussenkovegor
@kussenkovegor Жыл бұрын
you can create a variable and initialize it with a valueConnectivityObserver.Status.Unavailable
@mdalikazi
@mdalikazi Жыл бұрын
Same issue. Commenting here to receive any updates on this.
@mdalikazi
@mdalikazi Жыл бұрын
@davidscammell9823​ @denismirgorod7931 @mohinithakkar2172 The solution is to make the flow a hot flow and to start with an initial value. Do this at the end of the callbackFlow }.distinctUntilChanged().stateIn(scope, SharingStarted.WhileSubscribed(), initialValue) private val initialValue = if (connectivityManager.activeNetwork != null) { ConnectivityObserver.NetworkStatus.Available } else { ConnectivityObserver.NetworkStatus.Lost } scope is my lifecycle scope and is sent as property to observe(scope: CoroutineScope)
@theai2020
@theai2020 Жыл бұрын
how to observe it without compose collectasstate is not the option available in normal xml
@apzar3436
@apzar3436 2 жыл бұрын
What's your thought on creating a state based application like implementing FSM(Finite State Machine) in its brother ?
@VishnuHaridas
@VishnuHaridas Жыл бұрын
The observe() function registers a new network callback every time we try to observe it and returns a cold flow. We can prevent this by converting the cold flow into a hot flow using the `shareIn` or `stateIn` operators. We can add a property to the `class NetworkConnectivityObserver` like this: ``` val status: Flow = observe().stateIn(scope, WhileSubscribed(), Status.Unavailable) // Injected scope ``` Or creating a `class NetworkStatusRepository(CoroutineScope, ConnectivityObserver)` which creates a property like above will be better.
@mdalikazi
@mdalikazi Жыл бұрын
Man you're a life saver. I was not receiving updates when I open the app with network already lost. By making the flow hot I am now receiving updates perfectly.
@user-ws1cr9sc7k
@user-ws1cr9sc7k Жыл бұрын
Was thinking the same, good one
@Synthwave89
@Synthwave89 10 ай бұрын
You absolute KING/QUEEN. I implemented on my own and using this video, and in both cases starting with no connectivity would not trigger the stupid network callback. Making it into a hot flow worked like a charm! Thank you! ♥
@ArturoDevA
@ArturoDevA 6 ай бұрын
​@@Synthwave89 i used sharedFlow but no work, give me an example please
@asadansar6214
@asadansar6214 Жыл бұрын
Hey Phillip its a great video. but how to use the check internet flag in our viewModel. do we need to check internet on every api call or any better global way to check?
@mustafaammar551
@mustafaammar551 2 жыл бұрын
VERY COOL YOU ARE THE BEST
@vengateshm2122
@vengateshm2122 2 жыл бұрын
Please make a video on building custom Kotlin DSL for android usecase.
@umairkhalid123
@umairkhalid123 2 жыл бұрын
That's Philip Lackner's way of programming ⭐ it will be great if we can add backward compatibility to it and make it even better solution
@ankitverma3932
@ankitverma3932 2 жыл бұрын
We can use the same code with connectivityManager.requestNetwork(networkRequest, networkCallback) for api levels lower than 24 .
@breensrobert
@breensrobert 2 жыл бұрын
This is great
@abdallawanjusi
@abdallawanjusi 2 жыл бұрын
Hi, this crushes app if you turn off and on and turn it back while observing some state.
@srikrishnanunna1
@srikrishnanunna1 10 ай бұрын
So when we have some device connected to our mobile say an insta 360 camera, and we want to connect to mobile for internet. How do we realise this ? I thought of using network capability and check for connection status.
@dota2heralds
@dota2heralds Жыл бұрын
Hey I'm Unable to get the unavailable status im not using compose just observing in activity what am I doing wrong?
@TheRcfrias
@TheRcfrias Жыл бұрын
Did you ever handle that last scenario?, A very frequent scenario is when you connect to a public wifi and the network is saturated or internet is down. You will still be connected to the internet, but you wont have any internet access whatsoever.
@SanjayVerma-mf4ch
@SanjayVerma-mf4ch 2 жыл бұрын
Was searching this yesterday and today got it👍👍
@mohammeddhiyaeddinegouaour1636
@mohammeddhiyaeddinegouaour1636 2 жыл бұрын
Thank you sir for the great content, I just want to know where does the observer fit in the clean architecture design
@mohamadalighezelbashyan4482
@mohamadalighezelbashyan4482 2 жыл бұрын
It is my question, too
@aguiarroney
@aguiarroney 4 ай бұрын
Passing context as parameter won't cause a memory leak?
@vtklsnkt
@vtklsnkt 2 жыл бұрын
Hi Philipp, thanks for the awesome video, one question, if we were to implement this in ViewModel, we would need to extend AndroidViewModel for getting the application context, is there a way we can do this with extending the simple ViewModel class?
@PhilippLackner
@PhilippLackner 2 жыл бұрын
Nah, you just need to inject an instance of it, not create it in the VM
@vtklsnkt
@vtklsnkt 2 жыл бұрын
@@PhilippLackner Ah! Correct thanks 👍 much appreciated
@dikenmhrz3902
@dikenmhrz3902 2 жыл бұрын
If I have to ping google to check whether connection really exists or not, how should I do it?
@alirezab4253
@alirezab4253 2 ай бұрын
hi phillipp thanx for this tutorial ❤, but , in android 11 and above , how we can do something on_net_state_change , when app is not open ? please answer this 😭
@baijusharma6027
@baijusharma6027 2 жыл бұрын
Hi, I have a doubt. For eg: fun getUsers(): Flow and suspend fun getUsers(): List. Here both the function will fetch the list of data from the API. What are the benefits of converting API data or List into FLOW? Also, my app does not retrieve streams of data like the stock market or video streaming app. Do I really need to use Flow?
@Synthwave89
@Synthwave89 10 ай бұрын
If you want to monitor a data source for changes. Your function without Flow will return a single, one shot result, the Flow can stream an infinite amount of results as the DB changes. I have only used it for a local DB, not sure how or if it would work for remote resource. Initially I received a Flow that would send data to collectors when the room database was updated, but then I converted the Flow to a StateFlow in the ViewModel and since the latter stores a state, it made for a much smoother user experience. Oh, also to answer your question, both functions do NOT fetch the list of data from the API. The Flow method will just return a Flow that you can use to create a collector and that will only stream data when the source (ie. the database) is modified. It is cold, it won't actually fetch data by itself.
@David-zb8br
@David-zb8br Жыл бұрын
What if user has +4G on but got no data plan? What can i do in that case?
@lukealvinmadzedze2050
@lukealvinmadzedze2050 2 жыл бұрын
Hey bro, Thank you so much for the great content 🙏 One question, can we not use trySend() instead of launch { send( ) } or is it ultimately the same thing Thanks
@tibrec8
@tibrec8 Жыл бұрын
we should use trySend() because if we use lunch {send()} if theres no collectors an error will be thrown
@hxrin3748
@hxrin3748 2 жыл бұрын
Hey, great video, I've tried to implement it but it seems like onUnavailable is not getting triggered? I've tried and turned off wifi and data in emulator, started the app and no log message showed up. Then when I turned on Wifi, Available status got sent to the channel and then when I turned it off, Lost status got sent. But never the Unavailable.
@de.mirgorod
@de.mirgorod Жыл бұрын
Same problem. DId you solve it somehow?
@dota2heralds
@dota2heralds Жыл бұрын
did you got the solution?
@abhishekupadhyay7339
@abhishekupadhyay7339 Жыл бұрын
@@dota2heralds got any solution?
@Synthwave89
@Synthwave89 10 ай бұрын
@@de.mirgorod @dota2heralds @abhishekupadhyay7339 Convert the cold Flow to a hot StateFlow. worked perfectly for me.
@uop6238
@uop6238 2 жыл бұрын
I try these code but these callback is not work(apart from onAvailable)..
@usermai174
@usermai174 2 жыл бұрын
Nice Explanation! however I'd like to highlight that The android ConnectivityManager API only notifies the clients about the Network Status (available, Lost, etc...) wether your device is connected to a network or not and does not reflect the actual Internet connectivity. The only way to check if the device has access to Internet is through a HTTP request that returns a valid HTTP status code.
@PhilippLackner
@PhilippLackner 2 жыл бұрын
Yeah, I mentioned this in the video, although you don't need an http request to do that, a simple ping is enough 😄
@dikenmhrz3902
@dikenmhrz3902 Жыл бұрын
@@PhilippLackner could you please explain this a bit more?
@lucasianii8178
@lucasianii8178 5 ай бұрын
Hi guys, does any body know how I can get IP ADDRESS of devices connected to my mobile phone hotspot in kotlin?
@davidsantiagorodriguezcruz7023
@davidsantiagorodriguezcruz7023 2 жыл бұрын
Thanks so much, it's really amazing. But I feel a little lost when something changes and i need to observe it, can you recommend me some video or documentation for work on that?
@m77mo65
@m77mo65 2 жыл бұрын
Start with liveData
@davidsantiagorodriguezcruz7023
@davidsantiagorodriguezcruz7023 2 жыл бұрын
@@m77mo65 thanks
@apunichjohncena4533
@apunichjohncena4533 Жыл бұрын
How to pass initial state in non-compose application?
@sajidgarcia3135
@sajidgarcia3135 Жыл бұрын
Very useful, but what happen with mobile network but not internet data, still get Available
@supportreplyemail2706
@supportreplyemail2706 2 жыл бұрын
please tell me how to create game animation please tell me about graphics canvas unity, agdk
@Banana-sq1hl
@Banana-sq1hl 2 жыл бұрын
can u make video about bazel build tools
@rajneeshroy4538
@rajneeshroy4538 Жыл бұрын
Network status is updated,but what happens when we have wifi connection but not internet.
@ayushs_2k4
@ayushs_2k4 Жыл бұрын
How to use it in viewModel where we can't have applicationContext
@pa1shetty
@pa1shetty 2 жыл бұрын
So it doesn't says whether device is connected to the internet or not. ( Having connected to wifi / keeping mobile data on doesn't mean device actually has internet connection) any way to resolve this?
@PhilippLackner
@PhilippLackner 2 жыл бұрын
As I said in the video, the only real way to check this is to send a ping to google.com or so and check if a response comes back after 5-10s
@billythekid1848
@billythekid1848 2 жыл бұрын
Hi Philipp thank you so mush great work ! Please if you Can one day make a video about how to use okhttp authenticator, i never find video or tutorial that talking about it on thé nice way, which you the best ❤️💪
@erfansn869
@erfansn869 2 жыл бұрын
Wouldn't it be better to use StateFlow, less and cleaner code?
@GN9K71
@GN9K71 2 жыл бұрын
StateFlow is a hot flow, so collecting from it may not (and must not trigger the producer). In this case I think in this case it`s cleaner to emit events from raw Flow since it`s more abstract and more reusable if you don`t want to collect the emitted events from many subscribers for example.
@raydevivo2168
@raydevivo2168 Жыл бұрын
I believe there is a bug here - if you open the app while network is already available, wouldn't the app still show Unavailable since the initial state you set was UNAVAILABLE and the callback would not actually be triggered for AVAILABLE since it is already available? I think there needs to be a check for initial state
@PhilippLackner
@PhilippLackner Жыл бұрын
I think the switch should be pretty much instant. But if it's still an issue you can set the initial value to null and wait for the first real emission
@Synthwave89
@Synthwave89 10 ай бұрын
In my tests, there is no issue when opening the app while network is already available. Like Philipp said, it will first return Unavailable and immediately switch to Available. The issue I found was when network is NOT available on app start or resume. The NetworkCallback would refuse to trigger in such a case UNTIL you get network Available. Making the Flow hot (by converting to StateFlow) fixed it.
@mohinithakkar2172
@mohinithakkar2172 Жыл бұрын
I've implemented this, but when my internet is off and i'm opening the application, it doesn't trigger disconnected state!! Can you please give brief! Thanks
@nurmatjunushev2529
@nurmatjunushev2529 Жыл бұрын
Yeah, that's an issue. This is because Network Callback isn't triggering. A workaround is to check for active network after connectivityManager.registerDefaultNetworkCallback(callback) if (connectivityManager.activeNetwork == null) { trySend(ConnectivityObserver.Status.Unavailable) } Also you need to add new status like ConnectivityObserver.Status.NotObserved or make nullable to split various states
@_joelkanyi
@_joelkanyi Жыл бұрын
@@nurmatjunushev2529 Thanks for this ❤
@Sarria000
@Sarria000 2 жыл бұрын
CallbackFlow can directly use “offer” to provide data, you don’t need to use “send” because you didn’t change the coroutine context.
@PhilippLackner
@PhilippLackner 2 жыл бұрын
Ah lol, I was looking for that. Thought it was either send or emit. Thanks 😁
@marshallladd
@marshallladd 2 жыл бұрын
@Patrick of course it was
@aliciabeltran
@aliciabeltran 2 жыл бұрын
What about be connected but no navigation
@raulmaza5138
@raulmaza5138 2 жыл бұрын
Good point, this approach does not solve that situation and Android is not offering an API for that. Normally developers open a socket pinging Google IP in a loop
@jewelsbypodcasterganesh
@jewelsbypodcasterganesh 6 ай бұрын
This doesn't work if the client is using a VPN
@ChrisAthanas
@ChrisAthanas 2 жыл бұрын
@8:10 you mention needing to use ViewModelFactory to inject the context using Hilt for the ConnectivityObserver, but is the ViewModelFactory actually needed in that case? Would it not just be injected in the Hilt Module and then injected into the Activity or Fragment (because it contains a reference to the Context) and then send messages to the ViewModel via an exposed channel or flow? What I'm asking is that the ConnectivityObserver would be injected into the Activity/Fragment and not the ViewModel because of the applicationContext dependency in ConnectivityObserver. Wouldn't injecting the ConnectivtyObserver into the ViewModel cause memory leaks due to the dependency on applicationContext? Or is the applicationContext always valid and does not change on config changes? Would it make more sense to inject the ConnectivityObserver into the fragment/activity and then send messages to the ViewModel on the changes of network state?
@PhilippLackner
@PhilippLackner 2 жыл бұрын
ViewModels are totally fine using dependencies that use the app context. No leaks can happen with the application context as it's a singleton. The reason we don't directly use it in the viewmodel is that it makes it non unit testable (at least not with local unit tests)
@ChrisAthanas
@ChrisAthanas 2 жыл бұрын
@@PhilippLackner ok that makes sense. I was confused about context and application context
@ashishtiwadi
@ashishtiwadi 2 жыл бұрын
What if you are connected to a network and internet is not working.😉
@raulmaza5138
@raulmaza5138 2 жыл бұрын
Yes, this approach does not solve that situation and Android is not offering an API for that. Normally developers open a socket pinging Google IP in a loop
@ankushverma9392
@ankushverma9392 2 жыл бұрын
*Mrs Charlotte is legit and her method works like magic I keep on earning every single week with her new strategies *
@bozemanhenrik4431
@bozemanhenrik4431 2 жыл бұрын
She helped me recover what I lost trying to trade my self
@laurajosie9926
@laurajosie9926 2 жыл бұрын
She has made success easier than we thought
@laurajosie9926
@laurajosie9926 2 жыл бұрын
I've never heard or seen any of her clients complain of Lost....I think she's just too perfect
@Bruce__Springsteen0
@Bruce__Springsteen0 2 жыл бұрын
She's not like other brokers that will star telling you stories and excuses why they trade didn't go well after collecting your money
@Bruce__Springsteen0
@Bruce__Springsteen0 2 жыл бұрын
Investment is the future
@baapkobhaj8133
@baapkobhaj8133 Жыл бұрын
Hi bro you know me who I'm
@dmytroberezhnyi717
@dmytroberezhnyi717 2 жыл бұрын
Connectivity means nothing, if it is connected not the fact user have internet
@remmievail2003
@remmievail2003 2 жыл бұрын
This is true. Being connecting to a wifi network doesn't mean you have internet connection.
@PhilippLackner
@PhilippLackner 2 жыл бұрын
As I said in the video :) you'd need to ping a server and wait for a response to check that
@nefafilmstudio5575
@nefafilmstudio5575 6 ай бұрын
Very long for short thinkg 😢
@momentslikethis8014
@momentslikethis8014 Жыл бұрын
this shit. this code work only when we off wifi and mobile data. when we have bad internet connection this code return avaliable
@hristoivanov4374
@hristoivanov4374 2 жыл бұрын
Android боклук 😂 Iso iphone 🤘
@drackon1995
@drackon1995 2 жыл бұрын
How can I convert this code to a service, to monitoring all mi app no only one activity? 🤔
@izaacdoyle
@izaacdoyle 2 жыл бұрын
I am having an Issue to when I add the Permissions for the Network_State. it Informs me even after adding to manifest permission is still missing
@ankitverma3932
@ankitverma3932 2 жыл бұрын
Facing the same problem
Full Guide to Delegation in Kotlin  - Android Studio Tutorial
18:10
Philipp Lackner
Рет қаралды 67 М.
Monitoring a Network Connection in Realtime with LiveData
15:08
CodingWithMitch
Рет қаралды 28 М.
Inside Out 2: Who is the strongest? Joy vs Envy vs Anger #shorts #animation
00:22
I'm Excited To see If Kelly Can Meet This Challenge!
00:16
Mini Katana
Рет қаралды 29 МЛН
Викторина от МАМЫ 🆘 | WICSUR #shorts
00:58
Бискас
Рет қаралды 5 МЛН
This Is My FAVORITE Error Handling Class
28:57
Philipp Lackner
Рет қаралды 28 М.
WorkManager - Android Basics 2023
34:22
Philipp Lackner
Рет қаралды 53 М.
Should You Use Compose State or StateFlow in Your ViewModels?
13:59
Philipp Lackner
Рет қаралды 74 М.
Testing if a Network Connection actually has Internet on Android
7:02
CodingWithMitch
Рет қаралды 11 М.
Are You Connected? Check Your App Connectivity with Xamarin.Essentials
13:01
Most overpowered way to build mobile apps?
8:33
Beyond Fireship
Рет қаралды 754 М.
5 Fatal Coroutine Mistakes Nobody Tells You About
18:15
Philipp Lackner
Рет қаралды 86 М.
Inside Out 2: Who is the strongest? Joy vs Envy vs Anger #shorts #animation
00:22