Android Xamarin Detect Network Connection and Geo Location

The code sample below demonstrates how to detect the newtwork connection in use and query a specific type of network connection, as well identify the user's current Geo location in Android Xamarin.

1) Status of Network connection:
Andriod provides the ConnectivityManager class to identify the state of a network connection.

ConnectivityManager connectivity = (ConnectivityManager)(Application.Context.ApplicationContext).GetSystemService(Context.ConnectivityService);

The status of the network connection can be verified in NetworkInfo class

NetworkInfo[] info = connectivity.GetAllNetworkInfo();
                  
if (info != null)
                     
for (int i = 0; i < info.Length; i++)
                          
if (info[i].GetState() == NetworkInfo.State.Connected)
                          {
                              
// we are connected to a network
                         }


2) Query a Connection Type:
   It is also possible to query a perticular connection type, for eaxmple if device is connected by WiFi

var mobileState = connectivit
y.GetNetworkInfo(ConnectivityType.Mobile).GetState();

if (mobileState == NetworkInfo.State.Connected)
{
  
// We are connected via WiFi
}

3) Get
Current Device Location:

Android provides the LocationManager class to get the device location. This class will listen the GPS updates from the device and notfied by the application.

  a) Add below user
permissions to AsseblyInfo.cs file which are necessary to use the LocationServices

[assembly: UsesPermission(Manifest.Permission.AccessFineLocation)]
[assembly: UsesPermission(Manifest.Permission.AccessCoarseLocation)]
[assembly: UsesPermission(Manifest.Permission.Internet)]

  
b) If you are using Visual Studio, Right click on Android Project, select the Properties, then select the option Android Manifest and check the "ACCESS_COARSE_LOCATION", "ACCESS_FINE_LOCATION" and "ACCESS_NETWORK_STATE".

  
c) Add a method InitializeLocationManager

private void InitializeLocationManager()
        {
            _locationManager = (LocationManager)(Application.Context.ApplicationContext).GetSystemService(Context.LocationService);
            Criteria criteriaForLocationService =
new Criteria
            {
                Accuracy = Accuracy.Fine
            };

            IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService,
true);

             
if (acceptableLocationProviders.Any())
            {
                _locationProvider = acceptableLocationProviders.
First();
            }
            
else
            {
                _locationProvider = String.
Empty;              
            }
        }

or you can slightly modify the above function if you face any issue, this is alternative way to find the current location
private void InitializeLocationManager()
            {
            _locationManager = (LocationManager)(Application.Context.ApplicationContext).GetSystemService(Context.LocationService);            
            Criteria criteria = new Criteria();
            _locationProvider= _locationManager.GetBestProvider(criteria, true);                    
            OnLocationChanged( _locationManager.GetLastKnownLocation(_locationProvider));
         }
    d) Inherit the
ILocationListener and add the methods required by this interface. below are the methods required by the interface.

    public void OnLocationChanged(Location location) {}

    
public void OnProviderDisabled(string provider) {}

    
public void OnProviderEnabled(string provider) {}

    
public void OnStatusChanged(string provider, Availability status, Bundle extras) {}

  e)  Add below code in a GetLocationUpdate method
private async Task<string> GetLocationUpdate()
{

try
            {
                 InitializeLocationManager();
                 
if (_currentLocation == null)
                 {
                     
return string.Empty;
                }

                Geocoder geocoder =
new Geocoder(Application.Context.ApplicationContext);
                IList<Address> addressList = await geocoder.GetFromLocationAsync(_currentLocation.Latitude, _currentLocation.Longitude, 10);

                Address address = addressList.FirstOrDefault();
                 
if (address != null)
                {
                    StringBuilder userAddress =
new StringBuilder();
                     
for (int i = 0; i < address.MaxAddressLineIndex; i++)
                      {
                          userAddress.Append(address.GetAddressLine(i)).AppendLine(
",");
                    }
                    await Task.Factory.FromAsync(_client.BeginUpdateUserGeoLocation, _client.EndUpdateUserGeoLocation, candidateId,
Convert.ToString(userAddress), TaskCreationOptions.None);
                }
            }
            catch (UnauthorizedAccessException exception)
             {
                 
return "Location is disabled in user Phone Settings";
            }
            catch (Exception ex)
             {
                 
return ex.Message;
             }
}
Above function uses the GeoCoder API to retrieve the current street address for the current location. this function call should be async/await.

f) Update the method OnLocationChanged to display the latitude and longitude when GPS updates are received:
public void OnLocationChanged(Location location) { _currentLocation = location; }

Note: test this code in real device, not in emulator. Emulators may not give accurate results.

Please download the sample from below location
http://nullskull.com/FileUpload/-407123783_LocationSample.zip      

By Siva Jagan Dhulipalla   Popularity  (2579 Views)