Windows Phone 8 - Runtime Location API - 2

原文: Windows Phone 8 - Runtime Location API - 2

在<Windows Phone 8 - Runtime Location API - 1>介绍基本的APIs资讯与操作元件,里面介绍面的内谷主要专注

在於App需在前景模式下,如果您希望App是做像常见的,例如:美食导航、慢跑路线、约会地点连结…等,

那麽接下来该篇将讨论如何在背景模式下持续取得座标资讯的能力。

?

[观念]

?WP上的App如果不在前景运作中(例如:开其他程式或按Start键回到桌面),该App是被暂停的;

??? 如果其他App需要更大的Memory被暂停的App可能会被关闭或进入tombstoned的;

??? 参考资料<App activation and deactivation for Windows Phone>。

?WP8允许如果app属於「location-tracking」类型,它被允许在背景模式下持续进行,这个与Background Agent

??? 属於不同的处理机制。

?实作「location-tracking」类型的App,自动支援Fast resume特性。

??? 参考<Fast app resume for Windows Phone 8>或<Windows Phone 8 – Launch Apps与Fast Resume>。

?由於app是执行於行动设备上,电力的考量是最重要的部分,所以在App执行於背景时需要特别注意:

??? a. 最小化次数/数量的网路请求;

??????? =>如果可以的话,应统合所有请求改用批次的方式或是固定时间区间来发出请求。

??? b. 如果使用TimerDispatcherTimer物件只为了更新前景的UI,请不要使用;

??? c. 停止使用所有的XAML动画;

??? d. 如果App并非常时间需要做背景执行,可以搭配PositionChanged与StatusChanged的事件来停止座标追踨;

?

?

[背景可用APIs]

?背景执行的App具有些限制但也有开发一些可用的APIs,

?? 可参考<Features that can be used while running in the background for Windows Phone 8>。

?? 例如:ShellToast、ApplicationModel.Store、Speech.Synthesis、Notification、IsolatedStorage、HttpWebRequest、Sockets…等。

?

?

〉Location-tracking被系统通知Deactivation的条件

??? WP为了维持系统的稳定性,虽允许Location-Tracking类型的App可在背景执行,但具某些条件时系统会通知

Deactivated事件给App加以关闭。Deactivated事件就跟一般应用程式在前景模式收到Deactivated事件相同,这点与

Background Agent是不同的。

?

根据<Running location-tracking apps in the background for Windows Phone 8>中介绍,被通知Deactivated的条件:

?

?App本身停止座标追踪能力。App可在PositionChangedStatusChanged事件搭配GeolocatorGeoCoordinateWatcher

??? 停止持续座标追踪。

?App处於背景执行4个小时,但没有用户加以互动。

?省电模式被启动。

?设备记忆体过低。

?用户关闭了设备的位置服务。

?其他应用程式开始在背景模式执行。

?

这些条件发生後系统触发Deactivated事件,可搭配事件中的Reason参数来加以了解是什麽状态。

在撰写好的App时这些条件最好均要测试,以免在送审过程被退件。

?

?

有了以上的观念後,往下便来看看<How to run location-tracking apps in the background for Windows Phone 8>要怎麽实作吧。

?

A. 在WMAppManifest.xml宣告必要的特性 ID_CAP_LOCATION与设定DefaultTask具有<BackgroundExecution />

????? image

????? 在<DefaultTask />中宣告该App支援Background模式下的任务:

<Tasks>
  <DefaultTask Name="_default" NavigationPage="MainPage.xaml">
    <!-- 宣告为BackgroundExecution,固定的Name = LocationTracking -->
    <BackgroundExecution>
      <ExecutionType Name="LocationTracking" />
    </BackgroundExecution>
  </DefaultTask>
</Tasks>

????? 宣告使用的是<BackgroundExecution />与<BackgroundServiceAgent />二者不同,

????? 并且使用固定的Type Name:LocationTracking

?

?

B. 在App.xaml中覆写 shell:PhoneApplicationService 中的RunningInBackground事件

???? 在一般的App里 shell:PhoneApplicationService仅注册了四个事件:Launching、Closing、Activated与Deactivated。

???? 在此,增加了新的事件处理:RunningInBackground。它主要触发於当App执行於背景模式时。

???? 目前仅开放在location-aware型的App才可以有这样的功能。那麽一来需要将App.xaml修改成如下:

<Application.ApplicationLifetimeObjects>
   <!--Required object that handles lifetime events for the application-->
   <shell:PhoneApplicationService
       Launching="Application_Launching" Closing="Application_Closing"
       Activated="Application_Activated" Deactivated="Application_Deactivated"
       RunningInBackground="Application_RunningInBackground"/>
</Application.ApplicationLifetimeObjects>

?

?

C. 实作最重要的RunningInBackground事件

??? 在App.xaml.cs中宣告二个重要的变数:

??? ?Geolocator:用於同时储存App在前景与背景模式下所取得座标资讯;

??? ?RunningInBackground:用於识别目前处於前景或背景模式下;

???? 有了这二个变数的使用,便在Application_Activated与Application_RunningInBackground分别

