我正在尝试整理一个简单的跟踪应用。它所做的只是注册位置更新,而不是每15秒从设备位置发送到webapi(Web服务)服务。以下是执行注册和发布到服务器的代码。
#region START STOP TRACKING
public void StartTracking()
{
if (currentAsset == null) { return; }
isTracking = true;
//SETUP THE LOCATION VARIALBES
if (_geocoder == null) { _geocoder = new Geocoder(this); }
if (_locationManager == null) { _locationManager = (LocationManager)GetSystemService(LocationService); }
var criteria = new Criteria() { Accuracy = Accuracy.Fine };
string bestProvider = _locationManager.GetBestProvider(criteria, true);
Location lastKnownLocation = _locationManager.GetLastKnownLocation(bestProvider);
//LOG RECORD FOR CURRENT LOCATION
if (lastKnownLocation != null)
{
PostData(lastKnownLocation, DateTime.Now);
}
_locationManager.RequestLocationUpdates(bestProvider, 2000, 1, this);
BusTimer.Start();
}
private void OnTimeEvent(object source, ElapsedEventArgs e)
{
RunOnUiThread(delegate
{
var criteria = new Criteria() { Accuracy = Accuracy.Fine };
string bestProvider = _locationManager.GetBestProvider(criteria, true);
Location lastKnownLocation = _locationManager.GetLastKnownLocation(bestProvider);
//LOG RECORD FOR CURRENT LOCATION
if (lastKnownLocation != null)
{
PostData(lastKnownLocation, DateTime.Now);
}
});
}
public void StopTracking()
{
isTracking = false;
_locationManager.RemoveUpdates(this);
BusTimer.Stop();
}
#endregion
#region POST LOCATION DATA TO SERVER
private void PostData(Location setLocation, DateTime setDate)
{
try
{
currentLocation = setLocation;
string longString = string.Format("{0}", setLocation.Longitude);
string latString = string.Format("{0}", setLocation.Latitude);
//POST DATA OVER
var client = new RestClient("http://mywebserver/");
var request = new RestRequest("API/DataAPI/PerformAction", Method.GET);
request.AddParameter("ActionName", "PostEntityData"); // adds to POST or URL querystring based on Method
string JSONString = "{'EntityID':" + currentAsset.AssetID.ToString() + ",'EntityName':'Asset','Long':" + longString + ",'Lat':" + latString + ", 'CheckDateTime':'" + setDate.ToString("yyyy-MM-dd HH:mm:ss") + "'}";
request.AddParameter("ActionData", JSONString); // adds to POST or URL querystring based on Method
client.ExecuteAsync(request, response =>
{
Console.WriteLine(response.Content);
this.RunOnUiThread(new Runnable(PostToastData));
});
}
catch (System.Exception e)
{
Console.Write(e.Message);
}
}
public void PostToastData()
{
string longString = string.Format("{0}", currentLocation.Longitude);
string latString = string.Format("{0}", currentLocation.Latitude);
Toast.MakeText(this, "Logged Location record for " + currentAsset.AssetNumber + " at Long: " + longString + ", Lat: " + latString, ToastLength.Short).Show();
}
#endregion
这一切都很完美。当我最小化应用程序时,它会继续正确地将数据发布到服务中。问题是在大约一个小时后,应用程序意外地死了。
任何人都可以看到在一定时间后它会崩溃的原因吗?该应用程序几乎没有使用任何内存,所以我不认为这将是一个内存问题。我应该在不同的庄园中处理在后台运行的应用程序吗?我应该在不同的线程上执行此过程,以便在应用程序未处于焦点时可以继续在后台执行吗?
任何建议都将受到赞赏。
由于
答案 0 :(得分:2)
如果您想在应用失去焦点后继续在后台运行内容,则应使用后台服务。以下是一些可以帮助您入门的链接: