Xamarin在后台服务中获得GPS位置

时间:2016-03-23 08:06:19

标签: android xamarin gps

我正在构建一个应用程序,当它作为后台服务运行时从设备检索位置数据,当它连接到服务器时,它将发送gps数据。问题是应用程序打开时一切正常,当我关闭应用程序时,所有进程都停止工作但应用程序仍然在后台运行。

我使用了此链接https://developer.xamarin.com/guides/android/application_fundamentals/backgrounding/part_3_android_backgrounding_walkthrough/

中的源代码

我只对" LocationService.cs"进行了一些更改。文件。下面是" LocationService.cs"码。我将其用于测试目的。

[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 { };

    List<GpsList> _gpsList = new List<GpsList>();
    public Location lastLocation;

    // 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
    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        Log.Debug(logTag, "LocationService started");
        // start a task here
        new Task(() => {

        }).Start();

        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()
    {
        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 Last Location
        lastLocation = LocMgr.GetLastKnownLocation(locationProvider);

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

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

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

    List<double> distanceList = new List<double>();
    public void OnLocationChanged(Android.Locations.Location location)
    {
        this.LocationChanged(this, new LocationChangedEventArgs(location));
        var distance = location.DistanceTo(lastLocation);

        if (distanceList.Contains(distance) != true)
        {
            distanceList.Add(distance);
        }


        if (distanceList.Count >= 2)
        {
            var latestDistance = distanceList[0] - distanceList[1];
            Log.Debug(logTag, "LatestDistance " + latestDistance);
            distanceList.Clear();

            _gpsList.Add(new GpsList()
            {
                Distance = latestDistance,
                Latitude = location.Latitude,
                Longitude = location.Longitude,
                Altitude = location.Altitude,
                Speed = location.Speed,
                Heading = location.Bearing,
                Date = DateTime.Now.ToString("yy-MM-dd"),
                Time = location.Time.ToString(),
                Valid = true
            });

        }


        Log.Debug(logTag, "Bearing " + location.Bearing);
        Log.Debug(logTag, "Distance " + location.DistanceTo(lastLocation));

        string dbPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        var db = new SQLiteConnection(System.IO.Path.Combine(dbPath, "TrackOne.db"));
        db.CreateTable<GpsLogData>();

        //FOR FILITERING
        if (_gpsList.Count >= 1)
        {
            foreach (var item in _gpsList)
            {
                var logData = new GpsLogData
                {
                    Latitude = item.Latitude,
                    Longitude = item.Longitude,
                    Altitude = item.Altitude,
                    Speed = item.Speed,
                    Heading = item.Heading,
                    Date = item.Date,
                    Time = item.Time,
                    Valid = item.Valid
                };

                db.Insert(logData);
            }

            _gpsList.Clear();

        }

        //CHECK FOR INTERNET
        ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
        NetworkInfo activeConnection = connectivityManager.ActiveNetworkInfo;
        bool isOnline = (activeConnection != null) && activeConnection.IsConnected;

        if (db.Table<GpsLogData>().Count() != 0 && isOnline)
        {
            var table = db.Table<GpsLogData>();

            foreach (var item in table)
            {
                Log.Debug(logTag, "SEND STRING " + item.Id);

                SendGpsString();

                db.Delete<GpsLogData>(item.Id);
                Log.Debug(logTag, "DELETE RECORD " + item.Id);
            }
        }

    }

    public void SendGpsString()
    {
        //TCP SOCKET
        try
        {
            string textToSend = "sample data";

            //---create a TCPClient object at the IP and port no.---
            TcpClient client = new TcpClient("192.168.1.2", 8888);
            NetworkStream nwStream = client.GetStream();
            byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);

            //---send the text---
            //Console.WriteLine("Sending : " + textToSend);
            nwStream.Write(bytesToSend, 0, bytesToSend.Length);

            //---read back the text---
            byte[] bytesToRead = new byte[client.ReceiveBufferSize];
            int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
            //Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
            //Console.ReadLine();
            client.Close();
        }
        catch (Exception ex)
        {
            Log.Info("TrackerX", ex.Message);
        }
        //END TCP SOCKET
    }

    public void OnProviderDisabled(string provider)
    {
        this.ProviderDisabled(this, new ProviderDisabledEventArgs(provider));
    }

    public void OnProviderEnabled(string provider)
    {
        this.ProviderEnabled(this, new ProviderEnabledEventArgs(provider));
    }

    public void OnStatusChanged(string provider, Availability status, Bundle extras)
    {
        this.StatusChanged(this, new StatusChangedEventArgs(provider, status, extras));
    }

}

public class GpsLogData
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public double Distance { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public double Altitude { get; set; }
    public double Speed { get; set; }
    public double Heading { get; set; }
    public string Date { get; set; }
    public string Time { get; set; }
    public bool Valid { get; set; }
}
public class GpsList
{
    public double Distance { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public double Altitude { get; set; }
    public double Speed { get; set; }
    public double Heading { get; set; }
    public string Date { get; set; }
    public string Time { get; set; }
    public bool Valid { get; set; }
}

0 个答案:

没有答案