???? 设定RunningInBackground的变数值,如下:

private void Application_RunningInBackground(object sender, RunningInBackgroundEventArgs args)
{
    RunningInBackground = true;
    // 当进入背景模式时,要记把相关UI更新或动画全部取消;
}
private void Application_Activated(object sender, ActivatedEventArgs e)
{
    RunningInBackground = false;
    // 回到前景时,则设定关闭背景的执行任务,以节省电力
}

???? 为何不写在Application_Launch呢?因为有可能用户是从暂存区开启程式它就不会经过Launch, 而Activated则不管是第一次开启或

???? 从暂存区返回均可以使用。

?

?

D. 根据范例建立一个Page用於放置当Geolocator取得座标资讯时用於显示座标的画面

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <StackPanel>
        <TextBlock x:Name="LatitudeTextBlock" Text="latitude"/>
        <TextBlock x:Name="LongitudeTextBlock" Text="longitude"/>
    </StackPanel>
</Grid>

?

?

E. 在该Page的OnNavigatedTo时,实例化Geolocator并注册PositionChanged的事件

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
?
    // 实例化宣告於App.xaml的Geolocator
    if (App.Geolocator == null)
    {
        App.Geolocator = 
                new Windows.Devices.Geolocation.Geolocator();
        App.Geolocator.DesiredAccuracy =
                 Windows.Devices.Geolocation.PositionAccuracy.High;
        App.Geolocator.MovementThreshold = 100;
        App.Geolocator.PositionChanged += Geolocator_PositionChanged;
    }
}

?

?

F. 实作在PositionChanged事件下,前景模式更新画面中的资料、背景模式下透过ShellToast通知座标已更新

void Geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
    if (App.RunningInBackground == false)
    {
        //代表处於前景画面可以直接更新画面;
        Dispatcher.BeginInvoke(() =>
        {
            LatitudeTextBlock.Text = args.Position.Coordinate.Latitude.ToString("0.00");
            LongitudeTextBlock.Text = args.Position.Coordinate.Longitude.ToString("0.00");
        });
    }
    else
    {
        //代表处於背景模式,仅能利用ShellToas来通知;
        Microsoft.Phone.Shell.ShellToast toast = new Microsoft.Phone.Shell.ShellToast();
        toast.Content =string.Format("{0},{1}",
            args.Position.Coordinate.Latitude.ToString("0.00"),
            args.Position.Coordinate.Longitude.ToString("0.00"));
        toast.Title = "Location: ";
        toast.NavigationUri = new Uri("/Page2.xaml", UriKind.Relative);
        toast.Show();
    }            
}

?

?

G. 覆写重要的事件PhoneApplicationPage.OnRemovedFromJournal

??? 为什麽需要覆写这样的功能呢?为了就是当我们实作的Page是用於支援LocationTracking时,该页如果被关闭时,

注册於该页撷取Geolocator的事件需要被取消,以免造成不同Thread的Exception问题。而该事件会被呼叫,也代表该

Page已经被呼叫从journal移除掉了,例如:呼叫RemoveBackEntry()事件之後。

protected override void OnRemovedFromJournal(JournalEntryRemovedEventArgs e)
{
    //在该Page被移除之前,先取消注册处理PositionChanged的事件
    App.Geolocator.PositionChanged -= Geolocator_PositionChanged;
    App.Geolocator = null;
?
    base.OnRemovedFromJournal(e);
}

?

?

[执行画面]

444(背景模式)555(前景模式)

测试的方式我是使用Emulator加上Additional Tools一起模拟目前移动的座标位置。相关於如何使用Additional Tool来模拟座标,

可参以下的步骤:

image

?

[范例程式]

======

以上是分享如何实作LocationTracking的App,其中内容主要撷取MSDN上的内容来加以说明,

希望对大家有所帮助。

?

References

?Location for Windows Phone 8

?How to get the phone's current location for Windows Phone 8

?How to continuously track the phone's location for Windows Phone 8

?How to run location-tracking apps in the background for Windows Phone 8 (重要)

?Location Sample for Windows Phone 8

?Location Service Sample

?NET Location API for Windows Phone 8.

?Acquiring a single Geoposition in Windows Phone 8

?Windows Phone 8 and Windows 8 platform comparison

?Using the Location API in Your Windows Phone 8 Applications

?Features that can be used while running in the background for Windows Phone 8

?Fast app resume for Windows Phone 8 (重要)

?App activation and deactivation for Windows Phone (重要)

?Features that can be used while running in the background for Windows Phone 8 (重要)

?Maps in Windows Phone 8 and Phone toolkit: a winning team – Part 1

?Maps in Windows Phone 8 and Phone toolkit: a winning team – Part 2

?

Dotblogs 的标签: Windows Phone

 

enjoy developing application and learning new technology time.


admentorserve.aspx?type=img&z=18&a=11
DotBlogs Tags: Windows Phone

posted on 2014/3/6 01:17 | 我要推荐 | 阅读数 : 131 | 文章分类 [ Windows Phone ] | 订阅

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值