This commit is contained in:
satyambandarapu 2015-03-30 13:55:18 +03:00
Родитель f8c28c1966
Коммит a1c3fb53c5
19 изменённых файлов: 603 добавлений и 987 удалений

Просмотреть файл

@ -52,22 +52,22 @@ namespace ActivitiesExample
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">Event arguments</param>
async void AboutPage_Loaded(object sender, RoutedEventArgs e)
async void AboutPage_Loaded( object sender, RoutedEventArgs e )
{
string version = "";
var uri = new System.Uri("ms-appx:///AppxManifest.xml");
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);
using (var rastream = await file.OpenReadAsync())
using (var appManifestStream = rastream.AsStreamForRead())
var uri = new System.Uri( "ms-appx:///AppxManifest.xml" );
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync( uri );
using( var rastream = await file.OpenReadAsync() )
using( var appManifestStream = rastream.AsStreamForRead() )
{
using (var reader = XmlReader.Create(appManifestStream, new XmlReaderSettings { IgnoreWhitespace = true, IgnoreComments = true }))
using( var reader = XmlReader.Create( appManifestStream, new XmlReaderSettings { IgnoreWhitespace = true, IgnoreComments = true } ) )
{
var doc = XDocument.Load(reader);
var app = doc.Descendants(doc.Root.Name.Namespace + "Identity").FirstOrDefault();
if (app != null)
var doc = XDocument.Load( reader );
var app = doc.Descendants( doc.Root.Name.Namespace + "Identity" ).FirstOrDefault();
if( app != null )
{
var versionAttribute = app.Attribute("Version");
if (versionAttribute != null)
var versionAttribute = app.Attribute( "Version" );
if( versionAttribute != null )
{
version = versionAttribute.Value;
}

Просмотреть файл

@ -1,55 +0,0 @@
<Page
x:Class="ActivitiesExample.ActivateSensorCore.ActivateSensorCore"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ActivitiesExample.ActivateSensorCore"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="#FF1bA1E2">
<Grid x:Name="LayoutRoot">
<Grid.ChildrenTransitions>
<TransitionCollection>
<EntranceThemeTransition/>
</TransitionCollection>
</Grid.ChildrenTransitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="24,17,0,28" >
<TextBlock x:Uid="ApplicationSuite" Text="_SensorCore Example" Style="{ThemeResource TitleTextBlockStyle}" Typography.Capitals="SmallCaps" Foreground="White"/>
<TextBlock x:Uid="ApplicationName" Text="_activities" Style="{ThemeResource HeaderTextBlockStyle}" Foreground="White"/>
</StackPanel>
<Grid x:Name="MotionDataActivationBox" Grid.Row="1" Visibility="Collapsed" Background="#33000000" Margin="0,0,0,28" VerticalAlignment="Top">
<Grid Margin="10,10,10,10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock x:Uid="/ActivateSensorCore/MotionDataActivationTitle" Grid.Row="0" Foreground="{StaticResource PhoneForegroundBrush}" FontSize="36" />
<TextBlock x:Uid="/ActivateSensorCore/MotionDataActivationExplanation" Grid.Row="1" TextWrapping="Wrap" FontSize="20"/>
<Button x:Uid="/ActivateSensorCore/MotionDataActivationButton" Grid.Row="2" VerticalAlignment="Top" Click="MotionDataActivationButton_Click" HorizontalAlignment="Stretch"/>
<Button x:Uid="/ActivateSensorCore/LaterButton" Grid.Row="3" VerticalAlignment="Top" Click="LaterButton_Click" HorizontalAlignment="Stretch"/>
</Grid>
</Grid>
<Grid x:Name="LocationActivationBox" Grid.Row="1" Visibility="Collapsed" Background="#33000000" Margin="0,0,0,28" VerticalAlignment="Top">
<Grid Margin="10,10,10,10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock x:Uid="/ActivateSensorCore/LocationActivationTitle" Grid.Row="0" Foreground="{StaticResource PhoneForegroundBrush}" FontSize="36" />
<TextBlock x:Uid="/ActivateSensorCore/LocationActivationExplanation" Grid.Row="1" TextWrapping="Wrap" FontSize="20"/>
<Button x:Uid="/ActivateSensorCore/LocationActivationButton" Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Stretch" Click="LocationActivationButton_Click"/>
<Button x:Uid="/ActivateSensorCore/LaterButton" Grid.Row="3" Content="Activate" VerticalAlignment="Top" HorizontalAlignment="Stretch" Click="LaterButton_Click"/>
</Grid>
</Grid>
</Grid>
</Page>

Просмотреть файл

@ -1,197 +0,0 @@
/*
The MIT License (MIT)
Copyright (c) 2015 Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using Lumia.Sense;
using System;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
/// <summary>
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556
/// </summary>
namespace ActivitiesExample.ActivateSensorCore
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class ActivateSensorCore : Page
{
#region Private members
/// <summary>
/// SensorCore status
/// </summary>
private ActivateSensorCoreStatus _sensorCoreActivationStatus;
/// <summary>
/// Display/Hide Dialog for MotionData
/// </summary>
private bool _updatingDialog = false;
#endregion
/// <summary>
/// Constructor
/// </summary>
public ActivateSensorCore()
{
this.InitializeComponent();
var app = Application.Current as ActivitiesExample.App;
_sensorCoreActivationStatus = app.SensorCoreActivationStatus;
}
/// <summary>
/// Check if motion data is enabled
/// </summary>
async Task UpdateDialog()
{
if (_updatingDialog || (_sensorCoreActivationStatus.activationRequestResult != ActivationRequestResults.NotAvailableYet))
{
return;
}
_updatingDialog = true;
MotionDataActivationBox.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
LocationActivationBox.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
Exception failure = null;
try
{
// GetDefaultAsync will throw if MotionData is disabled
ActivityMonitor monitor = await ActivityMonitor.GetDefaultAsync();
// But confirm that MotionData is really enabled by calling ActivateAsync,
// to cover the case where the MotionData has been disabled after the app has been launched.
await monitor.ActivateAsync();
}
catch (Exception exception)
{
switch (SenseHelper.GetSenseError(exception.HResult))
{
case SenseError.LocationDisabled:
LocationActivationBox.Visibility = Windows.UI.Xaml.Visibility.Visible;
break;
case SenseError.SenseDisabled:
MotionDataActivationBox.Visibility = Windows.UI.Xaml.Visibility.Visible;
break;
default:
// Do something clever here
break;
}
failure = exception;
}
if (failure == null)
{
// All is good now, dismiss the dialog.
_sensorCoreActivationStatus.activationRequestResult = ActivationRequestResults.AllEnabled;
this.Frame.GoBack();
}
_updatingDialog = false;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.NavigationMode == NavigationMode.New)
{
Window.Current.VisibilityChanged += Current_VisibilityChanged;
_sensorCoreActivationStatus.onGoing = true;
_sensorCoreActivationStatus.activationRequestResult = ActivationRequestResults.NotAvailableYet;
}
await UpdateDialog();
}
/// <summary>
/// Called when navigating from this page
/// </summary>
/// <param name="e">Event argument.</param>
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
if (e.NavigationMode == NavigationMode.Back)
{
Window.Current.VisibilityChanged -= Current_VisibilityChanged;
}
}
/// <summary>
/// Called when the page is visible or not
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">Event arguments. Contains the arguments returned by the event fired when a CoreWindow instance's visibility changes.</param>
async void Current_VisibilityChanged(object sender, Windows.UI.Core.VisibilityChangedEventArgs e)
{
if (e.Visible)
{
await UpdateDialog();
}
}
/// <summary>
/// Called when later button is clicked
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">Event arguments</param>
private void LaterButton_Click(object sender, RoutedEventArgs e)
{
_sensorCoreActivationStatus.activationRequestResult = ActivationRequestResults.AskMeLater;
Application.Current.Exit();
}
/// <summary>
/// Called when never button is clicked
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">Event arguments</param>
private void NeverButton_Click(object sender, RoutedEventArgs e)
{
_sensorCoreActivationStatus.activationRequestResult = ActivationRequestResults.NoAndDontAskAgain;
this.Frame.GoBack();
}
/// <summary>
/// Called when motion data is activated
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">Event arguments</param>
private async void MotionDataActivationButton_Click(object sender, RoutedEventArgs e)
{
await SenseHelper.LaunchSenseSettingsAsync();
// Although asynchronous, this completes before the user has actually done anything.
// The application will loose control, the system settings will be displayed.
// We will get the control back to our application via a visibilityChanged event.
}
/// <summary>
/// Called when location is activated
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">Event arguments</param>
private async void LocationActivationButton_Click(object sender, RoutedEventArgs e)
{
await SenseHelper.LaunchLocationSettingsAsync();
// Although asynchronous, this completes before the user has actually done anything.
// The application will loose control, the system settings will be displayed.
// We will get the control back to our application via a visibilityChanged event.
}
}
}

Просмотреть файл

@ -1,54 +0,0 @@
/*
The MIT License (MIT)
Copyright (c) 2015 Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ActivitiesExample.ActivateSensorCore
{
/// <summary>
/// Enum to declare the motion data settings status
/// </summary>
public enum ActivationRequestResults
{
AllEnabled,
AskMeLater,
NoAndDontAskAgain,
NotAvailableYet
};
public class ActivateSensorCoreStatus
{
/// <summary>
/// ActivationRequestResults instance
/// </summary>
public ActivationRequestResults activationRequestResult;
/// <summary>
/// Check if the motion data dialog is initialized
/// </summary>
public bool onGoing = false;
}
}

Просмотреть файл

@ -26,12 +26,9 @@ using Windows.ApplicationModel.Activation;
using Windows.Phone.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
using ActivitiesExample.ActivateSensorCore;
/// <summary>
/// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556
/// </summary>
namespace ActivitiesExample
{
/// <summary>
@ -39,27 +36,17 @@ namespace ActivitiesExample
/// </summary>
sealed partial class App : Application
{
#region Private members
/// <summary>
/// Status of SensorCore
/// Transition collection
/// </summary>
private ActivateSensorCoreStatus _sensorCoreActivationStatus = new ActivateSensorCoreStatus();
#endregion
private TransitionCollection transitions;
/// <summary>
/// Gets or sets the status of SensorCore
/// This event wraps HardwareButtons.BackPressed to allow other pages to override
/// the default behavior by subscribing to this event and potentially
/// handling the back button press a different way (e.g. dismissing dialogs).
/// </summary>
public ActivateSensorCoreStatus SensorCoreActivationStatus
{
get
{
return _sensorCoreActivationStatus;
}
private set
{
_sensorCoreActivationStatus = value;
}
}
public event EventHandler<BackPressedEventArgs> BackPressed;
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
@ -69,27 +56,7 @@ namespace ActivitiesExample
{
this.InitializeComponent();
this.Suspending += OnSuspending;
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
/// <summary>
/// Handles back button press. If app is at the root page of app, don't go back and the
/// system will suspend the app.
/// </summary>
/// <param name="sender">The source of the BackPressed event.</param>
/// <param name="e">Details for the BackPressed event.</param>
private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
Frame frame = Window.Current.Content as Frame;
if (frame == null)
{
return;
}
if (frame.CanGoBack)
{
frame.GoBack();
e.Handled = true;
}
HardwareButtons.BackPressed += this.HardwareButtons_BackPressed;
}
/// <summary>
@ -98,50 +65,94 @@ namespace ActivitiesExample
/// search results, and so forth.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
protected override void OnLaunched( LaunchActivatedEventArgs e )
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
if( System.Diagnostics.Debugger.IsAttached )
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
if( rootFrame == null )
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
// Set the default language
rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
rootFrame.CacheSize = 1;
if( e.PreviousExecutionState == ApplicationExecutionState.Terminated )
{
//Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
if( rootFrame.Content == null )
{
// Removes the turnstile navigation for startup.
if( rootFrame.ContentTransitions != null )
{
this.transitions = new TransitionCollection();
foreach( var c in rootFrame.ContentTransitions )
{
this.transitions.Add( c );
}
}
rootFrame.ContentTransitions = null;
rootFrame.Navigated += this.RootFrame_FirstNavigated;
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
if( !rootFrame.Navigate( typeof( MainPage ), e.Arguments ) )
{
throw new Exception( "Failed to create initial page" );
}
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails.
/// Handles the back button press and navigates through the history of the root frame.
/// </summary>
/// <param name="sender">The Frame which failed navigation.</param>
/// <param name="e">Details about the navigation failure.</param>
private void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
/// <param name="sender">The source of the event. <see cref="HardwareButtons"/></param>
/// <param name="e">Details about the back button press.</param>
private void HardwareButtons_BackPressed( object sender, BackPressedEventArgs e )
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
Frame frame = Window.Current.Content as Frame;
if( frame == null )
{
return;
}
var handler = this.BackPressed;
if( handler != null )
{
handler( sender, e );
}
if( frame.CanGoBack && !e.Handled )
{
frame.GoBack();
e.Handled = true;
}
}
/// <summary>
/// Restores the content transitions after the app has launched.
/// </summary>
/// <param name="sender">The object where the handler is attached.</param>
/// <param name="e">Details about the navigation event.</param>
private void RootFrame_FirstNavigated( object sender, NavigationEventArgs e )
{
var rootFrame = sender as Frame;
rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() };
rootFrame.Navigated -= this.RootFrame_FirstNavigated;
}
/// <summary>
@ -151,7 +162,7 @@ namespace ActivitiesExample
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
private void OnSuspending( object sender, SuspendingEventArgs e )
{
var deferral = e.SuspendingOperation.GetDeferral();
//Save application state and stop any background activity

Просмотреть файл

@ -19,7 +19,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
*/
using Lumia.Sense;
using System;
using System.Collections.Generic;
@ -40,7 +40,7 @@ namespace ActivitiesExample.Converters
/// <summary>
/// Constructs a new ResourceLoader object
/// </summary>
private readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView("Resources");
private readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView( "Resources" );
#endregion
/// <summary>
@ -51,37 +51,38 @@ namespace ActivitiesExample.Converters
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object Convert(object value, Type targetType, object parameter, string language)
public object Convert( object value, Type targetType, object parameter, string language )
{
string hint = "";
switch(((string)value).ToLower())
switch( (Activity)value )
{
case "moving":
hint = this._resourceLoader.GetString("Hint/Moving");
case Activity.Moving:
hint = this._resourceLoader.GetString( "Hint/Moving" );
break;
case "idle":
hint = this._resourceLoader.GetString("Hint/Idle");
case Activity.Idle:
hint = this._resourceLoader.GetString( "Hint/Idle" );
break;
case "stationary":
hint = this._resourceLoader.GetString("Hint/Stationary");
case Activity.Stationary:
hint = this._resourceLoader.GetString( "Hint/Stationary" );
break;
case "walking":
hint = this._resourceLoader.GetString("Hint/Walking");
case Activity.Walking:
hint = this._resourceLoader.GetString( "Hint/Walking" );
break;
case "running":
hint = this._resourceLoader.GetString("Hint/Running");
case Activity.Running:
hint = this._resourceLoader.GetString( "Hint/Running" );
break;
case "biking":
hint = this._resourceLoader.GetString("Hint/Biking");
case Activity.Biking:
hint = this._resourceLoader.GetString( "Hint/Biking" );
break;
case "moving in vehicle":
hint = this._resourceLoader.GetString("Hint/MovingInVehicle");
case Activity.MovingInVehicle:
hint = this._resourceLoader.GetString( "Hint/MovingInVehicle" );
break;
case "unknown":
hint = this._resourceLoader.GetString("Hint/Unknown");
case Activity.Unknown:
hint = this._resourceLoader.GetString( "Hint/Unknown" );
break;
default: break;
}
default:
break;
}
return hint;
}
@ -93,7 +94,7 @@ namespace ActivitiesExample.Converters
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object ConvertBack(object value, Type targetType, object parameter, string language)
public object ConvertBack( object value, Type targetType, object parameter, string language )
{
string result = "";
return result;

Просмотреть файл

@ -38,9 +38,9 @@ namespace ActivitiesExample.Converters
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object Convert(object value, Type targetType, object parameter, string language)
public object Convert( object value, Type targetType, object parameter, string language )
{
Uri uri = new Uri("ms-appx:///Assets/Activities/" + ((string)value).ToLower() + ".png", UriKind.Absolute);
Uri uri = new Uri( "ms-appx:///Assets/Activities/" + ( value.ToString() ).ToLower() + ".png", UriKind.Absolute );
return uri;
}
@ -52,7 +52,7 @@ namespace ActivitiesExample.Converters
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object ConvertBack(object value, Type targetType, object parameter, string language)
public object ConvertBack( object value, Type targetType, object parameter, string language )
{
string result = "";
return result;

Просмотреть файл

@ -27,56 +27,57 @@ using Windows.UI.Xaml.Data;
namespace ActivitiesExample.Converters
{
/// <summary>
/// Helper class to convert time window to string
/// Helper class to convert date to display string
/// </summary>
class TimeWindowToString : IValueConverter
class DateToString : IValueConverter
{
#region Private members
/// <summary>
/// Constructs a new ResourceLoader object
/// Resource loader
/// </summary>
private readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView("Resources");
private readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView( "Resources" );
#endregion
/// <summary>
/// Convert activity time window to string
/// Converts date to string
/// </summary>
/// <param name="value">The source data being passed to the target.</param>
/// <param name="targetType">The type of the target property, as a type reference </param>
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object Convert(object value, Type targetType, object parameter, string language)
public object Convert( object value, Type targetType, object parameter, string language )
{
string twString = "";
if ((double)value == 0)
if( (DateTime)value >= DateTime.Today )
{
twString = this._resourceLoader.GetString("TimeWindow/Today");
twString = this._resourceLoader.GetString( "TimeWindow/Today" );
}
else if ((double)value == -1)
else if( (DateTime)value >= (DateTime.Today - TimeSpan.FromDays( 1) ) )
{
twString = this._resourceLoader.GetString("TimeWindow/Yesterday");
twString = this._resourceLoader.GetString( "TimeWindow/Yesterday" );
}
else
{
var sdatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate");
twString = sdatefmt.Format(DateTime.Now.Date.AddDays((double)value));
var sdatefmt = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter( "shortdate" );
twString = sdatefmt.Format( (DateTime)value );
}
return twString;
}
/// <summary>
/// Remove time window string
/// Convert string to time window offset
/// </summary>
/// <param name="value">The source data being passed to the target.</param>
/// <param name="targetType">The type of the target property, as a type reference </param>
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object ConvertBack(object value, Type targetType, object parameter, string language)
public object ConvertBack( object value, Type targetType, object parameter, string language )
{
string result = "";
return result;
throw new NotSupportedException();
}
}
}
// end of file

Просмотреть файл

@ -27,9 +27,9 @@ using Windows.UI.Xaml.Data;
namespace ActivitiesExample.Converters
{
/// <summary>
/// Helper class to convert time span to elipsis
/// Helper class to convert time span to ellipsis
/// </summary>
public class ElipsisVisible : IValueConverter
public class EllipsisVisible : IValueConverter
{
/// <summary>
/// Elipsis added if duration > 12h
@ -39,9 +39,9 @@ namespace ActivitiesExample.Converters
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object Convert(object value, Type targetType, object parameter, string language)
public object Convert( object value, Type targetType, object parameter, string language )
{
return ((TimeSpan)value).TotalMinutes >= 720 ? Visibility.Visible:Visibility.Collapsed;
return ( (TimeSpan)value ).TotalMinutes >= 720 ? Visibility.Visible : Visibility.Collapsed;
}
/// <summary>
@ -52,10 +52,11 @@ namespace ActivitiesExample.Converters
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object ConvertBack(object value, Type targetType, object parameter, string language)
public object ConvertBack( object value, Type targetType, object parameter, string language )
{
string result = "";
return result;
throw new NotSupportedException();
}
}
}
// end of file

Просмотреть файл

@ -38,10 +38,10 @@ namespace ActivitiesExample.Converters
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object Convert(object value, Type targetType, object parameter, string language)
public object Convert( object value, Type targetType, object parameter, string language )
{
string result = "(" + ((TimeSpan)value).ToString(@"hh\:mm") + ")";
return result;
string result = "(" + ( (TimeSpan)value ).ToString( @"hh\:mm" ) + ")";
return result;
}
/// <summary>
@ -52,7 +52,7 @@ namespace ActivitiesExample.Converters
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object ConvertBack(object value, Type targetType, object parameter, string language)
public object ConvertBack( object value, Type targetType, object parameter, string language )
{
string result = "";
return result;

Просмотреть файл

@ -38,12 +38,9 @@ namespace ActivitiesExample.Converters
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object Convert(object value, Type targetType, object parameter, string language)
public object Convert( object value, Type targetType, object parameter, string language )
{
// 320 is an ugly hardcoded value for list width (350) - elipsis column (30)
// would be nice if could be suplied as 'parameter' via a binding to list's ActualWidth
// but ConverterParameter is non-bindable :(
return (320 * ((TimeSpan)value).TotalMinutes) / (12*60);
return ( 375 * ( (TimeSpan)value ).TotalMinutes ) / ( 12 * 60 );
}
/// <summary>
@ -54,7 +51,7 @@ namespace ActivitiesExample.Converters
/// <param name="parameter">An optional parameter to be used in the converter logic.</param>
/// <param name="language">The language of the conversion.</param>
/// <returns>The value to be passed to the target dependency property.</returns>
public object ConvertBack(object value, Type targetType, object parameter, string language)
public object ConvertBack( object value, Type targetType, object parameter, string language )
{
string result = "";
return result;

Просмотреть файл

@ -0,0 +1,190 @@
/*
The MIT License (MIT)
Copyright (c) 2015 Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using Lumia.Sense;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
namespace ActivitiesExample.Data
{
/// <summary>
/// Data class for storing activity data for displaying in UI
/// </summary>
public class ActivityData : INotifyPropertyChanged
{
#region Private members
/// <summary>
/// List of activities and durations
/// </summary>
private List<ActivityDuration> _listData = null;
/// <summary>
/// Current activity
/// </summary>
private Activity _currentActivity = Activity.Idle;
/// <summary>
/// Date of the data set
/// </summary>
private DateTime _date = DateTime.Today;
/// <summary>
/// Singleton instance
/// </summary>
private static ActivityData _selfData;
#endregion
#region Events
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
#endregion
/// <summary>
/// This method is called by the Set accessor of each property.
/// The CallerMemberName attribute that is applied to the optional propertyName
/// parameter causes the property name of the caller to be substituted as an argument.
/// </summary>
/// <param name="propertyName">Name of the property</param>
private void NotifyPropertyChanged( [CallerMemberName] String propertyName = "" )
{
if( PropertyChanged != null )
{
PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
}
}
/// <summary>
/// Constructor
/// </summary>
private ActivityData()
{
_listData = new List<ActivityDuration>();
}
/// <summary>
/// Create new instance of the class
/// </summary>
/// <returns>Data instance</returns>
static public ActivityData Instance()
{
if( _selfData == null )
{
_selfData = new ActivityData();
}
return _selfData;
}
/// <summary>
/// Date of the data
/// </summary>
public DateTime Date
{
get
{
return _date;
}
set
{
_date = value;
NotifyPropertyChanged( "Date" );
}
}
/// <summary>
/// Current activity
/// </summary>
public Activity CurrentActivity
{
get
{
return _currentActivity;
}
set
{
_currentActivity = value;
NotifyPropertyChanged( "CurrentActivity" );
}
}
/// <summary>
/// Summary of activities for a day
/// </summary>
public List<ActivityDuration> History
{
get
{
return _listData;
}
set
{
_listData = value;
NotifyPropertyChanged( "History" );
}
}
}
/// <summary>
/// Class containing activity type and duration
/// </summary>
public class ActivityDuration
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="type">Activity type</param>
/// <param name="duration">Activity duration</param>
public ActivityDuration( Activity type, TimeSpan duration )
{
// Split activity string by capital letter
Duration = duration;
Type = type;
}
/// <summary>
/// Activity name
/// </summary>
public String Name
{
get
{
return System.Text.RegularExpressions.Regex.Replace( Type.ToString(), @"([A-Z])(?<=[a-z]\1|[A-Za-z]\1(?=[a-z]))", " $1" );
}
}
/// <summary>
/// Activity type
/// </summary>
public Activity Type { get; set; }
/// <summary>
/// Activity duration
/// </summary>
public TimeSpan Duration { get; set; }
}
}
// end of file

Просмотреть файл

@ -1,4 +1,5 @@
/*
using Lumia.Sense;
/*
The MIT License (MIT)
Copyright (c) 2015 Microsoft
@ -30,23 +31,18 @@ namespace ActivitiesExample.Data
/// <summary>
/// Data class for design mode
/// </summary>
public class MyDesignData : INotifyPropertyChanged
public class ActivityDesignData : INotifyPropertyChanged
{
#region Private members
/// <summary>
/// List of activities and durations
/// </summary>
private List<MyQuantifiedData> _listData = null;
private List<ActivityDuration> _listData = null;
/// <summary>
/// Design data instance
/// Singleton instance
/// </summary>
private static MyDesignData _selfData;
/// <summary>
/// Time window index, 0 = today, -1 = yesterday
/// </summary>
private double _timeWindowIndex = 0;
private static ActivityDesignData _selfData;
#endregion
/// <summary>
@ -59,31 +55,31 @@ namespace ActivitiesExample.Data
/// The CallerMemberName attribute that is applied to the optional propertyName
/// parameter causes the property name of the caller to be substituted as an argument
/// </summary>
/// <param name="propertyName"></param>
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
/// <param name="propertyName">Name of the property</param>
private void NotifyPropertyChanged( [CallerMemberName] String propertyName = "" )
{
if (PropertyChanged != null)
if( PropertyChanged != null )
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
}
}
/// <summary>
/// Constructor
/// </summary>
public MyDesignData()
public ActivityDesignData()
{
_listData = new List<MyQuantifiedData>();
if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
_listData = new List<ActivityDuration>();
if( Windows.ApplicationModel.DesignMode.DesignModeEnabled )
{
_listData.Add(new MyQuantifiedData("Idle", new TimeSpan(13, 0, 0)));
_listData.Add(new MyQuantifiedData("Moving", new TimeSpan(4, 0, 0)));
_listData.Add(new MyQuantifiedData("Stationary", new TimeSpan(1, 0, 0)));
_listData.Add(new MyQuantifiedData("Walking", new TimeSpan(2, 0, 0)));
_listData.Add(new MyQuantifiedData("Running", new TimeSpan(3, 0, 0)));
_listData.Add(new MyQuantifiedData("Biking", new TimeSpan(5, 0, 0)));
_listData.Add(new MyQuantifiedData("Moving in vehicle", new TimeSpan(1, 0, 0)));
_listData.Add(new MyQuantifiedData("Unknwon", new TimeSpan(1, 0, 0)));
_listData.Add( new ActivityDuration( Activity.Idle, TimeSpan.FromHours( 13 ) ) );
_listData.Add( new ActivityDuration( Activity.Moving, TimeSpan.FromHours( 4 ) ) );
_listData.Add( new ActivityDuration( Activity.Stationary, TimeSpan.FromHours( 1 ) ) );
_listData.Add( new ActivityDuration( Activity.Walking, TimeSpan.FromHours( 2 ) ) );
_listData.Add( new ActivityDuration( Activity.Running, TimeSpan.FromHours( 3 ) ) );
_listData.Add( new ActivityDuration( Activity.Biking, TimeSpan.FromHours( 5 ) ) );
_listData.Add( new ActivityDuration( Activity.MovingInVehicle, TimeSpan.FromHours( 1 ) ) );
_listData.Add( new ActivityDuration( Activity.Unknown, TimeSpan.FromHours( 1 ) ) );
}
}
@ -91,28 +87,30 @@ namespace ActivitiesExample.Data
/// Create new instance of the class
/// </summary>
/// <returns>Design data instance</returns>
static public MyDesignData Instance()
static public ActivityDesignData Instance()
{
if (_selfData == null)
_selfData = new MyDesignData();
if( _selfData == null )
{
_selfData = new ActivityDesignData();
}
return _selfData;
}
/// <summary>
/// Get the current activity
/// </summary>
public string CurrentActivity
public Activity CurrentActivity
{
get
{
return "walking";
return Activity.Walking;
}
}
/// <summary>
/// Get the list of activities and durations
/// </summary>
public List<MyQuantifiedData> ListData
public List<ActivityDuration> History
{
get
{
@ -121,14 +119,13 @@ namespace ActivitiesExample.Data
}
/// <summary>
/// Get the time window
/// Date of the data
/// </summary>
public double TimeWindow
public DateTime Date
{
get
{
return _timeWindowIndex;
}
get { return DateTime.Today; }
}
}
}
}
// end of file

Просмотреть файл

@ -1,312 +0,0 @@
/*
The MIT License (MIT)
Copyright (c) 2015 Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using Lumia.Sense;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
namespace ActivitiesExample.Data
{
/// <summary>
/// Data class for getting users activities
/// </summary>
public class MyData : INotifyPropertyChanged
{
#region Private members
/// <summary>
/// List of activities and durations
/// </summary>
private List<MyQuantifiedData> _listData = null;
/// <summary>
/// Data instance
/// </summary>
private static MyData _selfData;
/// <summary>
/// List of history data
/// </summary>
private IList<ActivityMonitorReading> _historyData;
/// <summary>
/// Activity instance
/// </summary>
private Activity _activityMode = Activity.Idle;
/// <summary>
/// Time window index, 0 = today, -1 = yesterday
/// </summary>
private double _timeWindowIndex = 0;
#endregion
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// This method is called by the Set accessor of each property.
/// The CallerMemberName attribute that is applied to the optional propertyName
/// parameter causes the property name of the caller to be substituted as an argument.
/// </summary>
/// <param name="propertyName"></param>
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// Constructor
/// </summary>
public MyData()
{
_listData = new List<MyQuantifiedData>();
}
/// <summary>
/// Create new instance of the class
/// </summary>
/// <returns>Data instance</returns>
static public MyData Instance()
{
if (_selfData == null)
_selfData = new MyData();
return _selfData;
}
/// <summary>
/// Get the current activity
/// </summary>
public string CurrentActivity
{
get
{
return _activityMode.ToString().ToLower();
}
}
/// <summary>
/// Set the current activity
/// </summary>
public Activity ActivityEnum
{
set
{
_activityMode = value;
NotifyPropertyChanged("CurrentActivity");
}
}
/// <summary>
/// Get the time window
/// </summary>
public double TimeWindow
{
get
{
return _timeWindowIndex;
}
}
/// <summary>
/// Set the time window to today
/// </summary>
public void NextDay()
{
if (_timeWindowIndex < 0)
{
_timeWindowIndex++;
NotifyPropertyChanged("TimeWindow");
}
}
/// <summary>
/// Set the time window to previous day
/// </summary>
public void PreviousDay()
{
if (_timeWindowIndex >= -9)
{
_timeWindowIndex--;
NotifyPropertyChanged("TimeWindow");
}
}
/// <summary>
/// List of activities occured during given time period.
/// </summary>
public IList<ActivityMonitorReading> History
{
get
{
return _historyData;
}
set
{
if (_historyData == null)
{
_historyData = new List<ActivityMonitorReading>();
}
else
{
_historyData.Clear();
}
_historyData = value;
QuantifyData();
}
}
/// <summary>
/// Get the list of activities and durations
/// </summary>
public List<MyQuantifiedData> ListData
{
get
{
return _listData;
}
}
/// <summary>
/// Populate the list of activities and durations to display in the UI
/// </summary>
private void QuantifyData()
{
if (_listData != null)
{
_listData.Clear();
}
_listData = new List<MyQuantifiedData>();
if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled)
{
List<string> _activitiesList = new List<string>(Enum.GetNames(typeof(Activity)));
Dictionary<Activity, int> indexer = new Dictionary<Activity, int>();
TimeSpan[] _durations = new TimeSpan[_activitiesList.Count];
Activity[] values = (Activity[])Enum.GetValues(typeof(Activity));
for (int i = 0; i < values.Length; i++)
{
indexer.Add(values[i], i);
}
// There could be days with no data (e.g. of phone was turned off)
if (_historyData.Count > 0)
{
// First entry may be from previous time window, is there any data from current time window?
bool hasDataInTimeWindow = false;
// Insert new fist entry, representing the last activity of the previous time window
// this helps capture that activity's duration but only from the start of current time window
ActivityMonitorReading first = _historyData[0];
if (first.Timestamp <= DateTime.Now.Date.AddDays(_timeWindowIndex))
{
// Create new "first" entry, with the same mode but timestamp set as 0:00h in current time window
_historyData.Insert(1, new ActivityMonitorReading(first.Mode, DateTime.Now.Date.AddDays(_timeWindowIndex)));
// Remove previous entry
_historyData.RemoveAt(0);
hasDataInTimeWindow = _historyData.Count > 1;
}
else
{
// The first entry belongs to the current time window
// there is no known activity before it
hasDataInTimeWindow = true;
}
// If at least one activity is recorded in this time window
if (hasDataInTimeWindow)
{
// Insert a last activity, marking the begining of the next time window
// this helps capturing the correct duration of the last activity stated in this time window
ActivityMonitorReading last = _historyData.Last();
if (last.Timestamp < DateTime.Now.Date.AddDays(_timeWindowIndex + 1))
{
// Is this today's time window
if (_timeWindowIndex == 0)
{
// Last activity duration measured until this instant time
_historyData.Add(new ActivityMonitorReading(last.Mode, DateTime.Now));
}
else
{
// Last activity measured until the begining of the next time index
_historyData.Add(new ActivityMonitorReading(last.Mode, DateTime.Now.Date.AddDays(_timeWindowIndex + 1)));
}
}
// Calculate duration for each current activity by subtracting its timestamp from that of the next one
for (int i = 0; i < _historyData.Count - 1; i++)
{
ActivityMonitorReading current = _historyData[i];
ActivityMonitorReading next = _historyData[i + 1];
_durations[indexer[current.Mode]] += next.Timestamp - current.Timestamp;
}
}
}
// Populate the list to be displayed in the UI
for (int i = 0; i < _activitiesList.Count; i++)
{
_listData.Add(new MyQuantifiedData(_activitiesList[i], _durations[i]));
}
}
NotifyPropertyChanged("ListData");
}
}
/// <summary>
/// Helper class to create a list of activities and their timestamp
/// </summary>
public class MyQuantifiedData
{
/// <summary>
/// Constructor
/// </summary>
public MyQuantifiedData(string s, TimeSpan i)
{
//Split activity string by capital letter
ActivityName = System.Text.RegularExpressions.Regex.Replace(s, @"([A-Z])(?<=[a-z]\1|[A-Za-z]\1(?=[a-z]))", " $1");
ActivityTime = i;
}
/// <summary>
/// Activity name
/// </summary>
public string ActivityName
{
get;
set;
}
/// <summary>
/// Activity time
/// </summary>
public TimeSpan ActivityTime
{
get;
set;
}
}
}

Просмотреть файл

@ -5,18 +5,18 @@
xmlns:local="using:ActivitiesExample"
xmlns:converters="using:ActivitiesExample.Converters"
xmlns:data="using:ActivitiesExample.Data"
d:DataContext="{Binding Source={d:DesignInstance Type=data:MyDesignData, IsDesignTimeCreatable=True}}"
d:DataContext="{Binding Source={d:DesignInstance Type=data:ActivityDesignData, IsDesignTimeCreatable=True}}"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="#FF1bA1E2">
<Page.Resources>
<converters:ElipsisVisible x:Key="VisibleElipsis"/>
<converters:EllipsisVisible x:Key="VisibleEllipsis"/>
<converters:TimeSpanToString x:Key="TimeToString"/>
<converters:TimeSpanToWidth x:Key="TimeToWidth"/>
<converters:ActivityToImage x:Key="ActivityToIcon"/>
<converters:ActivityToActivityHint x:Key="ActivityToHint"/>
<converters:TimeWindowToString x:Key="TimeWindowToString"/>
<converters:DateToString x:Key="DateToUiString"/>
</Page.Resources>
<Grid>
<Grid.RowDefinitions>
@ -24,7 +24,7 @@
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="24,24,24,0" >
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="24,10,24,0" >
<TextBlock x:Uid="ApplicationSuite" Text="_SensorCore Example" Style="{ThemeResource TitleTextBlockStyle}" Typography.Capitals="SmallCaps" Foreground="White"/>
<TextBlock x:Uid="ApplicationName" Text="_activities" Style="{ThemeResource HeaderTextBlockStyle}" Foreground="White"/>
</StackPanel>
@ -37,15 +37,15 @@
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- current activity text -->
<StackPanel Grid.Row="0" Margin="24,24,0,24" VerticalAlignment="Center" HorizontalAlignment="Left">
<StackPanel Grid.Row="0" Margin="24,14,0,0" VerticalAlignment="Center" HorizontalAlignment="Left">
<TextBlock x:Uid="CurrentActivityHeader" Text="_Current activity:" FontSize="{StaticResource TextStyleMediumFontSize}" VerticalAlignment="Center"/>
<TextBlock Text="{Binding Path=CurrentActivity, Mode=OneWay}" HorizontalAlignment="Left" FontSize="{StaticResource TextStyleExtraLargePlusFontSize}" Margin="12,0,0,0" VerticalAlignment="Center" />
</StackPanel>
<!-- current activity icon -->
<Image Source="{Binding CurrentActivity, Converter={StaticResource ActivityToIcon}}" Grid.Row="2" Height="300" Width="300" Opacity="0.3"/>
<!-- List of activities -->
<TextBlock Text="{Binding Path=TimeWindow, Converter={StaticResource ResourceKey=TimeWindowToString}, Mode=OneWay}" Grid.Row="1" Margin="24,0,0,6" FontSize="{StaticResource TextStyleMediumFontSize}"/>
<ListView x:Name="ActivityListView" Grid.Row="2" Margin="24,0" ItemsSource="{Binding Path=ListData, Mode=OneWay}" Background="#3FFFFFFF" SelectionMode="None" MinHeight="310">
<TextBlock Text="{Binding Path=Date, Converter={StaticResource ResourceKey=DateToUiString}}" Grid.Row="1" Margin="24,0,0,6" FontSize="{StaticResource TextStyleMediumFontSize}"/>
<ListView x:Name="ActivityListView" Grid.Row="2" Margin="24,0" ItemsSource="{Binding Path=History, Mode=OneWay}" Background="#3FFFFFFF" SelectionMode="None" MinHeight="310">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="0" Width="{Binding ActualWidth, ElementName=ActivityListView, Mode=OneWay}">
@ -57,20 +57,20 @@
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<!-- 30px reserved for elipsis -->
<!-- 30px reserved for ellipsis -->
<ColumnDefinition Width="30"/>
</Grid.ColumnDefinitions>
<!-- Activity name and durations -->
<StackPanel Orientation="Horizontal" Grid.Row="1" Margin="12,0,0,0" >
<TextBlock Text="{Binding Path=ActivityName}" FontSize="{StaticResource TextStyleMediumFontSize}" Foreground="White" VerticalAlignment="Center"/>
<TextBlock Text="{Binding Path=ActivityTime, Converter={StaticResource ResourceKey=TimeToString}}" FontSize="{StaticResource TextStyleMediumFontSize}" Foreground="White" Margin="12,0,0,0" VerticalAlignment="Center"/>
<TextBlock Text="{Binding Path=Name}" FontSize="{StaticResource TextStyleMediumFontSize}" Foreground="White" VerticalAlignment="Center"/>
<TextBlock Text="{Binding Path=Duration, Converter={StaticResource ResourceKey=TimeToString}}" FontSize="{StaticResource TextStyleMediumFontSize}" Foreground="White" Margin="12,0,0,0" VerticalAlignment="Center"/>
</StackPanel>
<!-- Activity description -->
<TextBlock Grid.Row="2" Text="{Binding Path=ActivityName, Converter={StaticResource ResourceKey=ActivityToHint}}" FontSize="{StaticResource TextStyleSmallFontSize}" Foreground="White" VerticalAlignment="Center" Margin="12,0,0,0" TextWrapping="Wrap" />
<TextBlock Grid.Row="2" Text="{Binding Path=Type, Converter={StaticResource ResourceKey=ActivityToHint}}" FontSize="{StaticResource TextStyleSmallFontSize}" Foreground="White" VerticalAlignment="Center" Margin="12,0,0,0" TextWrapping="Wrap" />
<!-- Activity duration as a rectangle -->
<Rectangle Grid.Row="3" Margin="0,6,0,0" Grid.Column="0" Width="{Binding Path=ActivityTime, Converter={StaticResource ResourceKey=TimeToWidth}}" Height="6" Fill="White" VerticalAlignment="Top" HorizontalAlignment="Left"/>
<!-- Elipsis added to the end of rectangle if duration > 12h -->
<StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal" Visibility="{Binding ActivityTime, Converter={StaticResource VisibleElipsis}}">
<Rectangle Grid.Row="3" Margin="0,6,0,0" Grid.Column="0" Width="{Binding Path=Duration, Converter={StaticResource ResourceKey=TimeToWidth}}" Height="6" Fill="White" VerticalAlignment="Top" HorizontalAlignment="Left"/>
<!-- Ellipsis added to the end of rectangle if duration > 12h -->
<StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal" Visibility="{Binding Duration, Converter={StaticResource VisibleEllipsis}}">
<Rectangle Margin="6,6,0,0" Width="6" Height="6" Fill="White" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Rectangle Margin="6,6,0,0" Width="6" Height="6" Fill="White" HorizontalAlignment="Right" VerticalAlignment="Top"/>
</StackPanel>

Просмотреть файл

@ -31,13 +31,9 @@ using Lumia.Sense;
using System.Diagnostics;
using ActivitiesExample.Data;
using Windows.Security.ExchangeActiveSyncProvisioning;
using Lumia.Sense.Testing;
using Windows.ApplicationModel.Resources;
using ActivitiesExample.ActivateSensorCore;
using System.Collections.Generic;
/// <summary>
/// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556
/// </summary>
namespace ActivitiesExample
{
/// <summary>
@ -59,11 +55,12 @@ namespace ActivitiesExample
/// <summary>
/// Constructs a new ResourceLoader object
/// </summary>
private readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView("Resources");
private readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView( "Resources" );
/// The application model
/// <summary>
/// Day offset from day, i.e. 0 = today, 1 = yesterday etc.
/// </summary>
private ActivitiesExample.App _app = Application.Current as ActivitiesExample.App;
private uint _dayOffset = 0;
#endregion
/// <summary>
@ -72,44 +69,86 @@ namespace ActivitiesExample
public MainPage()
{
InitializeComponent();
DataContext = MyData.Instance();
Loaded += MainPage_Loaded;
//Using this method to detect if the application runs in the emulator or on a real device. Later the *Simulator API is used to read fake sense data on emulator.
//In production code you do not need this and in fact you should ensure that you do not include the Lumia.Sense.Test reference in your project.
this.NavigationCacheMode = NavigationCacheMode.Required;
DataContext = ActivityData.Instance();
// Using this method to detect if the application runs in the emulator or on a real device. Later the *Simulator API is used to read fake sense data on emulator.
// In production code you do not need this and in fact you should ensure that you do not include the Lumia.Sense.Test reference in your project.
EasClientDeviceInformation x = new EasClientDeviceInformation();
if (x.SystemProductName.StartsWith("Virtual"))
if( x.SystemProductName.StartsWith( "Virtual" ) )
{
_runningInEmulator = true;
}
Window.Current.VisibilityChanged += async ( sender, args ) =>
{
await CallSensorCoreApiAsync( async () =>
{
if( !args.Visible )
{
// Application put to background, deactivate sensor and unregister change observer
if( _activityMonitor != null )
{
_activityMonitor.Enabled = true;
_activityMonitor.ReadingChanged -= activityMonitor_ReadingChanged;
await _activityMonitor.DeactivateAsync();
}
}
else
{
// Make sure all necessary settings are enabled in order to run SensorCore
await ValidateSettingsAsync();
// Make sure sensor is activated
if( _activityMonitor == null )
{
await InitializeSensorAsync();
}
else
{
await _activityMonitor.ActivateAsync();
}
// Enable change observer
_activityMonitor.ReadingChanged += activityMonitor_ReadingChanged;
_activityMonitor.Enabled = true;
// Update screen
await UpdateSummaryAsync();
}
} );
};
}
/// <summary>
/// Loaded event raised after the component is initialized
/// Initializes activity monitor sensor
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">Event argument</param>
async void MainPage_Loaded(object sender, RoutedEventArgs e)
/// <returns>Asynchronous task</returns>
private async Task InitializeSensorAsync()
{
if (!_runningInEmulator && !await ActivityMonitor.IsSupportedAsync())
if( _runningInEmulator )
{
// await CallSensorCoreApiAsync( async () => { _activityMonitor = await ActivityMonitorSimulator.GetDefaultAsync(); } );
}
else
{
await CallSensorCoreApiAsync( async () => { _activityMonitor = await ActivityMonitor.GetDefaultAsync(); } );
}
if( _activityMonitor == null )
{
// Nothing to do if we cannot use the API
// In a real app please do make an effort to create a better user experience.
// e.g. if access to Activity Monitor is not mission critical, let the app run without showing any error message
// simply hide the features that depend on it
MessageDialog md = new MessageDialog(this._resourceLoader.GetString("FeatureNotSupported/Message"), this._resourceLoader.GetString("FeatureNotSupported/Title"));
await md.ShowAsync();
Application.Current.Exit();
}
}
/// <summary>
/// Initializes activity monitor
/// Makes sure necessary settings are enabled in order to use SensorCore
/// </summary>
private async void Initialize()
/// <returns>Asynchronous task</returns>
private async Task ValidateSettingsAsync()
{
if (!(await ActivityMonitor.IsSupportedAsync()))
if( !( await ActivityMonitor.IsSupportedAsync() ) )
{
MessageDialog dlg = new MessageDialog("Unfortunately this device does not support activities.");
MessageDialog dlg = new MessageDialog( this._resourceLoader.GetString( "FeatureNotSupported/Message" ), this._resourceLoader.GetString( "FeatureNotSupported/Title" ) );
await dlg.ShowAsync();
Application.Current.Exit();
}
@ -117,101 +156,42 @@ namespace ActivitiesExample
{
uint apiSet = await SenseHelper.GetSupportedApiSetAsync();
MotionDataSettings settings = await SenseHelper.GetSettingsAsync();
// Devices with old location settings
if (settings.Version < 2 && !settings.LocationEnabled)
if( settings.Version < 2 )
{
MessageDialog dlg = new MessageDialog("In order to recognize activities you need to enable location in system settings. Do you want to open settings now? if no, applicatoin will exit", "Information");
dlg.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(async (cmd) => await SenseHelper.LaunchLocationSettingsAsync())));
dlg.Commands.Add(new UICommand("No", new UICommandInvokedHandler((cmd) =>{ Application.Current.Exit();})));
await dlg.ShowAsync();
}
if (!settings.PlacesVisited)
{
MessageDialog dlg = null;
if (settings.Version < 2)
// Device which has old Motion data settings which requires system location and Motion data be enabled in order to access
// ActivityMonitor.
if( !settings.LocationEnabled )
{
//device which has old motion data settings.
//this is equal to motion data settings on/off in old system settings(SDK1.0 based)
dlg = new MessageDialog("In order to recognize activities you need to enable Motion data in Motion data settings. Do you want to open settings now? if no, application will exit", "Information");
dlg.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(async (cmd) => await SenseHelper.LaunchSenseSettingsAsync())));
dlg.Commands.Add(new UICommand("No", new UICommandInvokedHandler((cmd) =>{ Application.Current.Exit();})));
MessageDialog dlg = new MessageDialog( "In order to recognize activities you need to enable location in system settings. Do you want to open settings now? If not, application will exit.", "Information" );
dlg.Commands.Add( new UICommand( "Yes", new UICommandInvokedHandler( async ( cmd ) => await SenseHelper.LaunchLocationSettingsAsync() ) ) );
dlg.Commands.Add( new UICommand( "No", new UICommandInvokedHandler( ( cmd ) => { Application.Current.Exit(); } ) ) );
await dlg.ShowAsync();
}
else
else if( !settings.PlacesVisited )
{
dlg = new MessageDialog("In order to recognize activities you need to 'enable Places visited' and 'DataQuality to detailed' in Motion data settings. Do you want to open settings now? ", "Information");
dlg.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(async (cmd) => await SenseHelper.LaunchSenseSettingsAsync())));
dlg.Commands.Add(new UICommand("No"));
MessageDialog dlg = new MessageDialog( "In order to recognize activities you need to enable Motion data in Motion data settings. Do you want to open settings now? If not, application will exit.", "Information" );
dlg.Commands.Add( new UICommand( "Yes", new UICommandInvokedHandler( async ( cmd ) => await SenseHelper.LaunchSenseSettingsAsync() ) ) );
dlg.Commands.Add( new UICommand( "No", new UICommandInvokedHandler( ( cmd ) => { Application.Current.Exit(); } ) ) );
await dlg.ShowAsync();
}
}
else if (apiSet >= 3 && settings.DataQuality == DataCollectionQuality.Basic)
else if( apiSet >= 3 )
{
MessageDialog dlg = new MessageDialog("In order to recognize biking you need to enable detailed data collection in Motion data settings. Do you want to open settings now?", "Information");
dlg.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(async (cmd) => await SenseHelper.LaunchSenseSettingsAsync())));
dlg.Commands.Add(new UICommand("No"));
await dlg.ShowAsync();
}
}
if (_activityMonitor == null)
{
if (_runningInEmulator)
{
if (await CallSensorCoreApiAsync(async () => { _activityMonitor = await ActivityMonitorSimulator.GetDefaultAsync(); }))
if( !settings.LocationEnabled )
{
Debug.WriteLine("ActivityMonitorSimulator initialized.");
MessageDialog dlg = new MessageDialog( "In order to recognize biking you need to enable location in system settings. Do you want to open settings now?", "Helpful tip" );
dlg.Commands.Add( new UICommand( "Yes", new UICommandInvokedHandler( async ( cmd ) => await SenseHelper.LaunchLocationSettingsAsync() ) ) );
dlg.Commands.Add( new UICommand( "No" ) );
await dlg.ShowAsync();
}
else return;
}
else
{
if (await CallSensorCoreApiAsync(async () => { _activityMonitor = await ActivityMonitor.GetDefaultAsync(); }))
else if( settings.DataQuality == DataCollectionQuality.Basic )
{
Debug.WriteLine("ActivityMonitor initialized.");
MessageDialog dlg = new MessageDialog( "In order to recognize biking you need to enable detailed data collection in Motion data settings. Do you want to open settings now?", "Helpful tip" );
dlg.Commands.Add( new UICommand( "Yes", new UICommandInvokedHandler( async ( cmd ) => await SenseHelper.LaunchSenseSettingsAsync() ) ) );
dlg.Commands.Add( new UICommand( "No" ) );
await dlg.ShowAsync();
}
else return;
}
if (_activityMonitor != null)
{
// Set activity observer
_activityMonitor.ReadingChanged += activityMonitor_ReadingChanged;
_activityMonitor.Enabled = true;
// Read current activity
ActivityMonitorReading reading = null;
if (await CallSensorCoreApiAsync(async () => { reading = await _activityMonitor.GetCurrentReadingAsync(); }))
{
if (reading != null)
{
MyData.Instance().ActivityEnum = reading.Mode;
}
}
// Read logged data
PollHistory();
}
else
{
// Nothing to do if we cannot use the API
// in a real app do make an effort to make the user experience better
Application.Current.Exit();
}
// Must call DeactivateAsync() when the application goes to background
Window.Current.VisibilityChanged += async (sender, args) =>
{
if (_activityMonitor != null)
{
await CallSensorCoreApiAsync(async () =>
{
if (!args.Visible)
{
await _activityMonitor.DeactivateAsync();
}
else
{
await _activityMonitor.ActivateAsync();
}
});
}
};
}
}
@ -220,41 +200,51 @@ namespace ActivitiesExample
/// </summary>
/// <param name="action">The function delegate to execute asynchronously when one task in the tasks completes</param>
/// <returns><c>true</c> if call was successful, <c>false</c> otherwise</returns>
private async Task<bool> CallSensorCoreApiAsync(Func<Task> action)
private async Task<bool> CallSensorCoreApiAsync( Func<Task> action )
{
Exception failure = null;
try
{
await action();
}
catch (Exception e)
catch( Exception e )
{
failure = e;
Debug.WriteLine("Failure:" + e.Message);
Debug.WriteLine( "Failure:" + e.Message );
}
if (failure != null)
if( failure != null )
{
try
{
MessageDialog dialog = null;
switch (SenseHelper.GetSenseError(failure.HResult))
switch( SenseHelper.GetSenseError( failure.HResult ) )
{
case SenseError.LocationDisabled:
case SenseError.SenseDisabled:
if (!_app.SensorCoreActivationStatus.onGoing)
{
this.Frame.Navigate(typeof(ActivateSensorCore.ActivateSensorCore));
dialog = new MessageDialog( "In order to recognize activities you need to enable location in system settings. Do you want to open settings now? If not, application will exit.", "Information" );
dialog.Commands.Add( new UICommand( "Yes", new UICommandInvokedHandler( async ( cmd ) => await SenseHelper.LaunchLocationSettingsAsync() ) ) );
dialog.Commands.Add( new UICommand( "No", new UICommandInvokedHandler( ( cmd ) => { Application.Current.Exit(); } ) ) );
await dialog.ShowAsync();
new System.Threading.ManualResetEvent( false ).WaitOne( 500 );
return false;
}
case SenseError.SenseDisabled:
{
dialog = new MessageDialog( "In order to recognize activities you need to enable Motion data in Motion data settings. Do you want to open settings now? If not, application will exit.", "Information" );
dialog.Commands.Add( new UICommand( "Yes", new UICommandInvokedHandler( async ( cmd ) => await SenseHelper.LaunchSenseSettingsAsync() ) ) );
dialog.Commands.Add( new UICommand( "No", new UICommandInvokedHandler( ( cmd ) => { Application.Current.Exit(); } ) ) );
await dialog.ShowAsync();
return false;
}
return false;
default:
dialog = new MessageDialog("Failure: " + SenseHelper.GetSenseError(failure.HResult), "");
dialog = new MessageDialog( "Failure: " + SenseHelper.GetSenseError( failure.HResult ), "" );
await dialog.ShowAsync();
return false;
}
}
catch (Exception ex)
catch( Exception ex )
{
Debug.WriteLine("Failed to handle failure. Message:" + ex.Message);
Debug.WriteLine( "Failed to handle failure. Message:" + ex.Message );
return false;
}
}
@ -268,28 +258,27 @@ namespace ActivitiesExample
/// Called when navigating to this page
/// </summary>
/// <param name="e">Event arguments</param>
protected override async void OnNavigatedTo(NavigationEventArgs e)
protected async override void OnNavigatedTo( NavigationEventArgs e )
{
ActivateSensorCoreStatus status = _app.SensorCoreActivationStatus;
if (e.NavigationMode == NavigationMode.Back && status.onGoing)
if( e.NavigationMode == NavigationMode.Back )
{
status.onGoing = false;
if (status.activationRequestResult != ActivationRequestResults.AllEnabled)
// Make sure all necessary settings are enabled in order to run SensorCore
await ValidateSettingsAsync();
// Make sure sensor is activated
if( _activityMonitor == null )
{
MessageDialog dialog = new MessageDialog(_resourceLoader.GetString("NoLocationOrMotionDataError/Text"), _resourceLoader.GetString("Information/Text"));
dialog.Commands.Add(new UICommand("Ok", new UICommandInvokedHandler(async (cmd) => await SenseHelper.LaunchSenseSettingsAsync())));
await dialog.ShowAsync();
new System.Threading.ManualResetEvent(false).WaitOne(500);
Application.Current.Exit();
await InitializeSensorAsync();
}
}
if (_activityMonitor != null)
{
else
{
await _activityMonitor.ActivateAsync();
}
// Register change observer
_activityMonitor.ReadingChanged += activityMonitor_ReadingChanged;
}
else
{
Initialize();
_activityMonitor.Enabled = true;
// Update screen
await UpdateSummaryAsync();
}
}
@ -297,11 +286,13 @@ namespace ActivitiesExample
/// Called when navigating from this page
/// </summary>
/// <param name="e">Event arguments</param>
protected override void OnNavigatedFrom(NavigationEventArgs e)
protected async override void OnNavigatedFrom( NavigationEventArgs e )
{
if (_activityMonitor != null)
if( _activityMonitor != null )
{
_activityMonitor.Enabled = false;
_activityMonitor.ReadingChanged -= activityMonitor_ReadingChanged;
await _activityMonitor.DeactivateAsync();
}
}
@ -310,28 +301,81 @@ namespace ActivitiesExample
/// </summary>
/// <param name="sender">Sender object</param>
/// <param name="args">Event arguments</param>
private async void activityMonitor_ReadingChanged(IActivityMonitor sender, ActivityMonitorReading args)
private async void activityMonitor_ReadingChanged( IActivityMonitor sender, ActivityMonitorReading args )
{
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
await this.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () =>
{
MyData.Instance().ActivityEnum = args.Mode;
});
ActivityData.Instance().CurrentActivity = args.Mode;
} );
}
/// <summary>
/// Poll history, read the data for the past day
/// </summary>
private async void PollHistory()
/// <returns>Asynchronous task</returns>
private async Task UpdateSummaryAsync()
{
if (_activityMonitor != null)
if( _activityMonitor != null )
{
if (!await CallSensorCoreApiAsync(async () =>
if( !await CallSensorCoreApiAsync( async () =>
{
// Get the data for the current 24h time window
MyData.Instance().History = await _activityMonitor.GetActivityHistoryAsync(DateTime.Now.Date.AddDays(MyData.Instance().TimeWindow), new TimeSpan(24, 0, 0));
}))
// Read current activity
ActivityMonitorReading reading = await _activityMonitor.GetCurrentReadingAsync();
if( reading != null )
{
ActivityData.Instance().CurrentActivity = reading.Mode;
}
// Fetch activity history for the day
DateTime startDate = DateTime.Today.Subtract( TimeSpan.FromDays( _dayOffset ) );
DateTime endDate = startDate + TimeSpan.FromDays( 1 );
var history = await _activityMonitor.GetActivityHistoryAsync( startDate, TimeSpan.FromDays( 1 ) );
Dictionary<Activity, TimeSpan> activitySummary = new Dictionary<Activity, TimeSpan>();
var activityTypes = Enum.GetValues( typeof( Activity ) );
foreach( var type in activityTypes )
{
activitySummary[ (Activity)type ] = TimeSpan.Zero;
}
if( history.Count > 0 )
{
Activity currentActivity = history[ 0 ].Mode;
DateTime currentDate = history[ 0 ].Timestamp.DateTime;
foreach( var item in history )
{
if( item.Timestamp >= startDate )
{
TimeSpan duration = TimeSpan.Zero;
if( currentDate < startDate )
{
// If first activity of the day started already yesterday, set start time to midnight.
currentDate = startDate;
}
if( item.Timestamp > endDate )
{
// If last activity extends over to next day, set end time to midnight.
duration = endDate - currentDate;
break;
}
else
{
duration = item.Timestamp - currentDate;
}
activitySummary[ currentActivity ] += duration;
}
currentActivity = item.Mode;
currentDate = item.Timestamp.DateTime;
}
}
List<ActivityDuration> historyList = new List<ActivityDuration>();
foreach( var activityType in activityTypes )
{
historyList.Add( new ActivityDuration( (Activity)activityType, activitySummary[ (Activity)activityType ] ) );
}
ActivityData.Instance().History = historyList;
ActivityData.Instance().Date = startDate;
} ) )
{
Debug.WriteLine("Reading the history failed.");
Debug.WriteLine( "Reading the history failed." );
}
}
}
@ -341,9 +385,9 @@ namespace ActivitiesExample
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">Event arguments</param>
private void AboutButton_Click(object sender, RoutedEventArgs e)
private void AboutButton_Click( object sender, RoutedEventArgs e )
{
this.Frame.Navigate(typeof(AboutPage));
this.Frame.Navigate( typeof( AboutPage ) );
}
/// <summary>
@ -351,9 +395,9 @@ namespace ActivitiesExample
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">Event arguments</param>
private void RefreshButton_Click(object sender, RoutedEventArgs e)
private async void RefreshButton_Click( object sender, RoutedEventArgs e )
{
PollHistory();
await UpdateSummaryAsync();
}
/// <summary>
@ -361,14 +405,16 @@ namespace ActivitiesExample
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">Event arguments</param>
private void PrevButton_Click(object sender, RoutedEventArgs e)
private async void PrevButton_Click( object sender, RoutedEventArgs e )
{
// Move the time window 24 to the past
MyData.Instance().PreviousDay();
nextButton.IsEnabled = true;
prevButton.IsEnabled = MyData.Instance().TimeWindow > -10;
refreshButton.IsEnabled = false;
PollHistory();
if( _dayOffset < 9 )
{
_dayOffset++;
nextButton.IsEnabled = true;
prevButton.IsEnabled = _dayOffset < 9;
refreshButton.IsEnabled = false;
await UpdateSummaryAsync();
}
}
/// <summary>
@ -376,14 +422,16 @@ namespace ActivitiesExample
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">Event arguments</param>
private void NextButton_Click(object sender, RoutedEventArgs e)
private async void NextButton_Click( object sender, RoutedEventArgs e )
{
// Move the time window 24h to the present
MyData.Instance().NextDay();
nextButton.IsEnabled = MyData.Instance().TimeWindow < 0;
prevButton.IsEnabled = true;
refreshButton.IsEnabled = MyData.Instance().TimeWindow == 0;
PollHistory();
if( _dayOffset > 0 )
{
_dayOffset--;
nextButton.IsEnabled = _dayOffset > 0;
prevButton.IsEnabled = true;
refreshButton.IsEnabled = _dayOffset == 0;
await UpdateSummaryAsync();
}
}
}
}

Просмотреть файл

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest" xmlns:m2="http://schemas.microsoft.com/appx/2013/manifest" xmlns:m3="http://schemas.microsoft.com/appx/2014/manifest" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest">
<Identity Name="NokiaDeveloper.ActivitiesLumiaSensorCoreSDKsample" Publisher="CN=4AD6DA08-6C39-4A10-98CC-3243374DA59C" Version="1.1.0.17" />
<Identity Name="NokiaDeveloper.ActivitiesLumiaSensorCoreSDKsample" Publisher="CN=4AD6DA08-6C39-4A10-98CC-3243374DA59C" Version="1.1.0.18" />
<Properties>
<DisplayName>Activities – Lumia SensorCore SDK sample</DisplayName>
<PublisherDisplayName>Lumia SDK</PublisherDisplayName>

Просмотреть файл

@ -91,10 +91,6 @@
<Compile Include="AboutPage.xaml.cs">
<DependentUpon>AboutPage.xaml</DependentUpon>
</Compile>
<Compile Include="ActivateSensorCore\ActivateSensorCore.xaml.cs">
<DependentUpon>ActivateSensorCore.xaml</DependentUpon>
</Compile>
<Compile Include="ActivateSensorCore\SensorCoreActivationStatus.cs" />
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
</Compile>
@ -102,14 +98,14 @@
<Compile Include="Converters\ActivityToImage.cs" />
<Compile Include="Converters\TimeSpanToWidth.cs" />
<Compile Include="Converters\TimeSpanToString.cs" />
<Compile Include="Converters\TimeWindowToString.cs" />
<Compile Include="Data\MyDesignData.cs" />
<Compile Include="Data\MyData.cs" />
<Compile Include="Converters\DateToString.cs" />
<Compile Include="Data\ActivityDesignData.cs" />
<Compile Include="Data\ActivityData.cs" />
<Compile Include="MainPage.xaml.cs">
<DependentUpon>MainPage.xaml</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Converters\ElipsisVisible.cs" />
<Compile Include="Converters\EllipsisVisible.cs" />
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest">
@ -125,10 +121,6 @@
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ActivateSensorCore\ActivateSensorCore.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="MainPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
@ -160,11 +152,13 @@
<PRIResource Include="Strings\en-US\Resources.resw" />
</ItemGroup>
<ItemGroup>
<None Include="Help\LumiaSensorCoreSDK.chm" />
<None Include="packages.config" />
<PRIResource Include="Strings\en-US\ActivateSensorCore.resw" />
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '12.0' ">
<ItemGroup>
<None Include="Help\LumiaSensorCoreSDK.chm" />
<None Include="packages.config" />
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '12.0' ">
<VisualStudioVersion>12.0</VisualStudioVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetPlatformIdentifier)' == '' ">

Просмотреть файл

@ -5,12 +5,6 @@ VisualStudioVersion = 12.0.30723.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "activities", "Activities\activities.csproj", "{613082E5-767C-439B-93E1-0B7968ADE746}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{912DA981-476B-4FA7-8BB4-64F6D8DF0177}"
ProjectSection(SolutionItems) = preProject
.nuget\NuGet.Config = .nuget\NuGet.Config
.nuget\NuGet.targets = .nuget\NuGet.targets
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM = Debug|ARM