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

			AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionLocal;
			AndroidEnvironment.UnhandledExceptionRaiser +=  HandleAndroidException;
			Xamarin.Forms.Forms.Init (this, bundle);

			Forms.Init(this, bundle);
			FormsMaps.Init(this, bundle);

			_locationManager = GetSystemService (Context.LocationService) as LocationManager;
			Criteria locationCriteria = new Criteria();
			locationCriteria.Accuracy = Accuracy.Coarse;
			locationCriteria.PowerRequirement = Power.Medium;
			var locationProvider = _locationManager.GetBestProvider(locationCriteria, true);
			if(locationProvider != null)
			{
				_locationManager.RequestLocationUpdates (locationProvider, 500, 1, this);
			}

			var pclApp = App.Portable.App.Instance;
			var setup = new AppSetup () {
				CreateConnectionPool = this.CreateConnnectionPool,
				DbPath = Path.Combine (System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal),"RF12G5td864.db3")
			};
			pclApp.Setup (setup);
			#if DEBUG
			//pclApp.DeleteUser ();
			#endif
			LoadApplication (pclApp);
		}
Beispiel #2
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;
        }
        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);
        }
        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);
                }
            };
        }
		protected override void OnResume ()
		{
			base.OnResume ();

			// Get a handle on the map element
			_mapFragment = FragmentManager.FindFragmentById(Resource.Id.map) as MapFragment;
			_map = _mapFragment.Map;

			// Set the map type 
			_map.MapType = GoogleMap.MapTypeNormal;

			// show user location
			_map.MyLocationEnabled = true;

			// setup a location manager
			_locationManager = GetSystemService(Context.LocationService) as LocationManager;

			// Add points on the map
			MarkerOptions marker1 = new MarkerOptions()
				.SetPosition(Location_Xamarin)
				.SetTitle("Xamarin")
				.InvokeIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueBlue));
			_map.AddMarker(marker1);

			MarkerOptions marker2 = new MarkerOptions()
			    .SetPosition(Location_Atlanta)
			    .SetTitle("Atlanta, GA")
			    .InvokeIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueRed));
			_map.AddMarker(marker2);

			// Add custom marker images on the map
			AddMonkeyMarkersToMap();

			// Add custom arrow callout on map
			AddInitialNewYorkBarToMap();

			// Add custom overlay image on the map
			PositionChicagoGroundOverlay(Location_Chicago);

			// use a generic location provider instead
			Criteria locationCriteria = new Criteria();
			locationCriteria.Accuracy = Accuracy.Coarse;
			locationCriteria.PowerRequirement = Power.Medium;

			var locationProvider = _locationManager.GetBestProvider(locationCriteria, true);
			if (locationProvider != null)
			{
				_locationManager.RequestLocationUpdates(locationProvider, 2000, 1, this);
			} else
			{
				Log.Info("error", "Best provider is not available. Does the device have location services enabled?");
			}

			// TODO: Step 4a - attach map handler for marker touch
//            _map.MarkerClick += MapOnMarkerClick;

			// TODO: Step 4c - attach map handler for info window touch
//			_map.InfoWindowClick += HandleInfoWindowClick;
		}
		/// <summary>
		/// This method activates the Android LocationManager and begins reporting
		/// location changes through our own LocationChanged event.
		/// </summary>
		public void StartLocationUpdates()
		{
			locMgr = Application.Context.GetSystemService("location") as LocationManager;
			if (locMgr == null)
				return;

			var locationCriteria = new Criteria() {
				Accuracy = Accuracy.NoRequirement,
				PowerRequirement = Power.NoRequirement
			};

			var locationProvider = locMgr.GetBestProvider(locationCriteria, true);
			locMgr.RequestLocationUpdates(locationProvider, 2000, 0, this);
		}
 private string GetBestLocationProvider(LocationManager lm)
 {
     Criteria cri = new Criteria();
     cri.Accuracy = Accuracy.Coarse;
     cri.PowerRequirement = Power.Low;
     cri.AltitudeRequired = false;
     cri.BearingAccuracy = Accuracy.Low;
     cri.CostAllowed = false;
     cri.HorizontalAccuracy = Accuracy.Low;
     cri.SpeedAccuracy = Accuracy.Low;
     cri.SpeedRequired = false;
     cri.VerticalAccuracy = Accuracy.Low;
     string pidStr = lm.GetBestProvider(cri, true);
     return pidStr;
 }
