Download Code

Xamarin GPS Example Android

In this tutorial you will learn how to get android gps location using Service,Location and Location Manager in xamarin gps example android application.Let me give you some information about classes which you will use in xamarin gps example android.

Xamarin GPS

Global Positioning System is a network of orbiting satellites that send precise details of their position in space back to earth.

Service

A Service is an application component that can perform long-running operations in the background and does not provide a user interface.Callback methods of a service.

  • onStartCommand()
  • onBind()
  • onCreate()
  • onDestroy()

Location

Location class gives geographic location.It contains latitude and longitude etc.

Location Manager

Location Manager provides access to the system location services.For more detail visit Developers site.

Location Listener

Location Listener used for receiving notifications from the LocationManager when the location has changed.

Now create new android application project.Go to your Main.axml and add following components.

  • Four TextViews
  • Button

xamarin gps android, xamarin gps example android, xamarin gps, xamarin gps example, gps example android, how to get location using gps in xamarin, location using gps xamarin android, permission for location in xamarin, gps location manager xamarin android,

Now go to MainActivity.cs class.Do the following steps.

  • Create variables for Two TextView and button.
  • Refer their id’s
  • Apply click event on button using IOnClickListener Interface.

MainActivity.cs

namespace XamarinGPS
{
	[Activity(Label = "XamarinGPS", MainLauncher = true, Icon = "@mipmap/icon")]
	public class MainActivity : Activity, Android.Views.View.IOnClickListener
	{
		
		TextView userLatitude, userLongitude;
		Button getUserLocation;

		protected override void OnCreate(Bundle savedInstanceState)
		{
			base.OnCreate(savedInstanceState);

			// Set our view from the "main" layout resource
			SetContentView(Resource.Layout.Main);
			initialize();

		}
		public void initialize()
		{
			userLatitude = (TextView)FindViewById(Resource.Id.lati);
			userLongitude = (TextView)FindViewById(Resource.Id.longi);
			getUserLocation = (Button)FindViewById(Resource.Id.location);
			getUserLocation.SetOnClickListener(this);
		}

		public void OnClick(View v)
		{
			switch (v.Id)
			{
				case Resource.Id.location:
					
					break;
			}
		}
	}
}

After that create new class GPSHelper.Now do the following steps.

  • Extends GPS.cs class with Service class.
  • Add unimplemented methods of Service class.
  • Implements ILocationListener Interface and add unimplemented methods.
  • Create variables for gps,network,connection_getter,Context,Location Manager and Location.
  • Create constructor with context as a parameter.
  • Create method like getUserLocation() to get latitude and longitude.
  • Some other methods to get the location.
  • Create alert dialog to enable service(GPS,Network) setting.

Android GPS location services class.

GPSHelper.cs

namespace XamarinGPS
{
	[Activity(Label = "GPSHelper")]
	public class GPSHelper : Service, ILocationListener
	{
		private Context con;     // pointer this class means context(this)
		bool GPS_Status = false;     // GPS status variable activated or not
		bool Network_Status = false; // Network service status checker
		bool able_To_Get_Location = false;   // status to check whether whether GPS or Network gives the location
		Location location;

		long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // The minimum distance to change Updates in meters
		long MIN_TIME_BW_UPDATES = 0; // The minimum time between updates in milliseconds
		protected LocationManager locationManager; // Location Manager variable
		double latitude; // latitude
		double longitude; // longitude
						  // constructor for GPS class to set the context and get user location
		public GPSHelper(Context con)
		{
			this.con = con;
			getUserLocation();
		}



		public void OnLocationChanged(Location location)
		{
			this.location = location;
			getLatitude();
			getLongitude();
		}

