Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Broadcast receiver listening for connectivity change firing at random intervals

I have a Xamarin.Android application that is supposed to sync my data when the device it is running on connects to a WiFi network. To save data and battery I only let this happen whenever it detects a connections.

The only thing is, the application would randomly run the sync service multiple time throughout the day, despite the WiFi connection remaining constant. Now, I can only imagine that the Android system is sending out the broadcast multiple times to remind applications of the connection state or something like that.

I've used a bit of a quick fix, the static bool FirstTime there, but I'm hoping to find a bit more of an elegant solution. Any suggestions?

This is the code I'm using to do it:

[BroadcastReceiver]
[IntentFilter(new string[] { "android.net.conn.CONNECTIVITY_CHANGE" })]
class ConnectivityReceiver : BroadcastReceiver
{
    public static bool FirstTime = true;
    public override void OnReceive(Context context, Intent intent)
    {
        if ( intent.Action != null && intent.Action == "android.net.conn.CONNECTIVITY_CHANGE") 
        {
            ConnectivityManager cm = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService);
            NetworkInfo info = cm.ActiveNetworkInfo;
            if (FirstTime && info != null)
            {
                FirstTime = false;
                Intent background = new Intent(context, typeof(BackgroundDataSyncService));
                context.StartService(background);
            }else
            {
                FirstTime = true;
                Intent background = new Intent(context, typeof(BackgroundDataSyncService));
                context.StopService(background);
            }
        }
    }
}
like image 796
Fireprufe15 Avatar asked Oct 30 '22 02:10

Fireprufe15


1 Answers

You have a plugin called Connectivity that can pulled from nuget. This plugin is compatible with almost every mobile platform and it can be used only in android it you want. The plugin does all that code for you and you only have to subscribe to connectivity events like:

CrossConnectivity.Current.ConnectivityChanged += (sender, args) =>
{
    page.DisplayAlert("Connectivity Changed", "IsConnected: " + args.IsConnected.ToString(), "OK");
};

The plugin has another nice features please take a look at the documentation.

like image 108
jzeferino Avatar answered Nov 10 '22 15:11

jzeferino