Beispiel #8
0
        public void GetLocation()
        {
            _locationManager = Application.Context.GetSystemService(Context.LocationService) as LocationManager;

            var locationCriteria = new Criteria();

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

            var locationProvider = _locationManager.GetBestProvider(locationCriteria, true);

            if (locationProvider != null)
            {
                _locationManager.RequestLocationUpdates(locationProvider, 2000, 1, this);
            }
        }
		public LocListener(LocationManager lm, SensorManager sm) : base()
		{
			// Get LocationManager
			locManager = lm;

			var locationCriteria = new Criteria ()
			{
				Accuracy = global::Android.Locations.Accuracy.Fine,
				AltitudeRequired = true,
				PowerRequirement = Power.Low
			};

			locationProvider = locManager.GetBestProvider(locationCriteria, true);

			if (locationProvider == null)
				throw new Exception("No location provider found");

			List<String> providers = locManager.GetProviders(true) as List<String>;

			// Loop over the array backwards, and if you get an accurate location, then break out the loop
			Location loc = null;

			if (providers != null) {
				for (int i = providers.Count - 1; i >= 0; i--) {
					loc = locManager.GetLastKnownLocation(providers[i]);
					if (loc != null) 
						break;
				}
			}

			if (loc != null)
			{
				lat = loc.Latitude;
				lon = loc.Longitude;
				alt = loc.Altitude;
				accuracy = loc.Accuracy;
			}

			sensorManager = sm;
			accelerometer = sensorManager.GetDefaultSensor(SensorType.Accelerometer);
			magnetometer = sensorManager.GetDefaultSensor(SensorType.MagneticField);
		}
 /// <summary>
 /// Starts the location update.
 /// </summary>
 /// <param name="precision">Précision en mêtre.</param>
 public void StartLocationUpdate(double precision)
 {
     if (GetLocationPermission())
     {
         Precision = precision;
         var accuracy = precision <= 10 ? Accuracy.Fine : Accuracy.Coarse;
         Provider = locationManager.GetBestProvider(new Criteria()
         {
             PowerRequirement = Power.NoRequirement, Accuracy = accuracy
         }, true);
         if (Provider != null)
         {
             locationManager.RequestLocationUpdates(Provider, 1, distanceFilter, this);
         }
         else
         {
             System.Diagnostics.Debug.WriteLine("No provider available. Does the device have location services enabled?");
         }
     }
 }
