Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当应用程序在UWP中被杀死时,如何运行进程内后台任务?_C#_Uwp_Windows Store Apps_Windows 10_Windows 10 Universal - Fatal编程技术网

C# 当应用程序在UWP中被杀死时,如何运行进程内后台任务?

C# 当应用程序在UWP中被杀死时,如何运行进程内后台任务?,c#,uwp,windows-store-apps,windows-10,windows-10-universal,C#,Uwp,Windows Store Apps,Windows 10,Windows 10 Universal,我希望在应用程序被终止时运行进程内后台任务。这是为了不断跟踪用户的位置变化。不是地理围栏。那么,在UWP中有没有办法做到这一点?以下是我的代码,当应用程序被终止时,它将被终止。在Android(粘性后台服务)和iOS上只需几分钟即可完成此操作。在进程外任务中使用WindowsRuntimeComponent是不可能的,因为我的Xamarin表单PCL中有很多代码可供参考我正在寻找的是Android粘性后台服务。 private async void RegisterBackgroundTask(

我希望在应用程序被终止时运行进程内后台任务。这是为了不断跟踪用户的位置变化。不是地理围栏。那么,在UWP中有没有办法做到这一点?以下是我的代码,当应用程序被终止时,它将被终止。在Android(粘性后台服务)和iOS上只需几分钟即可完成此操作。在进程外任务中使用WindowsRuntimeComponent是不可能的,因为我的Xamarin表单PCL中有很多代码可供参考我正在寻找的是Android粘性后台服务。

private async void RegisterBackgroundTask() 
{
    var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

    if (backgroundAccessStatus == BackgroundAccessStatus.AllowedSubjectToSystemPolicy)
    {
        UnregisterTask(TaskName);
        RegisterTask(TaskName);
    }
}

private async void RegisterTask(string taskName)
{
    BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder
    {
        Name = taskName,
    };

    var trigger = new ApplicationTrigger();
    taskBuilder.SetTrigger(trigger);

    var registration = taskBuilder.Register();
    await trigger.RequestAsync();
}


protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
{
    Debug.WriteLine("Background " + args.TaskInstance.Task.Name + " Starting...");
    SendToast("Hi this is background Task");
    //
    // Query BackgroundWorkCost
    // Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
    // of work in the background task and return immediately.
    //
    var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
    var settings = ApplicationData.Current.LocalSettings;
    settings.Values["BackgroundWorkCost"] = cost.ToString();

    //
    // Associate a cancellation handler with the background task.
    //
    args.TaskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

    //
    // Get the deferral object from the task instance, and take a reference to the taskInstance;
    //
    _deferral = args.TaskInstance.GetDeferral();
    _taskInstance = args.TaskInstance;

    _periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1));
}

private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
    //
    // Indicate that the background task is canceled.
    //
    _cancelRequested = true;
    _cancelReason = reason;

    SendToast("Background " + sender.Task.Name + " Cancel Requested...");
}

private void PeriodicTimerCallback(ThreadPoolTimer timer)
{
    if ((_cancelRequested == false) && (_progress < 100))
    {
        _progress += 10;
        _taskInstance.Progress = _progress;
        SendToast("Timer Went Off!!");
    }
    else
    {
        _periodicTimer.Cancel();

        var key = _taskInstance.Task.Name;

        //
        // Record that this background task ran.
        //
        String taskStatus = (_progress < 100) ? "Canceled with reason: " + _cancelReason.ToString() : "Completed";
        var settings = ApplicationData.Current.LocalSettings;
        settings.Values[key] = taskStatus;
        Debug.WriteLine("Background " + _taskInstance.Task.Name + settings.Values[key]);
        SendToast(taskStatus);
        //
        // Indicate that the background task has completed.
        //
        _deferral.Complete();
    }

}

public static void SendToast(string message)
{
    var template = ToastTemplateType.ToastText01;
    var xml = ToastNotificationManager.GetTemplateContent(template);
    var elements = xml.GetElementsByTagName("text");
    var text = xml.CreateTextNode(message);

    elements[0].AppendChild(text);
    var toast = new ToastNotification(xml);
    ToastNotificationManager.CreateToastNotifier().Show(toast);
}
专用异步无效注册表BackgroundTask()
{
var backgroundAccessStatus=等待BackgroundExecutionManager.RequestAccessAsync();
if(backgroundAccessStatus==backgroundAccessStatus.AllowedSubjectToSystemPolicy)
{
取消注册任务(任务名称);
注册任务(任务名称);
}
}
专用异步无效寄存器任务(字符串taskName)
{
BackgroundTaskBuilder taskBuilder=新建BackgroundTaskBuilder
{
名称=任务名称,
};
var trigger=new ApplicationTrigger();
taskBuilder.SetTrigger(触发器);
var registration=taskBuilder.Register();
wait trigger.RequestAsync();
}
BackgroundActivatedEventArgs(BackgroundActivatedEventArgs)上的受保护覆盖无效
{
Debug.WriteLine(“后台”+args.TaskInstance.Task.Name+“启动…”);
SendToast(“嗨,这是后台任务”);
//
//查询后台工作成本
//指导:如果后台工作成本较高,则只执行最低金额
//在后台任务中完成所有工作并立即返回。
//
var成本=背景工作成本。当前背景工作成本;
var settings=ApplicationData.Current.LocalSettings;
settings.Values[“BackgroundWorkCost”]=cost.ToString();
//
//将取消处理程序与后台任务关联。
//
args.TaskInstance.Cancelled+=新的BackgroundTaskCanceledEventHandler(OnCanceled);
//
//从task实例获取延迟对象,并引用taskInstance;
//
_延迟=args.TaskInstance.getDeleral();
_taskInstance=args.taskInstance;
_periodicTimer=ThreadPoolTimer.CreatePeriodicTimer(新的TimeResolutionHandler(PeriodicTimerCallback),TimeSpan.FromSeconds(1));
}
已取消私有void(IBackgroundTaskInstance发件人,BackgroundTaskCancellationReason)
{
//
//指示后台任务已取消。
//
_取消请求=真;
_取消原因=原因;
SendToast(“背景”+sender.Task.Name+“取消请求…”);
}
私有无效周期TimerCallback(线程池计时器)
{
如果((_cancelRequested==false)和(_progress<100))
{
_进展+=10;
_taskInstance.Progress=\u Progress;
SendToast(“计时器关闭!!”;
}
其他的
{
_periodicTimer.Cancel();
var key=_taskInstance.Task.Name;
//
//记录此后台任务是否已运行。
//
字符串taskStatus=(_progress<100)?“已取消,原因为:”+_cancelReason.ToString():“已完成”;
var settings=ApplicationData.Current.LocalSettings;
设置。值[键]=任务状态;
Debug.WriteLine(“背景”+_taskInstance.Task.Name+设置.Values[key]);
SendToast(任务状态);
//
//指示后台任务已完成。
//
_延迟。完成();
}
}
公共静态void sendtoos(字符串消息)
{
var template=ToastTemplateType.ToastText01;
var xml=ToastNotificationManager.GetTemplateContent(模板);
var elements=xml.GetElementsByTagName(“文本”);
var text=xml.CreateTextNode(消息);
元素[0]。追加子元素(文本);
var toast=新toast通知(xml);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}

为什么要投反对票??这个问题出了什么问题???不是一个反对者,尽管我心里有一个问题-你是在尝试没有运行时组件的背景任务吗?@Romasz是的。我正在尝试实现一个在周年更新中引入的进程内后台任务。您是否尝试在未连接调试器的情况下测试它?是。暂停生命周期事件。工作