		public Location getUserLocation()
		{
			try
			{
				locationManager = (LocationManager)con.GetSystemService(LocationService);

				// getting GPS status
				GPS_Status = locationManager.IsProviderEnabled(LocationManager.GpsProvider);

				// getting network status
				Network_Status = locationManager
					.IsProviderEnabled(LocationManager.NetworkProvider);

				if (!GPS_Status && !Network_Status)
				{
					// no network provider is enabled
				}
				else {
					this.able_To_Get_Location = true;
					// First get location from Network Provider
					if (Network_Status)
					{
						locationManager.RequestLocationUpdates(
							LocationManager.NetworkProvider,
								MIN_TIME_BW_UPDATES,
								MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

						if (locationManager != null)
						{
							location = locationManager
								.GetLastKnownLocation(LocationManager.NetworkProvider);
							if (location != null)
							{
								latitude = location.Latitude;
								longitude = location.Longitude;
							}
						}
					}
					// if GPS Enabled get lat/long using GPS Services
					if (GPS_Status)
					{
						if (location == null)
						{
							locationManager.RequestLocationUpdates(
								LocationManager.GpsProvider,
									MIN_TIME_BW_UPDATES,
									MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

							if (locationManager != null)
							{
								location = locationManager
									.GetLastKnownLocation(LocationManager.GpsProvider);
								if (location != null)
								{
									latitude = location.Latitude;
									longitude = location.Longitude;
								}
							}
						}
					}
				}

			}
			catch (Exception e)
			{
				e.StackTrace.ToString();
			}

			return location;
		}




		/**
	 * Function to get latitude
	 * */
		public double getLatitude()
		{
			if (location != null)
			{
				latitude = location.Latitude;
			}

			// return latitude
			return latitude;
		}

		/**
		 * Function to get longitude
		 * */
		public double getLongitude()
		{
			if (location != null)
			{
				longitude = location.Longitude;
			}

			// return longitude
			return longitude;
		}


		// check wifi and GPS status working or not
		public bool able_To_Get_Lo()
		{
			return this.able_To_Get_Location;
		}
		// alert to enable your GPS or Network setting
		// alert to enable your GPS or Network setting
		public void showSettingsAlert()
		{
			AlertDialog.Builder alertDialog = new AlertDialog.Builder(con);

			// Setting Dialog Title
			alertDialog.SetTitle("GPS is settings");

			// Setting Dialog Message
			alertDialog.SetMessage("GPS is not enabled. Do you want to go to settings menu?");

			alertDialog.SetPositiveButton("Settings", (senderAlert, args) =>
			{
				Intent intent = new Intent(Settings.ActionLocationSourceSettings);
				con.StartActivity(intent);
			});

			alertDialog.SetNegativeButton("Cancel", (senderAlert, args) =>
			{
				alertDialog.SetCancelable(true);
			});


			// Showing Alert Message
			alertDialog.Show();

		}

		public void OnProviderDisabled(string provider)
		{
			throw new NotImplementedException();
		}

		public void OnProviderEnabled(string provider)
		{
			throw new NotImplementedException();
		}

		public void OnStatusChanged(string provider, [GeneratedEnum] Availability status, Bundle extras)
		{
			throw new NotImplementedException();
		}
		public override IBinder OnBind(Intent intent)
		{
			throw new NotImplementedException();
		}
	}
}

Next create variable/object of GPS class in MainActivity.Get the location and set to textview.

MainActivity.cs

namespace XamarinGPS
{
	[Activity(Label = "XamarinGPS", MainLauncher = true, Icon = "@mipmap/icon")]
	public class MainActivity : Activity, Android.Views.View.IOnClickListener
	{
		
		TextView userLatitude, userLongitude;
		Button getUserLocation;
		GPSHelper myGPS;
		protected override void OnCreate(Bundle savedInstanceState)
		{
			base.OnCreate(savedInstanceState);

			// Set our view from the "main" layout resource
			SetContentView(Resource.Layout.Main);
			initialize();
			myGPS = new GPSHelper(this);

		}
		public void initialize()
		{
			userLatitude = (TextView)FindViewById(Resource.Id.lati);
			userLongitude = (TextView)FindViewById(Resource.Id.longi);
			getUserLocation = (Button)FindViewById(Resource.Id.location);
			getUserLocation.SetOnClickListener(this);
		}

		public void OnClick(View v)
		{
			switch (v.Id)
			{
				case Resource.Id.location:
					if (myGPS.able_To_Get_Lo())
					{
						double codecLatitude = myGPS.getLatitude();
						double codecLongitude = myGPS.getLongitude();
						userLatitude.Text = codecLatitude.ToString();
						userLongitude.Text = codecLongitude.ToString();
						Toast.MakeText(this, "Location Successfully set", ToastLength.Short).Show();
					}
					else {
						myGPS.showSettingsAlert();
					}
					break;
			}
		}
	}
}

Now go to Xamarin gps example android project Properties > Android Manifest.xml and add ACCESS_FINE_LOCATION permission.

Now run android application project.

xamarin gps android, xamarin gps example android, xamarin gps, xamarin gps example, gps example android, how to get location using gps in xamarin, location using gps xamarin android, permission for location in xamarin, gps location manager xamarin android,

That’s it for this tutorial Xamarin GPS example Android.

Thanks.