后台服务位置已更改未触发Xamarin Android

时间:2018-07-02 12:09:32

标签: xamarin xamarin.android

我需要检索设备的实时位置,我已经在我的服务类中实现了ILocationListener,因为我希望即使在应用程序处于后台或关闭状态下也要运行它-this 即使我更改设备位置,对于我来说似乎也不起作用

带有已实现的ILocationListener的我的服务类

 [Service]
public class LocationService : Service, ILocationListener
{
    public event EventHandler<LocationChangedEventArgs> LocationChanged = delegate { };
    public event EventHandler<ProviderDisabledEventArgs> ProviderDisabled = delegate { };
    public event EventHandler<ProviderEnabledEventArgs> ProviderEnabled = delegate { };
    public event EventHandler<StatusChangedEventArgs> StatusChanged = delegate { };

    public LocationService() 
    {
    }

    // Set our location manager as the system location service
    protected LocationManager LocMgr = Android.App.Application.Context.GetSystemService ("location") as LocationManager;

    readonly string logTag = "LocationService";
    IBinder binder;

    public override void OnCreate ()
    {
        base.OnCreate ();
        Log.Debug (logTag, "OnCreate called in the Location Service");
    }

    // This gets called when StartService is called in our App class
    [Obsolete("deprecated in base class")]
    public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId)
    {
        Log.Debug (logTag, "LocationService started");

        return StartCommandResult.Sticky;
    }

    // This gets called once, the first time any client bind to the Service
    // and returns an instance of the LocationServiceBinder. All future clients will
    // reuse the same instance of the binder
    public override IBinder OnBind (Intent intent)
    {
        Log.Debug (logTag, "Client now bound to service");

        binder = new LocationServiceBinder (this);
        return binder;
    }

    // Handle location updates from the location manager
    public void StartLocationUpdates () 
    {
        //we can set different location criteria based on requirements for our app -
        //for example, we might want to preserve power, or get extreme accuracy
        var locationCriteria = new Criteria();

        locationCriteria.Accuracy = Accuracy.NoRequirement;
        locationCriteria.PowerRequirement = Power.NoRequirement;

        // get provider: GPS, Network, etc.
        var locationProvider = LocMgr.GetBestProvider(locationCriteria, true);
        Log.Debug (logTag, string.Format ("You are about to get location updates via {0}", locationProvider));

        // Get an initial fix on location
        LocMgr.RequestLocationUpdates(locationProvider, 2000, 0, this);

        Log.Debug (logTag, "Now sending location updates");
    }

    public override void OnDestroy ()
    {
        base.OnDestroy ();
        Log.Debug (logTag, "Service has been terminated");

        // Stop getting updates from the location manager:
        LocMgr.RemoveUpdates(this);
    }

我的活页夹类

public class LocationServiceBinder : Binder
{
    public LocationService Service
    {
        get { return this.service; }
    } protected LocationService service;

    public bool IsBound { get; set; }

    // constructor
    public LocationServiceBinder (LocationService service)
    {
        this.service = service;
    }
}


public class LocationServiceConnection : Java.Lang.Object, IServiceConnection
{
    public event EventHandler<ServiceConnectedEventArgs> ServiceConnected = delegate {};

    public LocationServiceBinder Binder
    {
        get { return this.binder; }
        set { this.binder = value; }
    }
    protected LocationServiceBinder binder;

    public LocationServiceConnection (LocationServiceBinder binder)
    {
        if (binder != null) {
            this.binder = binder;
        }
    }

    // This gets called when a client tries to bind to the Service with an Intent and an 
    // instance of the ServiceConnection. The system will locate a binder associated with the 
    // running Service 
    public void OnServiceConnected (ComponentName name, IBinder service)
    {
        // cast the binder located by the OS as our local binder subclass
        LocationServiceBinder serviceBinder = service as LocationServiceBinder;
        if (serviceBinder != null) {
            this.binder = serviceBinder;
            this.binder.IsBound = true;
            Log.Debug ( "ServiceConnection", "OnServiceConnected Called" );
            // raise the service connected event
            this.ServiceConnected(this, new ServiceConnectedEventArgs () { Binder = service } );

            // now that the Service is bound, we can start gathering some location data
            serviceBinder.Service.StartLocationUpdates();
        }
    }

