Пример #1
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="context"></param>
        public LocationTracker(Context context, string provider = LocationManager.GpsProvider)
        {
            locationMan = (LocationManager)context.GetSystemService(Service.LocationService);

            if(locationMan.GetProviders(true).Contains(provider))
            {
                Provider = provider;
            }
            else if (locationMan.IsProviderEnabled(LocationManager.GpsProvider))
            {
                Provider = LocationManager.GpsProvider;
            }
            else if (locationMan.IsProviderEnabled(LocationManager.NetworkProvider))
            {
                Provider = LocationManager.NetworkProvider;
            }
            else
            {
                Criteria crit = new Criteria();
                crit.Accuracy = Accuracy.Fine;
                Provider = locationMan.GetBestProvider(crit, true);
            }

            LastGPSReceived = DateTime.MinValue;
        }
        private PhoneRequirements CheckLocationRequirements()
        {
            _locationManager = (LocationManager)GetSystemService(LocationService);
            _connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);

            var internetAccess = _connectivityManager.ActiveNetworkInfo;

            return new PhoneRequirements()
            {
                Gps = _locationManager.IsProviderEnabled(LocationManager.GpsProvider),
                Network = _locationManager.IsProviderEnabled(LocationManager.NetworkProvider),
                Internet = internetAccess != null && internetAccess.IsConnected
            };
        }
		public Location GetLocation() {
			try {
				locationManager = (LocationManager)mContext.GetSystemService("location");

				// Getting GPS status
				isGPSEnabled = locationManager.IsProviderEnabled(LocationManager.GpsProvider);

				// Getting network status
				isNetworkEnabled = locationManager.IsProviderEnabled(LocationManager.NetworkProvider);

				if (!isGPSEnabled && !isNetworkEnabled) {
					//showalert in activity
				}
				else {
					this.CanGetLocation = true;
					if (isNetworkEnabled) {
						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 (isGPSEnabled) {
						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) {
				AlertsService.ShowToast(this.mContext, "Nie masz w³¹czonej lokalizacji!");
			}

			return location;
		}
Пример #4
0
        protected override void OnResume()
        {
            base.OnResume();

            locMgr = GetSystemService(Context.LocationService) as LocationManager;

#if DEBUG
            // 利用可能な LocationManager の Provider とオンオフをチェック
            foreach (var item in locMgr.AllProviders)
            {
                Log.Debug("NetworkList", "Provider: " + item.ToString());
                Log.Debug("NetworkList", "Avalable: " + locMgr.IsProviderEnabled(item.ToString()));
            }
#endif

            button.Click += (sender, e) =>
            {
                if (button.Text.ToUpper() == "GET LOCATION")
                {
                    button.Text = "Location Service Running";

                    if (locMgr.AllProviders.Contains(LocationManager.NetworkProvider)
                        && locMgr.IsProviderEnabled(LocationManager.NetworkProvider))
                    {
                        // Network: Wifi と 3G で位置情報を取得します。電池使用量は少ないですが精度にばらつきがあります。
                        Log.Debug(tag, "Starting location updates with Network");
                        locMgr.RequestLocationUpdates(LocationManager.NetworkProvider, 10000, 10, this);
                    }
                    else
                    {
                        // GetBestProvider で最適な Provider を利用できるようです。(Network があればそれが Best になるようです。)
                        var locationCriteria = new Criteria();
                        locationCriteria.Accuracy = Accuracy.Coarse;
                        locationCriteria.PowerRequirement = Power.Medium;
                        string locationProvider = locMgr.GetBestProvider(locationCriteria, true);

                        Log.Debug(tag, "Starting location updates with " + locationProvider.ToString());
                        locMgr.RequestLocationUpdates(locationProvider, 10000, 10, this);
                    }
                }
                else
                {
                    Log.Debug(tag, "Stop locMgr manually");
                    locMgr.RemoveUpdates(this);
                    button.Text = "Get Location";
                }

            };
        }
Пример #5
0
        protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

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

            // Get our button from the layout resource,
            // and attach an event to it
            nameEditText = FindViewById<EditText>(Resource.Id.firstNameTextField);
            surnameEditText = FindViewById<EditText>(Resource.Id.surNameTextField);

            locM = GetSystemService(Context.LocationService) as LocationManager;
            if (locM.IsProviderEnabled(LocationManager.GpsProvider))
                locM.RequestLocationUpdates(LocationManager.GpsProvider, 2000, 1, this);


            Button notificationButton1 = FindViewById<Button>(Resource.Id.notificationButton1);
            Button notificationButton2 = FindViewById<Button>(Resource.Id.notificationbutton2);
            Button notificationButton3 = FindViewById<Button>(Resource.Id.notificationbutton3);
            Button notificationButton4 = FindViewById<Button>(Resource.Id.notificationbutton4);
            Button notificationButton5 = FindViewById<Button>(Resource.Id.notificationbutton5);
            textView = FindViewById<TextView>(Resource.Id.textView2);


            notificationButtons = new Button[] { notificationButton1, notificationButton2, notificationButton3, notificationButton4, notificationButton5 };

            foreach (Button button in notificationButtons)
            {
                button.Enabled = false;
                button.Click += SendNotification;
            }            
		}
        protected override void PlatformSpecificStart(MvxLocationOptions options)
        {
            if (_locationManager != null)
                throw new MvxException("You cannot start the MvxLocation service more than once");

            _locationManager = (LocationManager)Context.GetSystemService(Context.LocationService);
            if (_locationManager == null)
            {
                MvxTrace.Warning("Location Service Manager unavailable - returned null");
                SendError(MvxLocationErrorCode.ServiceUnavailable);
                return;
            }
            var criteria = new Criteria()
                {
                    Accuracy = options.Accuracy == MvxLocationAccuracy.Fine ? Accuracy.Fine : Accuracy.Coarse,
                };
            _bestProvider = _locationManager.GetBestProvider(criteria, true);
            if (_bestProvider == null)
            {
                MvxTrace.Warning("Location Service Provider unavailable - returned null");
                SendError(MvxLocationErrorCode.ServiceUnavailable);
                return;
            }

            _locationManager.RequestLocationUpdates(
                _bestProvider, 
                (long)options.TimeBetweenUpdates.TotalMilliseconds,
                options.MovementThresholdInM, 
                _locationListener);

			Permission = _locationManager.IsProviderEnabled (_bestProvider)
				? MvxLocationPermission.Granted
				: MvxLocationPermission.Denied;
        }
Пример #7
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());

            //Käynnistetään GPS-paikannus
            try
            {
                LocationManager = GetSystemService(
                    "location") as LocationManager;
                string Provider = LocationManager.GpsProvider;

                if (LocationManager.IsProviderEnabled(Provider))
                {
                    LocationManager.RequestLocationUpdates(
                        Provider, 2000, 1, this);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
        protected override void OnResume()
        {
            base.OnResume();

            // LocationManagerを初期化
            locMgr = GetSystemService(Context.LocationService) as LocationManager;

            button.Click += (sender, e) =>
            {
                if (locMgr.AllProviders.Contains(LocationManager.NetworkProvider)
                        && locMgr.IsProviderEnabled(LocationManager.NetworkProvider))
                {
                    // Network: Wifiと3Gで位置情報を取得します。電池使用量は少ないですが精度にばらつきがあります。
                    Log.Debug(tag, "Starting location updates with Network");
                    locMgr.RequestLocationUpdates(LocationManager.NetworkProvider, 10000, 10, this);
                }
                else
                {
                    // GetBestProviderで最適なProviderを利用できるようです。(NetworkがあればそれがBestProviderになるようです。)
                    var locationCriteria = new Criteria();
                    locationCriteria.Accuracy = Accuracy.Coarse;
                    locationCriteria.PowerRequirement = Power.Medium;
                    string locationProvider = locMgr.GetBestProvider(locationCriteria, true);

                    Log.Debug(tag, "Starting location updates with " + locationProvider.ToString());
                    locMgr.RequestLocationUpdates(locationProvider, 10000, 10, this);
                }
            };
        }
Пример #9
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            AndroidMainActivity = this;

            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new App());

            // käynnistetään GPS-paikannus
            try
            {
                LocationManager = GetSystemService(
                    "location") as LocationManager;
                string Provider = LocationManager.GpsProvider;

                if (LocationManager.IsProviderEnabled(Provider))
                {
                    LocationManager.RequestLocationUpdates(
                        Provider, 2000, 1, this);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
 protected override void GetCurrentLocation()
 {
     locationManager = context.GetSystemService(Context.LocationService) as LocationManager;
     if (locationManager.IsProviderEnabled(LocationManager.GpsProvider))
         locationManager.RequestLocationUpdates(LocationManager.GpsProvider, 2000, 1, this);
     
 }
Пример #11
0
 //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 //Check if GPS Enabled
 public static bool IsGPSProviderEnabled(LocationManager pLocMgr)
 {
     if (pLocMgr.IsProviderEnabled(LocationManager.GpsProvider))
       {
     return true;
       }
       else
       {
     return false;
       }
 }
        public GeolocationContinuousListener(LocationManager manager, TimeSpan timePeriod, IList<string> providers)
        {
            this.manager = manager;
            this.timePeriod = timePeriod;
            this.providers = providers;

            foreach (string p in providers)
            {
                if (manager.IsProviderEnabled(p))
                    this.activeProviders.Add(p);
            }
        }
Пример #13
0
		void InitializeLocationManager()
		{
			locMgr = GetSystemService (Context.LocationService) as LocationManager;

			if (locMgr.AllProviders.Contains (LocationManager.NetworkProvider)
				&& locMgr.IsProviderEnabled (LocationManager.NetworkProvider)) {
				locMgr.RequestLocationUpdates (LocationManager.NetworkProvider, 0, 0, this);
			} else {
				MApplication.getInstance().longitude = 0;
				MApplication.getInstance().latitude = 0;
			}
		}
Пример #14
0
        protected override void OnResume()
        {
            base.OnResume ();

            locMgr = GetSystemService (Context.LocationService) as LocationManager;

            if (locMgr.AllProviders.Contains (LocationManager.NetworkProvider)
                && locMgr.IsProviderEnabled (LocationManager.NetworkProvider)) {
                locMgr.RequestLocationUpdates (LocationManager.NetworkProvider, 2000, 1, this);
            } else {
                Toast.MakeText (this, "The Network Provider does not exist or is not enabled!", ToastLength.Long).Show ();
            }
        }
		/// <summary>
		///     Initializes a new instance of the <see cref="GeolocationContinuousListener" /> class.
		/// </summary>
		/// <param name="manager">The manager.</param>
		/// <param name="timePeriod">The time period.</param>
		/// <param name="providers">The providers.</param>
		public GeolocationContinuousListener(LocationManager manager, TimeSpan timePeriod, IList<string> providers)
		{
			_manager = manager;
			_timePeriod = timePeriod;
			_providers = providers;

			foreach (var p in providers)
			{
				if (manager.IsProviderEnabled(p))
				{
					_activeProviders.Add(p);
				}
			}
		}
        public void StartService()
        {
            _locMan = Application.Context.GetSystemService (Context.LocationService) as LocationManager;

            if (_locMan.GetProvider (LocationManager.GpsProvider) != null && _locMan.IsProviderEnabled (LocationManager.GpsProvider))
            {
                _pi = PendingIntent.GetBroadcast(Application.Context, 0, new Intent(), PendingIntentFlags.UpdateCurrent);
                _locMan.RequestLocationUpdates(LocationManager.GpsProvider, 2000, 5, _pi);
                _locMan.GetLastKnownLocation (LocationManager.GpsProvider);
            }

            else
                throw new GPSNotEnabledException (Const.NO_GPS_ERROR_MESSAGE);
        }
Пример #17
0
		public override void OnStart (Android.Content.Intent intent, int startId)
		{
			base.OnStart (intent, startId);

			DBRepository dbr = new DBRepository ();
			userAndsoft = dbr.getUserAndsoft ();
			userTransics = dbr.getUserTransics ();

			var t = DateTime.Now.ToString("dd_MM_yy");
			string dir_log = (Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads)).ToString();
			ISharedPreferences pref = Application.Context.GetSharedPreferences("AppInfo", FileCreationMode.Private);
			string log = pref.GetString("Log", String.Empty);
			//GetTelId
			TelephonyManager tel = (TelephonyManager)this.GetSystemService(Context.TelephonyService);
			var telId = tel.DeviceId;

			//Si il n'y a pas de shared pref
			if (log == String.Empty){
				log_file = Path.Combine (dir_log, t+"_"+telId+"_log.txt");
				ISharedPreferencesEditor edit = pref.Edit();
				edit.PutString("Log",log_file);
				edit.Apply();
			}else{
				//il y a des shared pref
				log_file = pref.GetString("Log", String.Empty);
				if (((File.GetCreationTime(log_file)).CompareTo(DateTime.Now)) > 3) {
					File.Delete(log_file);
					log_file = Path.Combine (dir_log, t+"_"+telId+"_log.txt");
					ISharedPreferencesEditor edit = pref.Edit();
					edit.PutString("Log",log_file);
					edit.Apply();
					log_file = pref.GetString("Log", String.Empty);
				}

			}
			File.AppendAllText(log_file,"[SERVICE] Service Onstart call "+DateTime.Now.ToString("t")+"\n");
			DoStuff ();

			// initialize location manager
			locMgr = GetSystemService (Context.LocationService) as LocationManager;

			if (locMgr.AllProviders.Contains (LocationManager.NetworkProvider)
				&& locMgr.IsProviderEnabled (LocationManager.NetworkProvider)) {
				locMgr.RequestLocationUpdates (LocationManager.NetworkProvider, 2000, 1, this);
				File.AppendAllText(log_file,"[GPS] Lancer le"+DateTime.Now.ToString("t")+"\n");
			} else {
				File.AppendAllText(log_file,"[GPS] Le GPS est désactiver"+DateTime.Now.ToString("t")+"\n");
			}
		}
Пример #18
0
        public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
        {
            locMgr = GetSystemService(Context.LocationService) as LocationManager;

            if (locMgr.AllProviders.Contains(LocationManager.NetworkProvider)
                && locMgr.IsProviderEnabled(LocationManager.NetworkProvider))
            {
                locMgr.RequestLocationUpdates(LocationManager.NetworkProvider, 2000, 1, this);
            }
            else
            {
                API apiCall = new API();
                apiCall.addReport("GPS is disabled");
                StopSelf();

            }

            return StartCommandResult.NotSticky;
        }
Пример #19
0
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            //...

            Xamarin.Essentials.Platform.Init(this, bundle); // add this line to your code, it may also be called: bundle
            //...

            global::Xamarin.Forms.Forms.Init(this, bundle);

            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) != Permission.Granted)
            {
                List <string> permission = new List <string>();
                permission.Add(Manifest.Permission.AccessFineLocation);

                if (permission.Count > 0)
                {
                    string[] array = permission.ToArray();

                    RequestPermissions(array, array.Length);
                }
            }

            try
            {
                locationManager = GetSystemService("location") as LocationManager;
                string Provider = LocationManager.GpsProvider;

                if (locationManager.IsProviderEnabled(Provider))
                {
                    locationManager.RequestLocationUpdates(Provider, 2000, 1, this);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            LoadApplication(new App());
        }
Пример #20
0
		// OnResume gets called every time the activity starts, so we'll put our RequestLocationUpdates
		// code here, so that 
		protected override void OnResume ()
		{
			base.OnResume (); 
			Log.Debug (tag, "OnResume called");

			// initialize location manager
			locMgr = GetSystemService (Context.LocationService) as LocationManager;

			button.Click += delegate {
				button.Text = "Location Service Running";

				// pass in the provider (GPS), 
				// the minimum time between updates (in seconds), 
				// the minimum distance the user needs to move to generate an update (in meters),
				// and an ILocationListener (recall that this class impletents the ILocationListener interface)
				if (locMgr.AllProviders.Contains (LocationManager.NetworkProvider)
					&& locMgr.IsProviderEnabled (LocationManager.NetworkProvider)) {
					locMgr.RequestLocationUpdates (LocationManager.NetworkProvider, 2000, 1, this);
				} else {
					Toast.MakeText (this, "The Network Provider does not exist or is not enabled!", ToastLength.Long).Show ();
				}


				// Comment the line above, and uncomment the following, to test 
				// the GetBestProvider option. This will determine the best provider
				// at application launch. Note that once the provide has been set
				// it will stay the same until the next time this method is called

				/*var locationCriteria = new Criteria();

				locationCriteria.Accuracy = Accuracy.Coarse;
				locationCriteria.PowerRequirement = Power.Medium;

				string locationProvider = locMgr.GetBestProvider(locationCriteria, true);

				Log.Debug(tag, "Starting location updates with " + locationProvider.ToString());
				locMgr.RequestLocationUpdates (locationProvider, 2000, 1, this);*/
			};
		}
Пример #21
0
		protected override void OnCreate (Bundle bundle)
		{

			base.OnCreate(bundle);

			connectivityManager = GetSystemService(ConnectivityService) as ConnectivityManager;
			locationManager = GetSystemService(LocationService) as LocationManager;

			var mobileState = connectivityManager.GetNetworkInfo(ConnectivityType.Wifi).GetState();
			provider = LocationManager.NetworkProvider;
			locationManager = (LocationManager)GetSystemService(LocationService);
			if (mobileState == NetworkInfo.State.Disconnected) {
				// We are connected via WiFi
				AlertDialog.Builder wifiError = new AlertDialog.Builder (this);
				AlertDialog wifiAlert = wifiError.Create ();
				wifiAlert.SetTitle ("Error Connection");
				wifiAlert.SetMessage ("There is no wifi connection!Please connect to wifi and try again!App now will close!");
				wifiAlert.SetButton ("Ok", delegate {
					wifiAlert.Dismiss ();
					System.Environment.Exit (0);					
				});
			} 
			else if (!locationManager.IsProviderEnabled (provider)) 
			{
				AlertDialog.Builder gpsError = new AlertDialog.Builder (this);
				AlertDialog gpsAlert = gpsError.Create ();
				gpsAlert.SetTitle ("Error Connection");
				gpsAlert.SetMessage ("There is no wifi connection!Please connect to wifi and try again!App now will close!");
				gpsAlert.SetButton ("Ok", delegate {
					gpsAlert.Dismiss ();
					System.Environment.Exit (0);
				});					
			}
			else 
			{
				ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
				ActionBar.SetDisplayShowHomeEnabled (false);
				ActionBar.SetDisplayShowTitleEnabled (false);
				SetContentView(Resource.Layout.Main);

				locationText = FindViewById<TextView>(Resource.Id.location);
				locationText.Text = "Please wait until we find you with our spy devices :)";
				addressText = String.Empty;
				home = new HomeFragment ();
				search = new SearchFragment ();

				mCurrentFragment = home;
				mStackFragments = new Stack<Fragment>();

				var homeTab = ActionBar.NewTab();
				homeTab.SetText(Resources.GetString(Resource.String.tab1_text));
				homeTab.SetIcon(Resource.Drawable.home_icon);
				homeTab.SetTabListener (this);
				ActionBar.AddTab(homeTab);

				var searchTab = ActionBar.NewTab();
				searchTab.SetText(Resources.GetString(Resource.String.tab2_text));
				searchTab.SetIcon(Resource.Drawable.search_icon);
				searchTab.SetTabListener (this);
				ActionBar.AddTab(searchTab);

				var trans = FragmentManager.BeginTransaction ();
				trans.Add (Resource.Id.fragmentContainer, home, "Home");
				trans.Add (Resource.Id.fragmentContainer, search, "Search");
				trans.Hide (search);
				trans.Commit ();
				InitializeLocationManager ();	
			}
		}
Пример #22
0
        // OnResume gets called every time the activity starts, so we'll put our RequestLocationUpdates
        // code here, so that
        protected override void OnResume()
        {
            base.OnResume ();
            Log.Debug (tag, "OnResume called");

            // initialize location manager
            locMgr = GetSystemService (Context.LocationService) as LocationManager;

            getLoc.Click += delegate {
                // pass in the provider (GPS),
                // the minimum time between updates (in seconds),
                // the minimum distance the user needs to move to generate an update (in meters),
                // and an ILocationListener (recall that this class impletents the ILocationListener interface)
                if (locMgr.AllProviders.Contains (LocationManager.NetworkProvider)
                    && locMgr.IsProviderEnabled (LocationManager.NetworkProvider)) {
                    getLoc.Text = "Getting location...";
                    locMgr.RequestLocationUpdates (LocationManager.NetworkProvider, 2000, 1, this);
                } else {
                    //set alert for executing the task
                    AlertDialog.Builder alert = new AlertDialog.Builder (this);
                    alert.SetTitle ("Please enable location services");
                    alert.SetNeutralButton ("OK", (senderAlert, args) => {} );
                    //run the alert in UI thread to display in the screen
                    RunOnUiThread (() => {
                        alert.Show();
                    });
                }
            };
        }
Пример #23
0
        private void InitLocation()
        {
            try
            {
                _locationManager = (LocationManager)_context.GetSystemService(LocationService);

                // getting GPS status
                _isGPSEnabled = _locationManager.IsProviderEnabled(LocationManager.GpsProvider);

                // getting network status
                _isNetworkEnabled = _locationManager.IsProviderEnabled(LocationManager.NetworkProvider);

                if (!_isGPSEnabled && !_isNetworkEnabled)
                {
                    // no network provider is enabled
                }
                else
                {
                    this._canGetLocation = true;
                    if (_isNetworkEnabled)
                    {
                        _locationManager.RequestLocationUpdates(LocationManager.NetworkProvider,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES,
                            this);

                        Log.Debug("Network", "Network Enabled");

                        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 (_isGPSEnabled)
                    {
                        if (_location == null)
                        {
                            _locationManager.RequestLocationUpdates(
                                    LocationManager.GpsProvider,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.Debug("GPS", "GPS Enabled");

                            if (_locationManager != null)
                            {
                                _location = _locationManager.GetLastKnownLocation(LocationManager.GpsProvider);
                                if (_location != null)
                                {
                                    _latitude = _location.Latitude;
                                    _longitude = _location.Longitude;
                                }
                            }
                        }
                    }
                }

            }
            catch (Exception e)
            {
                Log.Error("Location Error", e.StackTrace);
            }
        }
		void InitializeLocationManager()
		{
			_locationManager = (LocationManager)GetSystemService(LocationService);
			if (_locationManager.IsProviderEnabled (LocationManager.GpsProvider))
				IsGpsOn = true;
			else
				IsGpsOn = false;

			if (IsGpsOn) {
				//Check If GPS is available;
				Criteria criteriaForLocationService = new Criteria
				{
					Accuracy = Accuracy.Fine
				};
				IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);

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



			} else {
				Toast.MakeText (this, "Turn on GPS ", ToastLength.Short).Show ();
			}
		}
Пример #25
0
        async void InitializeLocationManager()
        {


            _locationManager = (LocationManager)GetSystemService(LocationService);
            Criteria criteriaForLocationService = new Criteria
            {
                Accuracy = Accuracy.NoRequirement,

            };

            var enabled = _locationManager.IsProviderEnabled(LocationManager.NetworkProvider);
            var enabled2 = _locationManager.IsProviderEnabled(LocationManager.GpsProvider);
            IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);



            if (acceptableLocationProviders.Any())
            {
                _locationProvider = acceptableLocationProviders.First();
            }
            else
            {
                _locationProvider = LocationManager.PassiveProvider;

                await CheckGoogleLocationSettings();


            }
            Log.Debug(TAG, "Using " + _locationProvider + ".");
        }
Пример #26
0
        /// <summary>
        /// Method to get latitude and longitude of device
        /// </summary>
        public void InitializeLocationManager()
        {
            try
            {
                bool isNetworkEnabled = false;

                bool isGPSEnabled = false;

                locationManager = (LocationManager)GetSystemService(Context.LocationService);

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

                isGPSEnabled = locationManager.IsProviderEnabled(LocationManager.GpsProvider);

                if (!isNetworkEnabled && !isGPSEnabled)
                {
                    // no network provider is enabled
                    Toast.MakeText(this, "No location providers available !", ToastLength.Short).Show();
                }
                else
                {
                    // First get location from Network Provider
                    if (isNetworkEnabled)
                    {
                        locationManager.RequestLocationUpdates(LocationManager.NetworkProvider, 0, 0, this);

                        if (locationManager != null)
                        {
                            location = locationManager.GetLastKnownLocation(LocationManager.NetworkProvider);
                            if (location != null)
                            {
                                if (location.Latitude != 0.0 && location.Longitude != 0.0)
                                {
                                    GeoLocations.Latitude = location.Latitude;
                                    GeoLocations.Longitude = location.Longitude;
                                }
                            }
                        }
                    }
                    // if GPS Enabled get lat/long using GPS Services
                    if (isGPSEnabled)
                    {
                        locationManager.RequestLocationUpdates(LocationManager.GpsProvider, 0, 0, this);
                        if (locationManager != null)
                        {
                            location = locationManager.GetLastKnownLocation(LocationManager.GpsProvider);
                            if (location != null)
                            {
                                if (location.Latitude != 0.0 && location.Longitude != 0.0)
                                {
                                    GeoLocations.Latitude = location.Latitude;
                                    GeoLocations.Longitude = location.Longitude;
                                }
                            }
                        }
                    }
                }
            }
            catch ( InvalidOperationException ex)
            {
                Toast.MakeText(this, GlobalConstants.ErrorMessage + ex.ToString(), ToastLength.Short);
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, GlobalConstants.ErrorMessage + ex.ToString(), ToastLength.Short);
            }
        }
Пример #27
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

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

            // Get our UI controls from the loaded layout:
            curLongitude = FindViewById<TextView>(Resource.Id.CurrentLongitudeText);
            curLatitude = FindViewById<TextView>(Resource.Id.CurrentLattitudeText);
            testNotificationButton = FindViewById<Button>(Resource.Id.TestNotificationButton);
            curTestLongitude = FindViewById<TextView>(Resource.Id.CurTestLongitude);
            curTestLatitude = FindViewById<TextView>(Resource.Id.CurTestLatitude);
            testLongitude = FindViewById<EditText>(Resource.Id.TestLongitude);
            testLatitude = FindViewById<EditText>(Resource.Id.TestLatitude);
            setTestCoordinatesButton = FindViewById<Button>(Resource.Id.SetTestCoordinatesButton);

            insideRadius = false;
            locMgr = GetSystemService (LocationService) as LocationManager;
            Provider = LocationManager.GpsProvider;

            if(locMgr.IsProviderEnabled(Provider))
            {
                locMgr.RequestLocationUpdates (Provider, 2000, 1, this);
            }
            else
            {
                //Log.Info(tag, Provider + " is not available. Does the device have location services enabled?");
            }

            testNotificationButton.Click += (sender, e) => {
                SendNotification();
            };

            setTestCoordinatesButton.Click += (sender, e) => {
                Double number;
                if (Double.TryParse(testLongitude.Text, out number))
                {
                    testLongitudeValue = number*-1.0;
                    curTestLongitude.Text = testLongitudeValue.ToString();
                    testLongitude.Text = "";
                }
                if (Double.TryParse(testLatitude.Text, out number))
                {
                    testLatitudeValue = number;
                    curTestLatitude.Text = testLatitudeValue.ToString();
                    testLatitude.Text = "";
                }
            };
        }
Пример #28
0
		void InitializeLocationManager()
		{
			locMgr = GetSystemService (Context.LocationService) as LocationManager;

			if (!(locMgr.AllProviders.Contains (LocationManager.NetworkProvider) && locMgr.IsProviderEnabled (LocationManager.NetworkProvider))) {
				ShowDialog (1);
				Utils.keepAskedFirstTimeGPS (true);
			}
		}
Пример #29
0
		protected override void OnResume ()
		{
			base.OnResume (); 

			if (!IsRefreshing & !notCurrentLocation) 
			{
				IsRefreshing;
				// Initialize location manager
				locMgr = GetSystemService (Context.LocationService) as LocationManager;
				// pass in the provider (GPS), 
				// the minimum time between updates (in seconds), 
				// the minimum distance the user needs to move to generate an update (in meters),
				// and an ILocationListener (recall that this class impletents the ILocationListener interface)
				if (locMgr.AllProviders.Contains (LocationManager.NetworkProvider)
					 && locMgr.IsProviderEnabled (LocationManager.NetworkProvider)) 
				{
					!IsRefreshing;
					locMgr.RequestLocationUpdates (LocationManager.NetworkProvider, 10000, 100, this);
				} else {
					Toast.MakeText (this, "The Network Provider does not exist or is not enabled!", ToastLength.Long).Show ();
				}
			}
		}