Beispiel #11
0
        public Task <Location> RequestSingleLocationUpdate()
        {
            var tcs = new TaskCompletionSource <Location>();

            var looper       = Looper.MyLooper() ?? Looper.MainLooper;
            var criteria     = new Criteria();
            var bestProvider = _locationManager.GetBestProvider(criteria, true);

            _locationManager.RequestSingleUpdate(
                bestProvider,
                new SingleLocationListinter(location =>
            {
                var lastLocation  = new Location(location.Latitude, location.Longitude);
                LastKnownLocation = lastLocation;
                tcs.SetResult(lastLocation);
            }),
                looper);

            return(tcs.Task);
        }
        protected override void OnResume ()
        {
            base.OnResume ();

			// Get a handle on the map element
			_mapFragment = FragmentManager.FindFragmentById(Resource.Id.map) as MapFragment;
			_map = _mapFragment.Map;

			#region Show Location
			// TODO: Step 2a - show user location
			 _map.MyLocationEnabled = true;

			_map.UiSettings.MyLocationButtonEnabled = true;
			#endregion

			#region Setup Location Manager

			// TODO: Step 2b - setup a location manager
			 _locationManager = GetSystemService(Context.LocationService) as LocationManager;

			#endregion

			#region Get Location Provider 

			// TODO: Step 2d - use a generic location provider
			Criteria locationCriteria = new Criteria();
			locationCriteria.Accuracy = Accuracy.Coarse;
			locationCriteria.PowerRequirement = Power.Medium;

			var locationProvider = _locationManager.GetBestProvider(locationCriteria, true);
			if (locationProvider != null)
			{
			    _locationManager.RequestLocationUpdates(locationProvider, 2000, 1, this);
			} 

			#endregion

        }
        protected override void PlatformSpecificStart(MvxGeoLocationOptions 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.EnableHighAccuracy ? Accuracy.Fine : Accuracy.Coarse};
            var bestProvider = _locationManager.GetBestProvider(criteria, true);
            if (bestProvider == null)
            {
                MvxTrace.Warning( "Location Service Provider unavailable - returned null");
                SendError(MvxLocationErrorCode.ServiceUnavailable);
                return;
            }
            _locationManager.RequestLocationUpdates(bestProvider, 5000, 2, _locationListener);
            // TODO - Ideally - _geoWatcher.MovementThreshold needed too
        }
        protected override void OnResume ()
        {
            base.OnResume ();

			// Get a handle on the map element
			_mapFragment = FragmentManager.FindFragmentById(Resource.Id.map) as MapFragment;
			_map = _mapFragment.Map;

			 _map.UiSettings.MyLocationButtonEnabled = true;
			 _map.MyLocationEnabled = true;

			 _locationManager = GetSystemService(Context.LocationService) as LocationManager;

//			string Provider = LocationManager.GpsProvider;
//			if(_locationManager.IsProviderEnabled(Provider))
//			{
//			    _locationManager.RequestLocationUpdates (Provider, 2000, 1, this);
//			} 
//			else 
//			{
//			    Log.Info("error", Provider + " is not available. Does the device have location services enabled?");
//			}

			Criteria locationCriteria = new Criteria();
			locationCriteria.Accuracy = Accuracy.Coarse;
			locationCriteria.PowerRequirement = Power.Medium;

			var locationProvider = _locationManager.GetBestProvider(locationCriteria, true);
			if (locationProvider != null)
			{
			    _locationManager.RequestLocationUpdates(locationProvider, 2000, 1, this);
			} 
			else
			{
			    Log.Info("error", "Best provider is not available. Does the device have location services enabled?");
			}
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.location_demo);

            _builder = new StringBuilder();
            _geocoder = new Geocoder(this);
            _locationText = FindViewById<TextView>(Resource.Id.location_text);
            _locationManager = (LocationManager)GetSystemService(LocationService);

            var criteria = new Criteria() { Accuracy = Accuracy.NoRequirement };
            string bestProvider = _locationManager.GetBestProvider(criteria, true);

            Location lastKnownLocation = _locationManager.GetLastKnownLocation(bestProvider);

            if (lastKnownLocation != null)
            {
                _locationText.Text = string.Format("Last known location, lat: {0}, long: {1}",
                                                   lastKnownLocation.Latitude, lastKnownLocation.Longitude);
            }

            _locationManager.RequestLocationUpdates(bestProvider, 5000, 2, this);
        }
Beispiel #16
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";
                }

            };
        }
Beispiel #17
0
        private void InitSensors()
        {
            locationManager = GetSystemService(LocationService) as LocationManager;
            
            if (locationManager != null)
            {
                var provider = locationManager.GetBestProvider(new Criteria(), true);
                locationManager.RequestLocationUpdates(provider, 50, 0, this);
            }

            world.StartSensors();
        }