    // This will be called when the Service unbinds, or when the app crashes
    public void OnServiceDisconnected (ComponentName name)
    {
        this.binder.IsBound = false;
        Log.Debug ( "ServiceConnection", "Service unbound" );
    }
}



public class ServiceConnectedEventArgs : EventArgs
{
    public IBinder Binder { get; set; }
}

我的MainActivity

public class MainActivity : Activity
{
    readonly string logTag = "MainActivity";

    // make our labels
    TextView latText;
    TextView longText;
    TextView altText;
    TextView speedText;
    TextView bearText;
    TextView accText;

    #region Lifecycle

    //Lifecycle stages
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        Log.Debug (logTag, "OnCreate: Location app is becoming active");

        SetContentView (Resource.Layout.Main);

        // This event fires when the ServiceConnection lets the client (our App class) know that
        // the Service is connected. We use this event to start updating the UI with location
        // updates from the Service
        App.Current.LocationServiceConnected += (object sender, ServiceConnectedEventArgs e) => {
            Log.Debug (logTag, "ServiceConnected Event Raised");
            // notifies us of location changes from the system
            App.Current.LocationService.LocationChanged += HandleLocationChanged;
            //notifies us of user changes to the location provider (ie the user disables or enables GPS)
            App.Current.LocationService.ProviderDisabled += HandleProviderDisabled;
            App.Current.LocationService.ProviderEnabled += HandleProviderEnabled;
            // notifies us of the changing status of a provider (ie GPS no longer available)
            App.Current.LocationService.StatusChanged += HandleStatusChanged;
        };

        latText = FindViewById<TextView> (Resource.Id.lat);
        longText = FindViewById<TextView> (Resource.Id.longx);
        altText = FindViewById<TextView> (Resource.Id.alt);
        speedText = FindViewById<TextView> (Resource.Id.speed);
        bearText = FindViewById<TextView> (Resource.Id.bear);
        accText = FindViewById<TextView> (Resource.Id.acc);

        altText.Text = "altitude";
        speedText.Text = "speed";
        bearText.Text = "bearing";
        accText.Text = "accuracy";

        // Start the location service:
        App.StartLocationService();
    }

    protected override void OnPause()
    {
        Log.Debug (logTag, "OnPause: Location app is moving to background");
        base.OnPause();
    }


    protected override void OnResume()
    {
        Log.Debug (logTag, "OnResume: Location app is moving into foreground");
        base.OnResume();
    }

    protected override void OnDestroy ()
    {
        Log.Debug (logTag, "OnDestroy: Location app is becoming inactive");
        base.OnDestroy ();

        // Stop the location service:
        App.StopLocationService();
    }

    #endregion

    #region Android Location Service methods

    ///<summary>
    /// Updates UI with location data
    /// </summary>
    public void HandleLocationChanged(object sender, LocationChangedEventArgs e)
    {
        Android.Locations.Location location = e.Location;
        Log.Debug (logTag, "Foreground updating");

        // these events are on a background thread, need to update on the UI thread
        RunOnUiThread (() => {
            latText.Text = String.Format ("Latitude: {0}", location.Latitude);
            longText.Text = String.Format ("Longitude: {0}", location.Longitude);
            altText.Text = String.Format ("Altitude: {0}", location.Altitude);
            speedText.Text = String.Format ("Speed: {0}", location.Speed);
            accText.Text = String.Format ("Accuracy: {0}", location.Accuracy);
            bearText.Text = String.Format ("Bearing: {0}", location.Bearing);
        });

    }

    public void HandleProviderDisabled(object sender, ProviderDisabledEventArgs e)
    {
        Log.Debug (logTag, "Location provider disabled event raised");
    }

    public void HandleProviderEnabled(object sender, ProviderEnabledEventArgs e)
    {
        Log.Debug (logTag, "Location provider enabled event raised");
    }

    public void HandleStatusChanged(object sender, StatusChangedEventArgs e)
    {
        Log.Debug (logTag, "Location status changed, event raised");
    }

    #endregion

}

以上public void HandleLocationChanged(object sender, LocationChangedEventArgs e) {} 永远不会因为我的设备位置更改而被解雇

0 个答案:

没有答案