扩展执行在Windows 10 Universal JavaScript应用中似乎不起作用

迈克·戴洛(Mike Dailor)

我有一个用JavaScript编写的Windows 10 Universal应用程序。该应用程序是一个位置跟踪器,需要在后台运行,我正在尝试使用ExtendedExecution API来实现这一目标。不过,我发现这可以在C#/ XAML应用程序中宣传,但在JavaScript应用程序中则无效。

作为实验,在Visual Studio 2015中,我通过创建了一个新的C#项目,File -> New -> Project -> Visual C# -> Blank App (Universal Windows)并将其设置为如下所示:

/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
    private Geolocator locator;
    private ObservableCollection<string> coordinates = new ObservableCollection<string>();
    private ExtendedExecutionSession session;

    public MainPage()
    {
        this.InitializeComponent();

        // Start geo locating
        locator = new Geolocator();
        locator.DesiredAccuracy = PositionAccuracy.High;
        locator.DesiredAccuracyInMeters = 0;
        locator.MovementThreshold = 0;
        locator.PositionChanged += positionChanged;
        coords.ItemsSource = coordinates;

        // Request extended execution
        RequestExtendedExecution();
    }

    private async void RequestExtendedExecution()
    {

        // Request extended execution via the ExtendedExecution API
        session = new ExtendedExecutionSession();
        session.Description = "Location Tracker";
        session.Reason = ExtendedExecutionReason.LocationTracking;
        session.Revoked += ExtendedExecutionSession_Revoked;
        var result = await session.RequestExtensionAsync();
        if (result == ExtendedExecutionResult.Allowed)
            coordinates.Insert(0, "Extended execution SUCCESS");
        else if (result == ExtendedExecutionResult.Denied)
            coordinates.Insert(0, "Extended execution DENIED");
        else
            coordinates.Insert(0, "Extended execution unexpected return code");
    }

    private async void EndExtendedExecution()
    {
        if (session != null)
        {
            session.Dispose();
            session = null;
        }
    }

    private void ExtendedExecutionSession_Revoked(object sender, ExtendedExecutionRevokedEventArgs args)
    {
        var _ = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
        {
            coordinates.Insert(0, "Extended execution REVOKED: " + ((args.Reason == ExtendedExecutionRevokedReason.Resumed) ? "Resumed" : (args.Reason == ExtendedExecutionRevokedReason.SystemPolicy) ? "Resources" : "Unknown reason"));
        });
        EndExtendedExecution();
    }

    private void positionChanged(Geolocator sender, PositionChangedEventArgs args)
    {
        var coord = args.Position;
        string position = string.Format("{0},{1}",
            args.Position.Coordinate.Point.Position.Latitude,
            args.Position.Coordinate.Point.Position.Longitude);
        var _ = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
        {
            coordinates.Insert(0, position);
        });
    }
}

标记很简单:

<ListView x:Name="coords" />

这绝对可以预期。当我请求扩展会话时,我得到“扩展执行成功”,当最小化应用程序继续将坐标添加到ListView时,当返回到前台时,我得到“扩展执行已撤消:恢复”。超级傻瓜。回到Visual Studio 2015,然后我通过创建了一个新的JavaScript项目File -> New -> Project -> JavaScript -> Blank App (Universal Windows)并实现了相同的功能,如下所示:

(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    var extendedExecution = Windows.ApplicationModel.ExtendedExecution;
    var session = null;
    var geolocator = null;

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {

                // TODO: This application has been newly launched. Initialize your application here.

                // Start geo tracking
                Windows.Devices.Geolocation.Geolocator.requestAccessAsync().done(
                    function (accessStatus) {
                        switch (accessStatus) {
                            case Windows.Devices.Geolocation.GeolocationAccessStatus.allowed:
                                geolocator = new Windows.Devices.Geolocation.Geolocator();
                                geolocator.ReportInterval = 1000;

                                // Subscribe to PositionChanged event to get updated tracking positions
                                geolocator.addEventListener("positionchanged", function (e) {
                                    var coord = e.position.coordinate;
                                    log("app.onactivated: coord = " + coord.point.position.latitude + ", " + coord.point.position.longitude, false, true, false);
                                });
                                break;

                            case Windows.Devices.Geolocation.GeolocationAccessStatus.denied:
                                log("Geolocator.requestAccessAsync: Access to location is denied.", false, true, false);
                                break;

                            case Windows.Devices.Geolocation.GeolocationAccessStatus.unspecified:
                                log("Geolocator.requestAccessAsync: Unspecified error.", false, true, false);
                                break;
                        }
                    },
                    function (err) {
                        log("Geolocator.requestAccessAsync: error " + err, false, true, false);
                    }
                );

                // Request extended execution
                requestExtendedExecution();

            } else {
                // TODO: This application was suspended and then terminated.
                // To create a smooth user experience, restore application state here so that it looks like the app never stopped running.
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state that needs to persist across suspensions here.
        // You might use the WinJS.Application.sessionState object, which is automatically saved and restored across suspension.
        // If you need to complete an asynchronous operation before your application is suspended, call args.setPromise().
        log("app.oncheckpoint: application is about to be suspended");
    };

    function requestExtendedExecution() {

        // If we already have an extended session, close it before requesting a new one.
        if (session != null) {
            session.close();
            session = null;
        }

        // Request extended execution via the ExtendedExecution API
        session = new extendedExecution.ExtendedExecutionSession();
        session.description = "Background location tracking";
        session.reason = extendedExecution.ExtendedExecutionReason.locationTracking;
        session.onrevoked = function (args) {
            log("requestExtendedExecution: Background mode revoked: " + args.reason);
            requestExtendedExecution();
        };
        session.requestExtensionAsync().done(
            function success() {
                log("requestExtendedExecution: Successfully enabled background mode");
            },
            function error(error) {
                log("requestExtendedExecution: Could not enable background mode: " + error);
            }
        );      
    }

    function log (text) {
        var now = new Date();
        var timestamp = now.toLocaleDateString() + " " + now.toLocaleTimeString();
        var outputDiv = document.getElementById("divOutput");
        outputDiv.innerHTML = timestamp + " " + text + "<br/>" + outputDiv.innerHTML;
    }

    app.start();
})();

标记是:

<div id="divOutput"></div>

是的,当我请求扩展会话时,我仍然会得到“扩展执行成功”,但是当我最小化应用程序时,会调用app.oncheckpoint,该应用程序将被挂起,直到返回到前台为止,没有其他活动。我也尝试从app.oncheckpoint内请求扩展会话,但这也没有任何效果。

有人对此有见识吗?提前致谢。

Alan Yao - MSFT

有用。实际的问题是您的代码不监听撤销事件。应该撤消它。:)

并且您的代码中存在一些小问题。

请尝试以下操作:

function requestExtendedExecution() {

    // Request extended execution via the ExtendedExecution API
    session = new extendedExecution.ExtendedExecutionSession();
    session.description = "Background location tracking";
    session.reason = extendedExecution.ExtendedExecutionReason.locationTracking;
    session.onrevoked = function (args) {
        log("requestExtendedExecution: Background mode revoked: " + args.reason);
    };
    session.requestExtensionAsync().done(
        function success() {
            log("requestExtendedExecution: Successfully enabled background mode");
        },
        function error(error) {
            log("requestExtendedExecution: Could not enable background mode: " + error);
        }
    );
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在Windows 10 Universal App中从JavaScript调用C#组件

来自分类Dev

如何在Windows Universal App 10中实现推送通知?

来自分类Dev

列出Windows 10 Universal App中已安装的字体名称

来自分类Dev

如何在Windows Universal App 10中实现推送通知?

来自分类Dev

以编程方式突出显示Universal Windows 10中的ListView元素

来自分类Dev

ScrollView在Windows 10中不起作用

来自分类Dev

在Windows 10 C#UWP Universal Windows应用中获取用户名

来自分类Dev

在Windows 10中共享目标Universal Apps Template10方法

来自分类Dev

在Windows 10 Universal Apps中使用CreateInstance

来自分类Dev

C#Windows Universal 10 TopMost窗口

来自分类Dev

SQLite文件的位置Windows 10 Universal App

来自分类Dev

Windows Universal 10强制下载语言资源

来自分类Dev

VB.net-Openfilepicker在Windows Mobile 10应用程序中不起作用

来自分类Dev

Windows 10中的HTML5 / Javascript Universal Apps使用的浏览器引擎是什么?

来自分类Dev

Windows 10应用程序别名不起作用

来自分类Dev

Windows Universal应用-Windows 10是否没有“任何CPU”配置?

来自分类Dev

在Universal Windows中通过Storyboard设置TextBlock前景不起作用

来自分类Dev

Windows Universal App中的加速度计摇晃事件不起作用

来自分类Dev

如何使用Powershell为Windows 10 Universal应用程序创建桌面快捷方式?

来自分类Dev

如何在Windows 10 Phone的Windows Universal Apps中通过触摸设置拖动?

来自分类Dev

在设备中安装Windows Universal App 8.1(Windows计算机10,8.1)

来自分类Dev

如何获得ListBox ItemTemplate在Windows 10 Universal中水平拉伸ListBox的整个宽度?

来自分类Dev

在Windows 10 Universal App C#中为图像重新着色

来自分类Dev

Windows 10 Universal App中的AWS开发工具包

来自分类Dev

如何在Windows 10 Universal(C#)中不断读取串行端口

来自分类Dev

ScrollIntoView属性不适用于Windows 10 Universal App中的GridView

来自分类Dev

Windows键在Windows 10中不起作用

来自分类Dev

Genymotion在Windows 10 for Android Emulator中不起作用

来自分类Dev

docker命令在PowerShell(Windows 10 Home)中不起作用?

Related 相关文章

  1. 1

    在Windows 10 Universal App中从JavaScript调用C#组件

  2. 2

    如何在Windows Universal App 10中实现推送通知?

  3. 3

    列出Windows 10 Universal App中已安装的字体名称

  4. 4

    如何在Windows Universal App 10中实现推送通知?

  5. 5

    以编程方式突出显示Universal Windows 10中的ListView元素

  6. 6

    ScrollView在Windows 10中不起作用

  7. 7

    在Windows 10 C#UWP Universal Windows应用中获取用户名

  8. 8

    在Windows 10中共享目标Universal Apps Template10方法

  9. 9

    在Windows 10 Universal Apps中使用CreateInstance

  10. 10

    C#Windows Universal 10 TopMost窗口

  11. 11

    SQLite文件的位置Windows 10 Universal App

  12. 12

    Windows Universal 10强制下载语言资源

  13. 13

    VB.net-Openfilepicker在Windows Mobile 10应用程序中不起作用

  14. 14

    Windows 10中的HTML5 / Javascript Universal Apps使用的浏览器引擎是什么?

  15. 15

    Windows 10应用程序别名不起作用

  16. 16

    Windows Universal应用-Windows 10是否没有“任何CPU”配置?

  17. 17

    在Universal Windows中通过Storyboard设置TextBlock前景不起作用

  18. 18

    Windows Universal App中的加速度计摇晃事件不起作用

  19. 19

    如何使用Powershell为Windows 10 Universal应用程序创建桌面快捷方式?

  20. 20

    如何在Windows 10 Phone的Windows Universal Apps中通过触摸设置拖动?

  21. 21

    在设备中安装Windows Universal App 8.1(Windows计算机10,8.1)

  22. 22

    如何获得ListBox ItemTemplate在Windows 10 Universal中水平拉伸ListBox的整个宽度?

  23. 23

    在Windows 10 Universal App C#中为图像重新着色

  24. 24

    Windows 10 Universal App中的AWS开发工具包

  25. 25

    如何在Windows 10 Universal(C#)中不断读取串行端口

  26. 26

    ScrollIntoView属性不适用于Windows 10 Universal App中的GridView

  27. 27

    Windows键在Windows 10中不起作用

  28. 28

    Genymotion在Windows 10 for Android Emulator中不起作用

  29. 29

    docker命令在PowerShell(Windows 10 Home)中不起作用?

热门标签

归档