Beispiel #18
0
        private void InitializeLocationManager()
        {
            _locationManager = (LocationManager)GetSystemService(LocationService);
            var criteriaForLocationService = new Criteria
            {
                Accuracy = Accuracy.Coarse,
                PowerRequirement = Power.Medium
            };

            LocationProvider = _locationManager.GetBestProvider(criteriaForLocationService, true);
            _locationManager.RequestLocationUpdates(LocationProvider, 120000, 5000, this);
        }
Beispiel #19
0
        void InitializeLocationManager()
        {
            _locationManager = (LocationManager)GetSystemService(LocationService);
            var criteriaForLocationService = new Criteria
            {
                Accuracy = Accuracy.Coarse,
                PowerRequirement = Power.Medium
            };

            _locationProvider = _locationManager.GetBestProvider(criteriaForLocationService, true);
        }
		//ON RESUME
		protected override void OnResume ()
		{
			base.OnResume (); 
			Log.Debug (tag, "OnResume called");

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

				var locationCriteria = new Criteria();

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

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

				if(prov=="passive"){
					Log.Debug(tag, "Están deshabilitados los proveedores de ubicación: " + locationProvider.ToString());
					Toast.MakeText (this, "The Network Provider does not exist or is not enabled!", ToastLength.Long).Show ();
				gpsclass.PutString ("latitud", "nogps");
				gpsclass.PutString ("longitud", "nogps");
				}else{
					Log.Debug(tag, "Starting location updates with " + locationProvider.ToString());
					locMgr.RequestLocationUpdates (locationProvider, 2000, 0, this);
				}

			//Last Known Location
			Log.Debug(tag, "Se obtiene la ultima localizacion conocida");

			//locMgr.GetLastKnownLocation(locationProvider)

			try{
			Log.Debug ("LastKnownLocation","Latitud: "+locMgr.GetLastKnownLocation(locationProvider).Latitude+" Longitud: "+locMgr.GetLastKnownLocation(locationProvider).Longitude);
			}catch(NullReferenceException ex){
			Log.Debug ("LastKnownLocation","No hay LastLocation disponible");
			}
		}
Beispiel #21
0
        /// <summary>
        /// Creates the event for the home activity.
        /// Sets layout to home_page, references the Find Nearby Users,
        /// Get Location and Edit Profile button clicks.
        /// </summary>
        /// <param name="bundle">Bundle.</param>
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the home_page resource
            SetContentView(Resource.Layout.home_page);

            // Set context to this activity to be passed to NearbyUsersFragment
            Config.context = this;

            // Get profile object from another activity
            var jsonString = Intent.GetStringExtra("UserProfile");
            userProfile = JsonConvert.DeserializeObject<Profile>(jsonString);

            // Set our view from the home_page resource
            SetContentView(Resource.Layout.home_page);

            // References for Home Menu Items
            mButtonNearbyUsers = FindViewById<Button>(Resource.Id.NearbyUsersButton);
            mButtonUpdateLocation = FindViewById<Button>(Resource.Id.SetLocationButton);
            mButtonSendMessage = FindViewById<Button>(Resource.Id.SendMessageButton);
            mButtonGroupSendMessage = FindViewById<Button>(Resource.Id.btnGroupMessage);
            mTextViewUsername = FindViewById<TextView>(Resource.Id.UsernameTextView);


            // Set username text
            mTextViewUsername.Text = userProfile.username;

            //*** Click Events ***
            // Find Nearby Users Click
            mButtonNearbyUsers.Click += delegate
            {
                StartActivity(typeof(NearbyUsersActivity));
            };

            // Set Current Location Click 
            mButtonUpdateLocation.Click += mButtonSetLocation_Click;

            // Send Message Click
            mButtonSendMessage.Click += MButtonSendMsg_Click;

            //Send Group Message Click
            mButtonGroupSendMessage.Click += MButtonGroupSendMessage_Click;

            // Get the location manager
            locationManager = (LocationManager)GetSystemService(Context.LocationService);

            // Define the criteria how to select the location provider
            Criteria criteria = new Criteria();
            criteria.Accuracy = Accuracy.Fine;
            provider = locationManager.GetBestProvider(criteria, true);
        }
