xamarin.androidandroid-serviceandroid-service-binding

Upload data in the background depending on the connectivity


I am having problems with understanding how to approach this problem as I am really new to xamarin and android both.

My problem is the following: I need to develop an android app, which takes photos of things and uploads them to a rest server. The confusing part is that the users have really poor connection, so I need to check the internet connection constantly and try to upload the photos when the internet is there. This check needs to be done in the background so the user wont notice any lag.

When the user clicks on "save" the app should save the photo and metadata to a local database or file (json or sqlite) and upload them when the internet is there.

I have tried many different approaches but failed due to lack of understanding how android threading and services work. (Bound service, Foregroundservice, SQLite)

As I dont have much time to research and test all the posibilities, I am asking you guys: How can I do this ?

Thanks for your understanding.


Solution

  • There is one nuget plugin Xam.Plugin.Connectivity for check internet continuously, and you can manage your code in event of this plugin. For background, you need to create one background thread and you can call it from ConnectivityChanged event.

     CrossConnectivity.Current.ConnectivityChanged += (object sender, Plugin.Connectivity.Abstractions.ConnectivityChangedEventArgs e) =>
        {
              if(e.IsConnected){
                //your code here for fetching data when internet connected.
                //Create task for background process 
                Task.Run(() =>
                {
                    //your code for background
    
                }).ConfigureAwait(false);
              }
        }