onLocationChanged没有被调用 - Xamarin.Android

时间:2015-07-21 13:19:00

标签: android xamarin geolocation location xamarin.android

下面是一个获取位置的Service类。但onLocationChanged调用bask方法没有被调用。按照here找到的文档进行操作。我的服务开始没有问题,但回调方法没有被调用也没有任何例外。有人可以查看代码并告诉我是否遗漏了某些内容。感谢。

[Service]
    public class LocationService : Service, ILocationListener
    {
        public static LocationManager locMgr;

        [Obsolete ("deprecated")]
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId){

            Console.WriteLine ("LocationService-OnStartCommand");
            locMgr = (LocationManager)GetSystemService(LocationService);
            Criteria criteriaForLocationService = new Criteria
            {
                Accuracy = Accuracy.Fine
            };
            IList<string> acceptableLocationProviders = locMgr.GetProviders(criteriaForLocationService, true);
            string Provider;
            if (acceptableLocationProviders.Any())
            {
                Provider = acceptableLocationProviders.First();
                Console.WriteLine ("LocationService-acceptableLocationProviders.Any()");
            }
            else
            {
                Provider = String.Empty;
                Console.WriteLine ("LocationService-String.Empty");
            }

            if(locMgr.IsProviderEnabled(Provider))
            {
                Console.WriteLine ("LocationService-Provider enabled: "+Provider);
                locMgr.RequestLocationUpdates (Provider, 0, 0, this);
            }
            else
            {
                Console.WriteLine(" Provider is not available. Does the device have location services enabled?");
            }

            return StartCommandResult.Sticky;
        }

        public void OnLocationChanged (Location location)
        {
            Toast.MakeText (Application.Context, "location changed", ToastLength.Short).Show();
            Console.WriteLine ("LocationService-OnLocationChanged");
            Console.WriteLine (""+location.Latitude);
        }

        public void OnProviderDisabled (string provider)
        {
        }

        public void OnProviderEnabled (string provider)
        {
        }

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

        #region implemented abstract members of Service
        public override IBinder OnBind (Intent intent)
        {
            return null;
        }
        #endregion

        public override void OnDestroy ()
        {
            base.OnDestroy ();
            Console.WriteLine ("LocationService-OnDestroy");
            locMgr.RemoveUpdates (this);
        }
    }

1 个答案:

答案 0 :(得分:0)

此处:locMgr.RequestLocationUpdates (Provider, 0, 0, this);

在第二个和第三个参数中放置除0之外的其他东西(分别是最小间隔和更新之间的最小距离)。