Beispiel #22
0
        public bool Initialise()
        {
            if (_locManager != null)
                return true;

            try
            {
                _locManager = _activity.GetSystemService(Context.LocationService) as LocationManager;
                _geocoder = new Geocoder(_activity);

                var criteria = new Criteria() { Accuracy = Accuracy.NoRequirement };
                string bestProvider = _locManager.GetBestProvider(criteria, true);

                var lastKnownLocation = _locManager.GetLastKnownLocation(bestProvider);

                if (lastKnownLocation != null)
                {
                    OnLocationUpdated(lastKnownLocation);
                }

                _locManager.RequestLocationUpdates(bestProvider, 5000, 2, this);
                _locManager.RequestLocationUpdates("gps", 5000, 2, this);

                return true;
            }
            catch (Exception)
            {
                Toast.MakeText(_activity, Resource.String.error_LocationUnavailable, ToastLength.Long).Show();
                return false;
            }
        }
        private void AcquireCurrentGeoLocation()
        {
            _locationManager = (LocationManager)Application.Context.GetSystemService(Context.LocationService);
            // Get the best location provider
            Criteria locationCriteria = new Criteria();
            locationCriteria.Accuracy = Accuracy.Coarse;
            locationCriteria.PowerRequirement = Power.Medium;
            var locationProvider = _locationManager.GetBestProvider(locationCriteria, true);

            if (locationProvider != null)
            {
                CurrentLocation = _locationManager.GetLastKnownLocation(locationProvider);
            }

            _locationManager.RequestLocationUpdates(locationProvider, 0, 0, _locationListener);
        }
        /// <summary>
        /// Code to the executed when the activity is created
        /// </summary>
        /// <param name="bundle">Any additional data sent to the activity</param>
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Set our view 
			SetContentView (Resource.Layout.message_spinner);

            //Create the spinner for the name of the nearby users
			Spinner spinner = FindViewById<Spinner> (Resource.Id.spinner);
			spinner.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs> (spinner_ItemSelected);

			// Get the location manager
			locationManager = (LocationManager)Config.context.GetSystemService (Context.LocationService);

			// Define the criteria how to select the location provider -> use default
			Criteria criteria = new Criteria ();
			criteria.Accuracy = Accuracy.Fine;
			provider = locationManager.GetBestProvider (criteria, true);
			Location location = locationManager.GetLastKnownLocation (provider);

            //Create a Geolocation object which handles most of the location related functionality, including server calls
			Geolocation currentLocation = new Geolocation (MainActivity.username, location.Latitude, location.Longitude);

            //Get the list of nearby profiles
			Task<List<Profile>> nearbyProfiles = Task<List<Profile>>.Factory.StartNew (() => { 
				return currentLocation.GetNearbyUsers ().Result;
			});

            //Filter the list of profiles, removing the profile for this user, if it was returned by the server
			nearbyUserslist = new List<Profile> ();
			try {
				nearbyUserslist = nearbyProfiles.Result;
				foreach (Profile p in nearbyUserslist) {
					if (p.username.Equals (MainActivity.credentials.username)) {
						nearbyUserslist.Remove (p);
						break;
					}
				}
			} catch (Exception e) {
				string error = e.Message;
				System.Diagnostics.Debug.WriteLine ("\n\nServer offline\n\n" + error);
			}

            //Create an array containing all the usernames of the nearby users
			string[] nearbyUsers = new string[nearbyUserslist.Count];

			for (int i = 0; i < nearbyUserslist.Count; i++) {
				nearbyUsers [i] = nearbyUserslist [i].username;
			}

            //Set up the spinner object to user the array of nearby users
			var adapter = new ArrayAdapter<String> (this, Android.Resource.Layout.SimpleListItemChecked, nearbyUsers);

			adapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
			spinner.Adapter = adapter;

			mMessage = FindViewById<EditText> (Resource.Id.sendMessageTxt);
			mSendMessage = FindViewById<Button> (Resource.Id.btnSendMsg);

			mSendMessage.Click += MSendMessage_Click;
		}
        public override void OnCreate()
        {
            Log.Info("LMService.OnCreate", string.Format("In OnCreate"));
            base.OnCreate();

            _repository = new Repository<GeographicData>(this);

            _sbr = new ServiceBroadcastReceiver();
            _sbr.ReceiveMessage += (context, intent) =>
                                       {
                                           var cType = (AppConstants.ServiceCommandType) intent.GetIntExtra(AppConstants.COMMAND_TYPE_ID, -1);
                                           switch (cType)
                                           {
                                               case AppConstants.ServiceCommandType.SendPing:
                                                   {
                                                       Log.Info("TestService", "Ping received");
                                                       var pongIntent = new Intent(AppConstants.APPLICATION_COMMAND);
                                                       pongIntent.PutExtra(AppConstants.COMMAND_TYPE_ID, (int)AppConstants.ApplicationCommandType.ReceivePong);
                                                       Log.Info("TestService", "Sending pong!");
                                                       SendBroadcast(pongIntent);
                                                       break;
                                                   }
                                               case AppConstants.ServiceCommandType.StopService:
                                                   {
                                                       Log.Info("TestService", "Service stopping...");
                                                       ExportData();
                                                       StopSelf();
                                                       break;
                                                   }
                                               case AppConstants.ServiceCommandType.ExportData:
                                                   {
                                                       ExportData();
                                                       break;
                                                   }
                                               default:
                                                   {
                                                       Log.Info("TestService", "Unknown Command: {0}", cType.ToString());
                                                       break;
                                                   }
                                           }
                                       };

            _notificationManager = (NotificationManager) GetSystemService(Context.NotificationService);
            ShowNotification();
            var criteria = new Criteria
                               {
                                   Accuracy = Accuracy.Fine,
                                   PowerRequirement = Power.Medium,
                                   AltitudeRequired = false,
                                   BearingRequired = false,
                                   SpeedRequired = false,
                                   CostAllowed = false,
                               };
            _locationManager = (LocationManager) GetSystemService(Context.LocationService);

            // !!! Remember to enable the location permissions in the project attributes or _bestProvider comes back null :)
            // you will also need to ensure that the container class either inherits from Service or Activity, or it goes all crashy;
            // but you'll see a build warning about it implementing IJavaObject but not inheriting from Java.Object
            _bestProvider = _locationManager.GetBestProvider(criteria, false);
            // Location _location = _locationManager.GetLastKnownLocation(_bestProvider);
            // at least 15 seconds between updates, at least 100 metres between updates, 'this' because it implements ILocationListener.
            _locationManager.RequestLocationUpdates(_bestProvider, 15000, 100, this);
        }
