2016-04-08 3 views
0

Я создаю собственное приложение для Android с помощью xamarin. Проблема в том, что приложение собирает и отображает координаты отлично на эмуляторе, но когда я помещаю его на смартфон (попробовал 2 телефона samsung), он появляется, и не может определить текущий адрес. Дополнительные данные и данные включены, поэтому я не уверен, где проблема. Спасибо за вашу помощь. вот xammarin рецепт опалубить, который помогает https://developer.xamarin.com/recipes/android/os_device_resources/gps/get_current_device_location/Сбор GPS-совместимых

[Activity(Label = "NewRoute")] 
    public class NewRouteActivity : Activity, ILocationListener 
    { 

     static readonly string TAG = "X:" + typeof(NewRouteActivity).Name; 
     TextView _addressText; 
     Location _currentLocation; 
     LocationManager _locationManager; 

     string _locationProvider; 
     TextView _locationText; 


     public async void OnLocationChanged(Location location) { 
      _currentLocation = location; 
      if (_currentLocation == null) 
      { 
       _locationText.Text = "Unable to determine your location. Try again in a short while."; 
      } 
      else 
      { 
       _locationText.Text = string.Format("{0:f6},{1:f6}", _currentLocation.Latitude, _currentLocation.Longitude); 
       Address address = await ReverseGeocodeCurrentLocation(); 
       DisplayAddress(address); 
      } 
     } 

     public void OnProviderDisabled(string provider) { } 

     public void OnProviderEnabled(string provider) { } 

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

     protected override void OnCreate(Bundle bundle) 
     { 
      base.OnCreate(bundle); 
      SetContentView(Resource.Layout.CreatetRoute); 

      _addressText = FindViewById<TextView>(Resource.Id.address_text); 
      _locationText = FindViewById<TextView>(Resource.Id.location_text); 
      FindViewById<TextView>(Resource.Id.get_address_button).Click += AddressButton_OnClick; 

      InitializeLocationManager(); 


      Button btnEndPoint = FindViewById<Button>(Resource.Id.btnEndPoint); 
      btnEndPoint.Click += new EventHandler(AfterPointsCollected); 
     } 
     //Location Stuff 
     void InitializeLocationManager() 
     { 
      _locationManager = (LocationManager)GetSystemService(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; 
      } 
      Log.Debug(TAG, "Using " + _locationProvider + "."); 
     } 
     //Override OnResume so that Activity1 will begin listening to the LocationManager when the activity comes into the foreground: 
     protected override void OnResume() 
     { 
      base.OnResume(); 
      _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this); 
     } 
     async void AddressButton_OnClick(object sender, EventArgs eventArgs) 
     { 
      if (_currentLocation == null) 
      { 
       _addressText.Text = "Can't determine the current address. Try again in a few minutes."; 
       return; 
      } 

      Address address = await ReverseGeocodeCurrentLocation(); 
      DisplayAddress(address); 
     } 

     async Task<Address> ReverseGeocodeCurrentLocation() 
     { 
      Geocoder geocoder = new Geocoder(this); 
      IList<Address> addressList = 
       await geocoder.GetFromLocationAsync(_currentLocation.Latitude, _currentLocation.Longitude, 10); 

      Address address = addressList.FirstOrDefault(); 
      return address; 
     } 

     void DisplayAddress(Address address) 
     { 
      if (address != null) 
      { 
       StringBuilder deviceAddress = new StringBuilder(); 
       for (int i = 0; i < address.MaxAddressLineIndex; i++) 
       { 
        deviceAddress.AppendLine(address.GetAddressLine(i)); 
       } 
       // Remove the last comma from the end of the address. 
       _addressText.Text = deviceAddress.ToString(); 
      } 
      else 
      { 
       _addressText.Text = "Unable to determine the address. Try again in a few minutes."; 
      } 
     } 

     //Override OnPause and unsubscribe Activity1 from the LocationManager when the activity goes into the background: 
     protected override void OnPause() 
     { 
      base.OnPause(); 
      _locationManager.RemoveUpdates(this); 
     } 
     //Changing Activity 
     void AfterPointsCollected(object sender, EventArgs e) 
     { 
      //context //activity 
      Intent intent = new Intent(this, typeof(AfterPointsCollectedActivity)); 
      //starts the activity with the intent above 
      this.StartActivity(intent); 

     } 
+0

Можете ли вы уточнить, что такое сообщение об ошибке. Предоставьте свой LogCat или скриншоты. Вы пытались отладить это, чтобы определить, где в вашем коде возникает проблема. – buczek

+0

Проблема в том, что нет никакой ошибки, что она отлично работает на эмуляторе, но она просто не работает, когда ее скомпилированная на мобильном устройстве она просто говорит, что каждая вещь имеет значение null, как если бы она не получала gps-координаты, даже если местоположение и данные оба являются причиной, по которой появляются мои сообщения об ошибках. –

+0

На устройствах вы пытались использовать другое приложение, чтобы получить местоположение, например Карты Google. Убедитесь, что ваши устройства правильно получают местоположение для этих приложений. – buczek

ответ

0

Ваши телефоны, вероятно, работает зефира, которые в настоящее время требуют, чтобы вы запрашиваете разрешение на место службы.

Подробнее об этом можно узнать здесь https://blog.xamarin.com/requesting-runtime-permissions-in-android-marshmallow/. Возможно, вы захотите использовать этот пакет Nuget, который обрабатывает все, что для вас. https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/Geolocator