Xamarin位置服务OnLocationChanged不会触发

时间:2017-11-14 10:19:07

标签: c# xamarin.android android-gps currentlocation

我们遇到一个问题,就是在某些设备上随机发生,无法触发OnLocationChanged事件。

eval('self.__class__.'+FunctioNameAsString+'()')

我们也尝试设置一个计时器,如果一分钟后事件没有触发,我们将尝试获取最后一个已知位置,但它仍然返回null。

self.__class__.test()

我可能知道我的代码有什么问题吗?

已编辑(完整代码):

LocationManager.RequestLocationUpdates(LocationManager.GpsProvider, 30000, 100, this);
LocationManager.RequestLocationUpdates(LocationManager.NetworkProvider, 30000, 100, this);

1 个答案:

答案 0 :(得分:0)

我建议您检查是否提供了位置服务,我的意思是如果不这样做就会启用这样可以解决问题,如果这些服务不可用或者您可以说当前可以做的是拒绝您只需使用它来检查它是否可用,并以这种方式将您自己的代码应用于它,这可以决定您是否继续前往地图页面。

 public class LocationEnabled : Fragment
{
    public GoogleApiClient googleApiClient;
  //  static int REQUEST_LOCATION = 199;
    public const int MIN_TIME_BW_UPDATES = 1000 * 3;
    public const int REQUEST_CHECK_SETTINGS = 9000;
    AppCompatActivity _activity;
    public LocationEnabled(AppCompatActivity activity)
    {
        _activity = activity;
    }
    private bool hasGPSDevice(Context context)
    {
        LocationManager mgr = (LocationManager)context.GetSystemService(Context.LocationService);
        if (mgr == null)
            return false;
        IList<string> providers = mgr.AllProviders;
        if (providers == null)
            return false;
        return providers.Contains(LocationManager.GpsProvider);
    }
    private async void enableLoc()
    {
        if (googleApiClient == null)
        {
            googleApiClient = new GoogleApiClient.Builder(_activity)
             .AddApi(LocationServices.API)
             .AddConnectionCallbacks(new CallBackHelper(googleApiClient))
             .AddOnConnectionFailedListener(new ConnectionFailedCallBack(_activity)).Build();

            googleApiClient.Connect();

            LocationRequest locationRequest = LocationRequest.Create();
            locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
            locationRequest.SetInterval(MIN_TIME_BW_UPDATES);
            locationRequest.SetFastestInterval(MIN_TIME_BW_UPDATES/2);

            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
              .AddLocationRequest(locationRequest);
            builder.SetAlwaysShow(true);

            LocationSettingsResult locationSettingsResult =
             await LocationServices.SettingsApi.CheckLocationSettingsAsync(googleApiClient, builder.Build());

            switch (locationSettingsResult.Status.StatusCode)
            {
                case LocationSettingsStatusCodes.Success:
                    Toast.MakeText(_activity, "SUCCESS", ToastLength.Short).Show();
                    break;

                case LocationSettingsStatusCodes.ResolutionRequired:
                    try
                    {
                        locationSettingsResult.Status.StartResolutionForResult(_activity, REQUEST_CHECK_SETTINGS);
                    }
                    catch (Exception e)
                    {
                        Toast.MakeText(_activity, "CANCEL: " + e.Message, ToastLength.Short).Show();
                    }
                    break;

                default:
                    googleApiClient.Disconnect();
                    break;
            }
        }
    }

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        LocationManager manager = (LocationManager)_activity.GetSystemService(Context.LocationService);
        if (manager.IsProviderEnabled(LocationManager.GpsProvider) && hasGPSDevice(_activity))
        {
            Intent intent = new Intent(_activity, typeof(GoogleMapsActivity));
            StartActivity(intent);
        }
        if (!hasGPSDevice(_activity))
        {
              Toast.MakeText(_activity, "Gps not Supported", ToastLength.Long).Show();
        }

        if (!manager.IsProviderEnabled(LocationManager.GpsProvider) && hasGPSDevice(_activity))
        {
            enableLoc();              
        }
        else
        {

        }
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        return base.OnCreateView(inflater, container, savedInstanceState);
    }
}
public class ConnectionFailedCallBack : Java.Lang.Object, GoogleApiClient.IOnConnectionFailedListener
{
    Context _context;
    public ConnectionFailedCallBack(Context context)
    {
        _context = context;
    }
    public void OnConnectionFailed(ConnectionResult result)
    {
        Toast.MakeText(_context, "Location connection failed.", ToastLength.Short).Show();
    }
}
public class CallBackHelper : Java.Lang.Object, GoogleApiClient.IConnectionCallbacks
{
    GoogleApiClient googleApiClient;
    public CallBackHelper(GoogleApiClient googleApiClient)
    {
        this.googleApiClient = googleApiClient;
    }
    public void OnConnected(Bundle connectionHint)
    {

    }

    public void OnConnectionSuspended(int cause)
    {
        googleApiClient.Connect();
    }
}

使用以下方法获取片段主机活动的结果:

  protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        if (requestCode == LocationEnabled.REQUEST_CHECK_SETTINGS)
        {
            switch (resultCode)
            {
                case Result.Canceled:
                 //negative result 
                    break;

                case Result.Ok:
               //positive result 
                    break;

                case Result.FirstUser:
                default:
                    break;
            }
        }
    }

古德勒克!