Beispiel #26
0
		protected override void OnResume ()
		{
			base.OnResume ();
			SetupMapIfNeeded ();
			locMgr = GetSystemService (Context.LocationService) as LocationManager;

			var locationCriteria = new Criteria ();
			locationCriteria.Accuracy = Accuracy.Coarse;
			locationCriteria.PowerRequirement = Power.Medium;
			string locationProvider = locMgr.GetBestProvider (locationCriteria, true);
			Console.WriteLine ("Starting location updates with " + locationProvider.ToString ());
			locMgr.RequestLocationUpdates (locationProvider, 2000, 1, this);
		}
		/// <summary>
		/// Gets the location manager and creates a new Geolocation object with
		/// the user's current location and receives a list from our server
		/// containing all of the nearby users based on that geolocation.
		/// The list is parsed and the profile bios are formatted and placed 
		/// into a string array with the same corresponding index of the string
		/// array of nearby usernames.
		/// </summary>
		/// <param name="savedInstanceState">Bundle.</param>
		public override void OnActivityCreated(Bundle savedInstanceState)
		{
			base.OnActivityCreated(savedInstanceState);

			var ProfileFrame = Activity.FindViewById<View>(Resource.Id.UserProfile);

			// If running on a tablet, then the layout in Resources/Layout-Large will be loaded. 
			// That layout uses fragments, and defines the detailsFrame. We use the visiblity of 
			// detailsFrame as this distinguisher between tablet and phone.
			isDualPane = ProfileFrame != null && ProfileFrame.Visibility == ViewStates.Visible;


			// Get the location manager
			locationManager = (LocationManager) Config.context.GetSystemService(Context.LocationService);
			// Define the criteria how to select the location provider -> use default
			Criteria criteria = new Criteria();
			criteria.Accuracy = Accuracy.Fine;
			provider = locationManager.GetBestProvider(criteria, true);
			Location location = locationManager.GetLastKnownLocation(provider);

            //Create a Geolocation object which handles most of the location related functionality, including server calls
            Geolocation currentLocation = new Geolocation (MainActivity.username, location.Latitude, location.Longitude);

            //Get the list of nearby profiles
            Task<List<Profile>> nearbyProfiles = Task<List<Profile>>.Factory.StartNew(() => 
				{ 
					return currentLocation.GetNearbyUsers().Result;
				});

            //Filter the list of profiles, removing the profile for this user, if it was returned by the server
            nearbyUserslist = new List<Profile>();
			try{
				nearbyUserslist = nearbyProfiles.Result;
				foreach (Profile p in nearbyUserslist){
					if(p.username.Equals(MainActivity.credentials.username)){
						nearbyUserslist.Remove(p);
						break;
					}
				}
			}
			catch(Exception e) {
				string error = e.Message;
				System.Diagnostics.Debug.WriteLine ("\n\nServer offline\n\n" + error);
			}

            //Create the arrays containing the information about the users
			int numUsers = nearbyUserslist.Count;
			string[] nearbyUsers = new string[numUsers];
			nearbyBios = new string[numUsers];

            //Process the information about the nearby users in a formatted string, for display
			for (int i = 0; i < numUsers; i++)
			{
				nearbyUsers [i] = nearbyUserslist [i].username;
				nearbyBios [i] = "⇧ " + nearbyUserslist[i].positive_votes 
					+ "\n⇩ " + nearbyUserslist[i].negative_votes 
					+ "\n\n" + nearbyUserslist [i].gender
					+ "\n\n" + nearbyUserslist [i].bio;
			}
		
            //Set up the adapted to display the list of users
			var adapter = new ArrayAdapter<String>(Activity, Android.Resource.Layout.SimpleListItemChecked, nearbyUsers);
			ListAdapter = adapter;

			if (savedInstanceState != null)
			{
				selectedUserId = savedInstanceState.GetInt("selected_user_id", 0);
			}

			if (isDualPane)
			{
				ListView.ChoiceMode = ChoiceMode.Single;
				ShowProfile(selectedUserId);
			}
		}
 private void InitializeLocationManager()
 {
     _locationManager = (LocationManager)GetSystemService(LocationService);
     var criteriaForLocationService = new Criteria
     {
         Accuracy = Accuracy.Fine
     };
     var acceptableLocationProviders = _locationManager.GetBestProvider(criteriaForLocationService, true);
     _locationProvider = acceptableLocationProviders;
 }
