How to Observe Internet Connectivity in Android - Android Studio Tutorial

Поделиться
HTML-код
  • Опубликовано: 22 окт 2024
  • 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/...
    Subscribe to my FREE newsletter for regular Android, Kotlin & Architecture advice!
    pl-coding.com/...
    Join this channel to get access to perks:
    / @philipplackner
    Get the source code for this video here:
    github.com/phi...
    Join my Discord server:
    / discord
    Regular programming advice on my Instagram page: / _philipplackner_
    Checkout my GitHub: github.com/phi...
    You like my free content? Here you can buy me a coffee:
    www.buymeacoff...

Комментарии • 127

  • @aoh1996
    @aoh1996 2 года назад +27

    I was googling this question a few days ago and now you've made a tutorial. Just in time, thanks!

  • @jarkow
    @jarkow 2 года назад +8

    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 года назад +1

      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 2 года назад +1

      @@miladhashemzadeh5626 live data is not depricated

  • @sijanneupane
    @sijanneupane 3 месяца назад

    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.

  • @leonelp9593
    @leonelp9593 4 месяца назад

    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 😎

  • @alco8864
    @alco8864 2 года назад +3

    It's a useful demo for handling the context depend resource by callbackflow ❤️

  • @chinenye_ikpa
    @chinenye_ikpa 2 года назад

    This is timely. Thanks a lot for the thorough breakdown on how and why.

  • @VishnuHaridas
    @VishnuHaridas 2 года назад +5

    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 Год назад +1

      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.

    • @RatkaOdalovic-Radusinovic
      @RatkaOdalovic-Radusinovic Год назад

      Was thinking the same, good one

    • @Synthwave89
      @Synthwave89 Год назад

      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 9 месяцев назад +1

      ​@@Synthwave89 i used sharedFlow but no work, give me an example please

  • @aymericloos3070
    @aymericloos3070 Год назад

    Thank you for your superb explanation ! You're certainly the best RUclips's Android guy !

  • @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!

  • @emmanuelmtera5936
    @emmanuelmtera5936 2 года назад +1

    Phillip i was finding a solution like this, thanks brother.

  • @davidscammell9823
    @davidscammell9823 2 года назад +5

    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 2 года назад +1

      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)

  • @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

  • @vengateshm2122
    @vengateshm2122 2 года назад +3

    Please make a video on building custom Kotlin DSL for android usecase.

  • @232techtalk
    @232techtalk 2 года назад +2

    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

  • @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 года назад +1

      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 2 года назад

      @@PhilippLackner could you please explain this a bit more?

  • @umairkhalid123
    @umairkhalid123 2 года назад +1

    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 года назад +2

      We can use the same code with connectivityManager.requestNetwork(networkRequest, networkCallback) for api levels lower than 24 .

  • @tejastidake6897
    @tejastidake6897 Год назад +1

    Thank You for making video in Kotlin 🙏

  • @talhac2796
    @talhac2796 Год назад +1

    Should i use sync adapter to synchronize my local db with server?

  • @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

  • @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?

  • @hxrin3748
    @hxrin3748 2 года назад +3

    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 2 года назад

      Same problem. DId you solve it somehow?

    • @dota2heralds
      @dota2heralds Год назад

      did you got the solution?

    • @abhishekupadhyay7339
      @abhishekupadhyay7339 Год назад

      @@dota2heralds got any solution?

    • @Synthwave89
      @Synthwave89 Год назад

      @@de.mirgorod @dota2heralds @abhishekupadhyay7339 Convert the cold Flow to a hot StateFlow. worked perfectly for me.

  • @MaxWeninger
    @MaxWeninger 2 года назад +1

    Very nice. Exactly what I needed right now 😂

  • @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.

  • @soumyaranjan6485
    @soumyaranjan6485 2 года назад

    Awesome tutorial Phill

  • @lukealvinmadzedze2050
    @lukealvinmadzedze2050 2 года назад +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 2 года назад

      we should use trySend() because if we use lunch {send()} if theres no collectors an error will be thrown

  • @letscode29
    @letscode29 Год назад

    Good Explanation . Thank you

  • @apzar3436
    @apzar3436 2 года назад

    What's your thought on creating a state based application like implementing FSM(Finite State Machine) in its brother ?

  • @RiccardoGabellone
    @RiccardoGabellone 2 года назад

    Great job Philipp!! 💪🏻

  • @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.

  • @Sarria000
    @Sarria000 2 года назад +1

    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 года назад +2

      Ah lol, I was looking for that. Thought it was either send or emit. Thanks 😁

    • @marshallladd
      @marshallladd 2 года назад +2

      @Patrick of course it was

  • @alirezab4253
    @alirezab4253 4 месяца назад

    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 😭

  • @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?

  • @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 Год назад

      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.

  • @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 года назад +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

  • @ChrisAthanas
    @ChrisAthanas 2 года назад +1

    @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 года назад +1

      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

  • @keepgoingman5829
    @keepgoingman5829 2 года назад

    It's very useful! thank you!

  • @anudeepananth
    @anudeepananth Год назад

    Nice video.... Thank u so much for this....

  • @srikrishnanunna1
    @srikrishnanunna1 Год назад

    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.

  • @aguiarroney
    @aguiarroney 7 месяцев назад

    Passing context as parameter won't cause a memory leak?

  • @theai2020
    @theai2020 2 года назад +2

    how to observe it without compose collectasstate is not the option available in normal xml

  • @ankitverma3932
    @ankitverma3932 2 года назад

    Much needed 💙

  • @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 Год назад +1

      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.

  • @dota2heralds
    @dota2heralds Год назад

    Hey I'm Unable to get the unavailable status im not using compose just observing in activity what am I doing wrong?

  • @abdallawanjusi
    @abdallawanjusi 2 года назад

    Hi, this crushes app if you turn off and on and turn it back while observing some state.

  • @sajidgarcia3135
    @sajidgarcia3135 Год назад

    Very useful, but what happen with mobile network but not internet data, still get Available

  • @mustafaammar551
    @mustafaammar551 2 года назад

    VERY COOL
    YOU ARE THE BEST

  • @Banana-sq1hl
    @Banana-sq1hl 2 года назад

    can u make video about bazel build tools

  • @dikenmhrz3902
    @dikenmhrz3902 2 года назад

    If I have to ping google to check whether connection really exists or not, how should I do it?

  • @billythekid1848
    @billythekid1848 2 года назад +1

    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 ❤️💪

  • @uop6238
    @uop6238 2 года назад

    I try these code but these callback is not work(apart from onAvailable)..

  • @rajneeshroy4538
    @rajneeshroy4538 Год назад

    Network status is updated,but what happens when we have wifi connection but not internet.

  • @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 года назад +3

      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

  • @breensrobert
    @breensrobert 2 года назад

    This is great

  • @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 ❤

  • @lucasianii8178
    @lucasianii8178 7 месяцев назад

    Hi guys, does any body know how I can get IP ADDRESS of devices connected to my mobile phone hotspot in kotlin?

  • @ayushs_2k4
    @ayushs_2k4 Год назад

    How to use it in viewModel where we can't have applicationContext

  • @David-zb8br
    @David-zb8br Год назад

    What if user has +4G on but got no data plan? What can i do in that case?

  • @erfansn869
    @erfansn869 2 года назад

    Wouldn't it be better to use StateFlow, less and cleaner code?

    • @GG9K71
      @GG9K71 2 года назад +1

      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.

  • @SanjayVerma-mf4ch
    @SanjayVerma-mf4ch 2 года назад

    Was searching this yesterday and today got it👍👍

  • @jewelsbypodcasterganesh
    @jewelsbypodcasterganesh 9 месяцев назад

    This doesn't work if the client is using a VPN

  • @apunichjohncena4533
    @apunichjohncena4533 Год назад

    How to pass initial state in non-compose application?

  • @ankushverma9392
    @ankushverma9392 2 года назад +22

    *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

  • @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

  • @ashishtiwadi
    @ashishtiwadi 2 года назад +1

    What if you are connected to a network and internet is not working.😉

    • @raulmaza5138
      @raulmaza5138 2 года назад +1

      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

  • @dmytroberezhnyi717
    @dmytroberezhnyi717 2 года назад +1

    Connectivity means nothing, if it is connected not the fact user have internet

    • @remmievail2003
      @remmievail2003 2 года назад +1

      This is true. Being connecting to a wifi network doesn't mean you have internet connection.

    • @PhilippLackner
      @PhilippLackner  2 года назад +1

      As I said in the video :) you'd need to ping a server and wait for a response to check that

  • @baapkobhaj8133
    @baapkobhaj8133 Год назад

    Hi bro you know me who I'm

  • @Jarakuyaa
    @Jarakuyaa 9 месяцев назад

    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 🤘

  • @izaacdoyle
    @izaacdoyle 2 года назад +1

    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

  • @drackon1995
    @drackon1995 2 года назад

    How can I convert this code to a service, to monitoring all mi app no only one activity? 🤔