歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Windows Phone 8 基於定位的後台應用

Windows Phone 8 基於定位的後台應用

日期:2017/3/1 9:53:50   编辑:Linux編程

後台應用算是 windows phone 8 所特有的一個新功能,說起後台我經常要和地圖一起聊起 【關於地圖的用法請參考:Windows Phone 8 Nokia地圖控件 http://www.linuxidc.com/Linux/2013-08/89011.htm 】今天我著重跟大家聊一下手機定位及基於定位的後台應用,說到定位相信大家已經不再陌生,下載各個平台的只能手機定位 GPS & AGPS 都是一個基本功能很多應用都會用到,但是後台定位應用可能有些同學不他理解,我舉一個“栗子”說,好比我現在開車正在借助一款手機導航軟件尋找某個餐館,此時家裡的那位老大已經到了目的地要檢查一下我到哪了,於是電話響了。。。這時導航軟件必然被切換到後台,相信用過手機導航的同學都有過這樣的經歷,如此場景其他平台也就罷了,在如今windows phone8 是應用支持後台的,那麼這個後台能做什麼呢?簡單的說也就是在此場景下應用可以通過其他形式的提醒方式繼續為用戶提供導航,例如 ShellToast 當然後台能夠使用的API是受限制 但是也足夠用了 API的限制請相信參考MSDN:http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj662941(v=vs.105).aspx

此文是 升級到WP8必需知道的13個特性 系列的一個更新 希望這個系列可以給 Windows Phone 8開發者帶來一些開發上的便利。

升級到WP8必需知道的13個特性 系列文章目錄地址:http://www.linuxidc.com/Linux/2013-08/89003.htm

首先我先給大家介紹如使用定位

使用定位功能當然還是要在Manifest文件中聲明 location 這裡我用的是上一節的Demo 所以也選中了MAP如果你的應用沒有使用地圖控件可以不選MAP,

這裡介紹一下 Geolocator 這個對象使用它來對地理位置進行獲取、初始精度、追蹤狀態等。

        private void TrackLocation_Click_1(object sender, EventArgs e)
        {
            if (!tracking)
            {
                App.Geolocator = new Geolocator();
                App.Geolocator.DesiredAccuracy = PositionAccuracy.High;
                App.Geolocator.MovementThreshold = 2; // The units are meters.

                App.Geolocator.StatusChanged += geolocator_StatusChanged;
                App.Geolocator.PositionChanged += geolocator_PositionChanged;

                tracking = true;
                //TrackLocationButton.Content = "stop tracking";
            }
            else
            {
                App.Geolocator.PositionChanged -= geolocator_PositionChanged;
                App.Geolocator.StatusChanged -= geolocator_StatusChanged;
                App.Geolocator = null;

                tracking = false;

                //TrackLocationButton.Content = "track location";
                StatusTextBlock.Text = "stopped";
            }
        }

下面主要使用了StatusChange 和 PositionChange 時間來進行位置獲取和路徑追蹤。

注釋中可以明確的看到返回的枚舉值都代表著目前是什麼樣的一個狀態,注意這裡包括獲取到用戶在 系統設置中禁用了定位服務(之前有朋友問過我這個問題)

        void geolocator_StatusChanged(Geolocator sender, StatusChangedEventArgs args)
        {
            string status = "";

            switch (args.Status)
            {
                case PositionStatus.Disabled:
                    // the application does not have the right capability or the location master switch is off
                    status = "location is disabled in phone settings";
                    break;
                case PositionStatus.Initializing:
                    // the geolocator started the tracking operation
                    status = "initializing";
                    break;
                case PositionStatus.NoData:
                    // the location service was not able to acquire the location
                    status = "no data";
                    break;
                case PositionStatus.Ready:
                    // the location service is generating geopositions as specified by the tracking parameters
                    status = "ready";
                    break;
                case PositionStatus.NotAvailable:
                    status = "not available";
                    // not used in WindowsPhone, Windows desktop uses this value to signal that there is no hardware capable to acquire location information
                    break;
                case PositionStatus.NotInitialized:
                    // the initial state of the geolocator, once the tracking operation is stopped by the user the geolocator moves back to this state

                    break;
            }

            Dispatcher.BeginInvoke(() =>
            {
                StatusTextBlock.Text = status;
            });

        }

PositionChange 中的代碼是上次講地圖的時候寫的code添加了一個圖層來標記當前位置,當然 args.Position.Coordinate 中的屬性就是我們想得到的經緯度信息了

        void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {
                Dispatcher.BeginInvoke(() =>
                    {
                        if (!MyMap.MapElements.Contains(MPL))
                            MyMap.MapElements.Add(MPL);

                        CurrenLocation = new GeoCoordinate(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude);
                        
                        MPL.Path.Add(CurrenLocation);

                        MyMap.SetView(CurrenLocation, 15, MapAnimationKind.Parabolic);
                        MyMap.Layers.Clear();
                        MapOverlay MyOverlay = new MapOverlay();
                        MyOverlay.Content = GetGrid();
                        MyOverlay.GeoCoordinate = new GeoCoordinate(CurrenLocation.Latitude, CurrenLocation.Longitude);
                        MyOverlay.PositionOrigin = new Point(0, 0.5);
                        MapLayer MyLayer = new MapLayer();
                        MyLayer.Add(MyOverlay);
                        MyMap.Layers.Add(MyLayer);

                    });
        }

其次再給大家介紹如何使應用在後台繼續跟蹤定位

上面我只是實現了一個定位應用和WP7樣的在後台不會繼續工作,接下來我對這個項目稍作修改 讓大家看看怎麼做一個基於定位的後台應用。

首先呢我們需要手動修改Manifest文件,也就是右鍵Manifest文件文本編輯,在Tasks 下 DefaultTask節點中添加 BackgroundExecution節點如下:

    <Tasks>
      <DefaultTask Name="_default" NavigationPage="MainPage.xaml">
        <BackgroundExecution>
          <ExecutionType  Name="LocationTracking" />
        </BackgroundExecution>
      </DefaultTask>
    </Tasks>

之後呢我們打開 項目文件中的 App.xaml 在shell:PhoneApplicationService 中注冊 RuningInBackground 事件用來標記此應用以及跑在後,並且我們聲明兩個靜態屬性 分別是 Geolocator 和 RunningInBackground,作用是在應用程序中共享狀態。

public static Geolocator Geolocator { get; set; }
public static bool RunningInBackground { get; set; }

private void Application_RunningInBackground(object sender, RunningInBackgroundEventArgs args)
{
    RunningInBackground = true;
    // Suspend all unnecessary processing such as UI updates
}

private void Application_Activated(object sender, ActivatedEventArgs e)
{
    RunningInBackground = false;
}

分別在聲明周期的 RunningInBackground 和 Activated 事件中標記應用程序的後台運行情況,細心的同學可能已經發現我在前面聲明 Geolocator 的時候已經是賦值給 App.Geolocator 以確保在後台也可以持續訪問該對象

Copyright © Linux教程網 All Rights Reserved