Beispiel #29
0
        //private double currLatitude;
        //private Location currLongitude;
        protected override void OnCreate(Bundle bundle)
        {
            player = MediaPlayer.Create (this,Resource.Raw.police_alarm);
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);

            //_addressText = FindViewById<TextView>(Resource.Id.textView3);
            _latitudeText = FindViewById<TextView>(Resource.Id.txtLatitude);
            _longitudeText = FindViewById<TextView> (Resource.Id.txtLongitude);
            //_timeText = FindViewById<TextView> (Resource.Id.txtSpeed);
            FindViewById<TextView>(Resource.Id.button1).Click += CallPolice_OnClick;
            FindViewById<TextView> (Resource.Id.button2).Click += alarm_click;

            var sendsos = FindViewById<Button> (Resource.Id.button3);
            //correct on click
            sendsos.Click += (sender, e) => {
                if (_latitudeText.Text == "") {
                    _locationManager = (LocationManager)GetSystemService(LocationService);
                    //var status = _locationManager.GetGpsStatus (null).TimeToFirstFix;
                    //Toast.MakeText (this, status, Toas).Show ();
                    var criteriaForLocationService = new Criteria
                    {
                        Accuracy = Accuracy.Fine
                    };
                    string bestProvider = _locationManager.GetBestProvider(criteriaForLocationService, false);
                    //var acceptableLocationProviders = _locationManager.GetProviders (criteriaForLocationService, true);
                    Location l = _locationManager.GetLastKnownLocation (bestProvider);
                    _latitudeText.Text = l.Latitude.ToString ();
                }
                else{

                    SmsManager.Default.SendTextMessage("1234567890", null,"http://maps.google.com/maps?q="+_currentLocation.Latitude+","+_currentLocation.Longitude, null, null);
                    //SmsManager.Default.SendTextMessage(
                }
            };
            FindViewById<TextView> (Resource.Id.button4).Click += cell_loc;

            var sendsosIntent = FindViewById<Button> (Resource.Id.button3);

            sendsosIntent.Click += (sender, e) => {
                double lat=_currentLocation.Latitude;
                double lon=_currentLocation.Longitude;
                string lo="http://maps.google.com/maps?q="+_currentLocation.Latitude+","+_currentLocation.Longitude+"&mode=driving";
                string locationString = @"				http://maps.google.com/maps/api/staticmap?center=" + _currentLocation.Latitude + "," + _currentLocation.Longitude;
                var i=new Intent(Intent.ActionView,Android.Net.Uri.Parse(lo));
                var intent=new Intent(Intent.ActionView,Android.Net.Uri.Parse("http://maps.google.com/maps?q=loc:56.3245,-3.24567"));

                //StartActivity(i);
                var smsUri = Android.Net.Uri.Parse("smsto:1234567890");
                var smsIntent = new Intent (Intent.ActionSendto, smsUri);
                smsIntent.PutExtra("sms_body",lo);
                StartActivity (smsIntent);

                /*					var smsUri1=Android.Net.Uri.Parse("smsto:378437483");
                var url=Android.Net.Uri.Parse(String.Format("http://maps.google.com/maps?q=\"+_currentLocation.Latitude+\",\"+_currentLocation.Longitude"));
                var smsIntent1=new Intent(Intent.ActionSendto,url);
                StartActivity(smsIntent1);*/

                /*var smsUri = Android.Net.Uri.Parse("smsto:1234567890");
                var smsIntent = new Intent (Intent.ActionSendto, smsUri);
                var ValueType=_currentLocation.Latitude*1E6;
                smsIntent.PutExtra("sms_body",ValueType);
                StartActivity (smsIntent);*/
            };

            InitializeLocationManager();
        }
		void InitLocationManager()
		{
			_locationManager = (LocationManager)GetSystemService (LocationService);
			Criteria criteriaForLocation = new Criteria{ Accuracy = Accuracy.Coarse, PowerRequirement = Power.Low };
			string acceptableLocationProviders = _locationManager.GetBestProvider (criteriaForLocation, true);

			if (acceptableLocationProviders.Any ()) {
				_locationProvider = acceptableLocationProviders;

			} else {
				_locationProvider = string.Empty;
			}
			Log.Debug (TAG, "Using " + _locationProvider + ".");
		}
Beispiel #31
0
		//Start the location manager:
		public void InitLocationManager() {
			locationManager = (LocationManager)GetSystemService (LocationService);
			Criteria criteriaForLocationService = new Criteria {
				Accuracy = Accuracy.Fine
			};

			locationProvider = locationManager.GetBestProvider (criteriaForLocationService, true);
			locationManager.GetBestProvider (criteriaForLocationService, true);

		}