重启后,xamarin.forms android服务运行两次

时间:2017-05-09 17:04:34

标签: xamarin.android xamarin.forms

我有这个代码创建一个Android服务

[Service]
public abstract class LongRunningTaskService : Service
{
    public override IBinder OnBind(Intent intent)
    {
        return null;
    }

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        Logs.Info("service started: " + this.GetType().ToString());

        try
        {
            Tasks.RunTask(() =>
            {
                try
                {
                    Task.run(() => SomeTaskFunction);
                    StopSelf();
                    Logs.Info("service ended successfully from main task");
                }
                catch (Android.OS.OperationCanceledException e)
                {
                    Logs.Warning("Error in Tasks.RunTaskWithoutWaitForResult", e);
                }
            });


            return StartCommandResult.NotSticky;
        }
        catch (Exception e)
        {
            Logs.Warning("error in OnStartCommand", e);
            return StartCommandResult.NotSticky;
        }
    }

    public override void OnDestroy()
    {
        try
        {
            Logs.Info("service destroyed: " + this.GetType().ToString());

            base.OnDestroy();
        }
        catch (Exception e)
        {
            Logs.Warning("Error in service destroyed: " + this.GetType().ToString(), e);
        }
    }
}

当我第一次创建服务时它正常工作,但当我从服务外部销毁服务并使用相同的功能重新创建服务时,同时运行2个任务。

我做错了什么?

0 个答案:

没有答案