Xamarin 让我的整个程序在后台运行

Xamarin 让我的整个程序在后台运行,xamarin,gps,Xamarin,Gps,我正在开发一个创建模拟位置的应用程序。现在,在我开始之后——这里一切似乎都正常——然后进入地图,我总是被设置到我实际所在的位置——而不是我的假坐标所在的位置。所以我想,这是因为我的程序在我调试的android手机的后台一推就立即停止了 1) 你也这么说吗? 2) 那么,我如何让我的程序继续模拟这个位置,即使它在后台?我已经设置了计时器,每5秒模拟一个新位置。这是我的主要活动(抱歉,刚好有点长) 任何帮助都会很棒 public static double GlobalLongitude = 0

我正在开发一个创建模拟位置的应用程序。现在,在我开始之后——这里一切似乎都正常——然后进入地图,我总是被设置到我实际所在的位置——而不是我的假坐标所在的位置。所以我想,这是因为我的程序在我调试的android手机的后台一推就立即停止了

1) 你也这么说吗? 2) 那么,我如何让我的程序继续模拟这个位置,即使它在后台?我已经设置了计时器,每5秒模拟一个新位置。这是我的主要活动(抱歉,刚好有点长)

任何帮助都会很棒

  public static double GlobalLongitude = 0.0; // global, cause i need to pull string from void method 
    public static double GlobalLatitude = 0.0;

    static readonly string TAG = "X:" + typeof(Activity1).Name;
    Location _currentLocation;
    LocationManager _locationManager;

    string _locationProvider;
    TextView _locationText;
    static TextView txtAdded;
    static Button btnMain;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        _locationText = FindViewById<TextView>(Resource.Id.GpsTest);
        txtAdded = FindViewById<TextView>(Resource.Id.AddedCoordinates);
        btnMain = FindViewById<Button>(Resource.Id.startbutton);

        CountDown();
        InitializeLocationManager();
    } // start here! :D 

    private void CountDown()
    {

        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = 5000;
        timer.Elapsed += OnTimedEvent;
        timer.Enabled = true;

    }

    private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e) // txt.Added is here!
    {
         txtAdded.Text = SetMockLocation();       
    }

    public void OnLocationChanged(Location location)
    {
        string test = "Null";
        string test2 = "Null";
        bool waitforresult = false;

        _currentLocation = location;
        if (_currentLocation == null)
        {
            _locationText.Text = "Unable to determine your location. Try again in a short while.";
        }
        else
        {
            _locationText.Text = string.Format("Unchanged: {0:f5} {1:f5}", _currentLocation.Latitude, _currentLocation.Longitude);// hh: 53, 10
            //das her wird ausgegeben bei button.click 

            test = string.Format("{0:f5}", _currentLocation.Latitude); // to format 
            test2 = string.Format("{0:f5}", _currentLocation.Longitude);

            double.TryParse(test, out GlobalLatitude);
            double.TryParse(test2, out GlobalLongitude);

            if (test != "Null")
            {
                waitforresult = true;
            }

            if (waitforresult == true)
            {
                Add700ToCoordinates();
            }
        }

    } // ausgabe der koordinaten 

    void InitializeLocationManager()
    {
        _locationManager = (LocationManager)GetSystemService(LocationService);
        Criteria criteriaForLocationService = new Criteria
        {
            Accuracy = Accuracy.Fine
        };
        IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);

        if (acceptableLocationProviders.Any())
        {
            _locationProvider = acceptableLocationProviders.First();
        }
        else
        {
            _locationProvider = string.Empty;
        }
        Log.Debug(TAG, "Using " + _locationProvider + ".");

    }

    protected override void OnResume()
    {
        base.OnResume();
        _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
        Log.Debug(TAG, "Listening for location updates using " + _locationProvider + ".");
    }

    protected override void OnPause()
    {
        base.OnPause();
        _locationManager.RemoveUpdates(this);
        Log.Debug(TAG, "No longer listening for location updates.");
    }

    public static double Add700ToCoordinates()
    {
        string xy = "Null";

        double FinalCoordinates = (GlobalLatitude + 0.01065);

        btnMain.Click += (sender, e) =>
        {

            xy = FinalCoordinates.ToString();
            xy = xy + " " + GlobalLongitude.ToString();

        };

        return FinalCoordinates;
    }

    public static string SetMockLocation()
    {

        var context = Android.App.Application.Context;
        var locationManager = context.GetSystemService(LocationService) as LocationManager;

        locationManager.AddTestProvider("Test09", false, false, false, false, false, false, false, Power.Low, Android.Hardware.SensorStatus.AccuracyHigh);
        locationManager.SetTestProviderEnabled("Test09", true);

        var location = new Location("Test09");
        location.Latitude = Add700ToCoordinates();
        location.Longitude = GlobalLongitude;
        location.Accuracy = 0; // ob das geht?... ja, aber was beduetet es?  
        location.Time = DateTime.Now.Ticks;
        location.ElapsedRealtimeNanos = 100;  // hier das gleiche... was hießt es? :D 
        locationManager.SetTestProviderLocation("Test09", location);

        //Check if your event reacted the right way

        locationManager.RemoveTestProvider("Test09");

        return location.Latitude.ToString();
    }

}
公共静态双GlobalLongitude=0.0;//全局,因为我需要从void方法中提取字符串
公共静态双Globallatude=0.0;
静态只读字符串TAG=“X:”+typeof(Activity1).Name;
位置_当前位置;
LocationManager _LocationManager;
字符串_locationProvider;
text视图_locationText;
增加了静态文本视图;
静态按钮btnMain;
创建时受保护的覆盖无效(捆绑包)
{
base.OnCreate(bundle);
//从“主”布局资源设置视图
SetContentView(Resource.Layout.Main);
_locationText=findviewbyd(Resource.Id.GpsTest);
txtAdded=FindViewById(Resource.Id.AddedCoordinates);
btnMain=findviewbyd(Resource.Id.startbutton);
倒计时();
初始化ElocationManager();
}//从这里开始!:D
私人空间倒计时()
{
System.Timers.Timer Timer=新的System.Timers.Timer();
定时器间隔=5000;
timer.appeased+=OnTimedEvent;
timer.Enabled=true;
}
private void OnTimedEvent(对象发送方,System.Timers.ElapsedEventArgs e)//txt.添加到这里!
{
Text=SetMockLocation();
}
已更改位置上的公共无效(位置)
{
字符串test=“Null”;
字符串test2=“Null”;
bool waitforresult=false;
_当前位置=位置;
如果(_currentLocation==null)
{
_locationText.Text=“无法确定您的位置。请稍后再试。”;
}
其他的
{
_locationText.Text=string.Format(“未更改:{0:f5}{1:f5}”,_currentLocation.Latitude,_currentLocation.Longitude);//hh:53,10
//这是她的第一个Ausgeben bei按钮。单击
test=string.Format(“{0:f5}”,_currentLocation.Latitude);//要格式化
test2=string.Format(“{0:f5}”,_currentLocation.Longitude);
双锥虫(试验,不含全球);
TryParse(测试2,超出全球范围);
如果(测试!=“空”)
{
waitforresult=true;
}
如果(waitforresult==true)
{
添加700ToCoordinates();
}
}
}//ausgabe der Koordien
void InitializeLocationManager()
{
_locationManager=(locationManager)GetSystemService(LocationService);
criteriaForLocationService=新标准
{
准确度=准确度。很好
};
IList acceptableLocationProviders=\u locationManager.GetProviders(criteriaForLocationService,true);
if(acceptableLocationProviders.Any())
{
_locationProvider=acceptableLocationProviders.First();
}
其他的
{
_locationProvider=string.Empty;
}
调试(标记“使用”+_locationProvider+”);
}
受保护的覆盖void OnResume()
{
base.OnResume();
_locationManager.RequestLocationUpdate(\u locationProvider,0,0,this);
Debug(标记“使用“+_locationProvider+”侦听位置更新”);
}
受保护的覆盖void OnPause()
{
base.OnPause();
_locationManager.RemoveUpdate(此);
Debug(标记“不再侦听位置更新”);
}
公共静态双Add700ToCoordinates()
{
字符串xy=“Null”;
双最终坐标=(全球坐标+0.01065);
btnMain.单击+=(发件人,e)=>
{
xy=最终坐标.ToString();
xy=xy+“”+GlobalLongitude.ToString();
};
返回财务坐标;
}
公共静态字符串SetMockLocation()
{
var context=Android.App.Application.context;
var locationManager=context.GetSystemService(LocationService)作为locationManager;
locationManager.AddTestProvider(“Test09”,false,false,false,false,false,Power.Low,Android.Hardware.SensorStatus.AccuracyHigh);
locationManager.SetTestProviderEnabled(“Test09”,true);
var位置=新位置(“Test09”);
位置。纬度=添加700到坐标();
位置。经度=全球经度;
位置。准确度=0;//ob das geht?…是的,aber是beduetet吗?
location.Time=DateTime.Now.Ticks;
location.elapsedrealtimenos=100;//他是谁…他是谁?:D
locationManager.SetTestProviderLocation(“Test09”,位置);
//检查您的活动是否反应正确
locationManager.RemoveTestProvider(“Test09”);
返回location.Latitude.ToString();
}
}

}首先,您需要为每个平台的服务创建本机实现

对于Android:

您需要将您的服务包装到Android服务中,以便在后台工作。请参阅此参考资料

对于iOS:

这有点难。首先阅读此参考资料,特别是“声明应用程序支持的后台任务”部分。() 所以,您可以使用“位置更新”后台模式,并将模拟生成器服务注入“位置更新”服务。 下面是xamarin iOS的示例:

    private void StartAccelerometerUpdates()
    {
        if (_motionManager.AccelerometerAvailable)
            _motionManager.AccelerometerUpdateInterval = ACCEL_UPDATE_INTERVAL;
        _motionManager.StartAccelerometerUpdates (NSOperationQueue.MainQueue, AccelerometerDataUpdatedHandler);
    }

    public void AccelerometerDataUpdatedHandler(CMAccelerometerData data, NSError error)
    { //your mock-generator code }
那里