Example #1
0
        public async Task <bool> CheckDeviceAccessAsync()
        {
            var access = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);

            if (access.CurrentStatus == DeviceAccessStatus.Unspecified)
            {
                var accessStatus = await Geolocator.RequestAccessAsync();

                if (accessStatus == GeolocationAccessStatus.Allowed)
                {
                    return(true);
                }

                return(false);
            }
            else if (access.CurrentStatus != DeviceAccessStatus.Allowed)
            {
                var message = Strings.Resources.PermissionNoLocationPosition;

                var confirm = await MessagePopup.ShowAsync(message, Strings.Resources.AppName, Strings.Resources.PermissionOpenSettings, Strings.Resources.OK);

                if (confirm == ContentDialogResult.Primary)
                {
                    await Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location"));
                }

                return(false);
            }

            return(true);
        }
Example #2
0
        private static async Task <bool> Initialize()
        {
            bool initializedSuccessfully = false;

            accessInfo = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);
            try
            {
                if (geolocator == null)
                {
                    geolocator = new Geolocator();
                }

                // Get cancellation token
                cts = new CancellationTokenSource();
                CancellationToken token = cts.Token;

                currentLocation = await geolocator.GetGeopositionAsync().AsTask(token);

                // other initialization for your app could go here

                accessInfo.AccessChanged += OnAccessChanged;
                GeofenceMonitor.Current.GeofenceStateChanged += OnGeofenceStateChanged;
                initializedSuccessfully = true;
            }
            catch (UnauthorizedAccessException)
            {
                if (DeviceAccessStatus.DeniedByUser == accessInfo.CurrentStatus)
                {
                    MessageBox.Show("Location has been disabled by the user. Enable access through the settings charm.");
                }
                else if (DeviceAccessStatus.DeniedBySystem == accessInfo.CurrentStatus)
                {
                    MessageBox.Show("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.");
                }
                else if (DeviceAccessStatus.Unspecified == accessInfo.CurrentStatus)
                {
                    MessageBox.Show("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.");
                }
            }
            catch (TaskCanceledException)
            {
                // task cancelled
            }
            catch (Exception)
            {
                if (geolocator.LocationStatus == PositionStatus.Disabled)
                {
                    // On Windows Phone, this exception will be thrown when you call
                    // GetGeopositionAsync if the user has disabled locaton in Settings.
                    MessageBox.Show("Location has been disabled in Settings.");
                }
            }
            finally
            {
                cts = null;
            }

            return(initializedSuccessfully);
        }
Example #3
0
        public MainPage()
        {
            this.InitializeComponent();

            m_deviceAccessInformation = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.AudioCapture);
            // Note: In unpatched RS4 the OnAccessChanged method will never be called.
            // This is fixed in RS5 and an upcoming update to RS4
            m_deviceAccessInformation.AccessChanged += new TypedEventHandler <DeviceAccessInformation, DeviceAccessChangedEventArgs>(OnAccessChanged);
        }
        /// <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 override void OnNavigatedTo(NavigationEventArgs e)
        {
            DeviceAccessInformation accessInfo;

            accessInfo = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);
            accessInfo.AccessChanged += OnAccessChanged;
            Initialize();
            CreateGeofence();
        }
Example #5
0
        private async Task <bool> CheckDeviceAccessAsync(bool audio, ChatRecordMode mode)
        {
            // For some reason, as far as I understood, CurrentStatus is always Unspecified on Xbox
            if (string.Equals(AnalyticsInfo.VersionInfo.DeviceFamily, "Windows.Xbox"))
            {
                return(true);
            }

            var access = DeviceAccessInformation.CreateFromDeviceClass(audio ? DeviceClass.AudioCapture : DeviceClass.VideoCapture);

            if (access.CurrentStatus == DeviceAccessStatus.Unspecified)
            {
                MediaCapture capture = null;
                try
                {
                    capture = new MediaCapture();
                    var settings = new MediaCaptureInitializationSettings();
                    settings.StreamingCaptureMode = mode == ChatRecordMode.Video
                        ? StreamingCaptureMode.AudioAndVideo
                        : StreamingCaptureMode.Audio;
                    await capture.InitializeAsync(settings);
                }
                catch { }
                finally
                {
                    if (capture != null)
                    {
                        capture.Dispose();
                        capture = null;
                    }
                }

                return(false);
            }
            else if (access.CurrentStatus != DeviceAccessStatus.Allowed)
            {
                var message = audio
                    ? mode == ChatRecordMode.Voice
                    ? Strings.Resources.PermissionNoAudio
                    : Strings.Resources.PermissionNoAudioVideo
                    : Strings.Resources.PermissionNoCamera;

                this.BeginOnUIThread(async() =>
                {
                    var confirm = await MessagePopup.ShowAsync(message, Strings.Resources.AppName, Strings.Resources.PermissionOpenSettings, Strings.Resources.OK);
                    if (confirm == ContentDialogResult.Primary)
                    {
                        await Launcher.LaunchUriAsync(new Uri("ms-settings:appsfeatures-app"));
                    }
                });

                return(false);
            }

            return(true);
        }
Example #6
0
        private async Task <bool> CheckDeviceAccessAsync()
        {
            var access = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.AudioCapture);

            if (access.CurrentStatus == DeviceAccessStatus.Unspecified)
            {
                MediaCapture capture = null;
                try
                {
                    capture = new MediaCapture();
                    var settings = new MediaCaptureInitializationSettings
                    {
                        StreamingCaptureMode = StreamingCaptureMode.Audio
                    };
                    await capture.InitializeAsync(settings);
                }
                catch { }
                finally
                {
                    if (capture != null)
                    {
                        capture.Dispose();
                        capture = null;
                    }
                }

                return(false);
            }
            else if (access.CurrentStatus != DeviceAccessStatus.Allowed)
            {
                //var message = audio
                //    ? mode == ChatRecordMode.Voice
                //    ? Strings.Resources.PermissionNoAudio
                //    : Strings.Resources.PermissionNoAudioVideo
                //    : Strings.Resources.PermissionNoCamera;

                //this.BeginOnUIThread(async () =>
                //{
                //    var confirm = await TLMessageDialog.ShowAsync(message, Strings.Resources.AppName, Strings.Resources.PermissionOpenSettings, Strings.Resources.OK);
                //    if (confirm == ContentDialogResult.Primary)
                //    {
                //        await Launcher.LaunchUriAsync(new Uri("ms-settings:appsfeatures-app"));
                //    }
                //});

                return(false);
            }

            return(true);
        }
Example #7
0
 public AccessManager(IGeolocationService _geolocationService)
 {
     this._geolocationService         = _geolocationService;
     AccessInformation                = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);
     AccessInformation.AccessChanged += AccessInformationOnAccessChanged;
 }
Example #8
0
        public Scenario4()
        {
            this.InitializeComponent();

            try
            {
                formatterShortDateLongTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{month.integer}/{day.integer}/{year.full} {hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                formatterLongTime          = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                calendar         = new Windows.Globalization.Calendar();
                decimalFormatter = new Windows.Globalization.NumberFormatting.DecimalFormatter();

                geofenceCollection = new GeofenceItemCollection();
                eventCollection    = new EventDescriptorCollection();

                // Get a geolocator object
                geolocator = new Geolocator();

                geofences = GeofenceMonitor.Current.Geofences;

                // using data binding to the root page collection of GeofenceItems
                RegisteredGeofenceListBox.DataContext = geofenceCollection;

                // using data binding to the root page collection of GeofenceItems associated with events
                GeofenceEventsListBox.DataContext = eventCollection;

                FillRegisteredGeofenceListBoxWithExistingGeofences();
                FillEventListBoxWithExistingEvents();

                accessInfo = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);
                accessInfo.AccessChanged += OnAccessChanged;

                coreWindow = CoreWindow.GetForCurrentThread(); // this needs to be set before InitializeComponent sets up event registration for app visibility
                coreWindow.VisibilityChanged += OnVisibilityChanged;

                // register for state change events
                GeofenceMonitor.Current.GeofenceStateChanged += OnGeofenceStateChanged;
                GeofenceMonitor.Current.StatusChanged        += OnGeofenceStatusChanged;
            }
            catch (UnauthorizedAccessException)
            {
                if (DeviceAccessStatus.DeniedByUser == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by the user. Enable access through the settings charm.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.DeniedBySystem == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.Unspecified == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.", NotifyType.StatusMessage);
                }
            }
            catch (Exception ex)
            {
                // GeofenceMonitor failed in adding a geofence
                // exceptions could be from out of memory, lat/long out of range,
                // too long a name, not a unique name, specifying an activation
                // time + duration that is still in the past

                // If ex.HResult is RPC_E_DISCONNECTED (0x80010108):
                // The Location Framework service event state is out of synchronization
                // with the Windows.Devices.Geolocation.Geofencing.GeofenceMonitor.
                // To recover remove all event handlers on the GeofenceMonitor or restart the application.
                // Once all event handlers are removed you may add back any event handlers and retry the operation.

                rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
Example #9
0
        /// <summary>
        /// Initialize SensorCore and find the current position
        /// </summary>
        private async void InitCore()
        {
            if (_monitor == null)
            {
                // This is not implemented by the simulator, uncomment for the PlaceMonitor
                if (await Monitor.IsSupportedAsync())
                {
                    // Init SensorCore
                    if (await CallSensorcoreApiAsync(async() => { _monitor = await Monitor.GetDefaultAsync(); }))
                    {
                        Debug.WriteLine("PlaceMonitor initialized.");

                        // Update list of known places
                        await UpdateKnownPlacesAsync();

                        HomeButton.IsEnabled     = true;
                        WorkButton.IsEnabled     = true;
                        FrequentButton.IsEnabled = true;
                        CurrentButton.IsEnabled  = true;
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    var           loader = new Windows.ApplicationModel.Resources.ResourceLoader();
                    MessageDialog dialog = new MessageDialog(loader.GetString("NoMotionDataSupport/Text"), loader.GetString("Information/Text"));
                    dialog.Commands.Add(new UICommand(loader.GetString("OkButton/Text")));
                    await dialog.ShowAsync();

                    new System.Threading.ManualResetEvent(false).WaitOne(500);
                    Application.Current.Exit();
                }
                // Init Geolocator
                try
                {
                    _accessInfo = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);
                    _accessInfo.AccessChanged += OnAccessChanged;
                    // Get a geolocator object
                    _geolocator = new Geolocator();
                    // Get cancellation token
                    _cancellationTokenSource = new CancellationTokenSource();
                    CancellationToken token       = _cancellationTokenSource.Token;
                    Geoposition       geoposition = await _geolocator.GetGeopositionAsync().AsTask(token);

                    _currentLocation = new Geopoint(new BasicGeoposition()
                    {
                        Latitude  = geoposition.Coordinate.Point.Position.Latitude,
                        Longitude = geoposition.Coordinate.Point.Position.Longitude
                    });

                    // Focus on the current location
                    OnCurrentClicked(this, null);
                }
                catch (UnauthorizedAccessException)
                {
                    if (DeviceAccessStatus.DeniedByUser == _accessInfo.CurrentStatus)
                    {
                        Debug.WriteLine("Location has been disabled by the user. Enable access through the settings charm.");
                    }
                    else if (DeviceAccessStatus.DeniedBySystem == _accessInfo.CurrentStatus)
                    {
                        Debug.WriteLine("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.");
                    }
                    else if (DeviceAccessStatus.Unspecified == _accessInfo.CurrentStatus)
                    {
                        Debug.WriteLine("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.");
                    }
                }
                catch (TaskCanceledException)
                {
                    // task cancelled
                }
                catch (Exception ex)
                {
                    if ((uint)ex.HResult == 0x80004004)
                    {
                        // the application does not have the right capability or the location master switch is off
                        Debug.WriteLine("location is disabled in phone settings.");
                    }
                }
                finally
                {
                    _cancellationTokenSource = null;
                }
            }
            // Activate and deactivate the SensorCore when the visibility of the app changes
            Window.Current.VisibilityChanged += async(oo, ee) =>
            {
                if (_monitor != null)
                {
                    if (!ee.Visible)
                    {
                        await CallSensorcoreApiAsync(async() => { await _monitor.DeactivateAsync(); });
                    }
                    else
                    {
                        await CallSensorcoreApiAsync(async() => { await _monitor.ActivateAsync(); });
                    }
                }
            };
        }
Example #10
0
        private static async Task <bool> CheckDeviceAccessAsync(bool audio, bool video, ElementTheme requestedTheme = ElementTheme.Default)
        {
            // For some reason, as far as I understood, CurrentStatus is always Unspecified on Xbox
            if (string.Equals(AnalyticsInfo.VersionInfo.DeviceFamily, "Windows.Xbox"))
            {
                return(true);
            }

            var access = DeviceAccessInformation.CreateFromDeviceClass(audio ? DeviceClass.AudioCapture : DeviceClass.VideoCapture);

            if (access.CurrentStatus == DeviceAccessStatus.Unspecified)
            {
                MediaCapture capture = null;
                bool         success = false;
                try
                {
                    capture = new MediaCapture();
                    var settings = new MediaCaptureInitializationSettings();
                    settings.StreamingCaptureMode = video
                        ? StreamingCaptureMode.AudioAndVideo
                        : StreamingCaptureMode.Audio;
                    await capture.InitializeAsync(settings);

                    success = true;
                }
                catch { }
                finally
                {
                    if (capture != null)
                    {
                        capture.Dispose();
                    }
                }

                return(success);
            }
            else if (access.CurrentStatus != DeviceAccessStatus.Allowed)
            {
                var message = audio
                    ? video
                    ? Strings.Resources.PermissionNoAudio
                    : Strings.Resources.PermissionNoAudioVideo
                    : Strings.Resources.PermissionNoCamera;

                var popup = new MessagePopup
                {
                    Title               = Strings.Resources.AppName,
                    Message             = message,
                    PrimaryButtonText   = Strings.Resources.Settings,
                    SecondaryButtonText = Strings.Resources.OK,
                    RequestedTheme      = requestedTheme
                };

                var confirm = await popup.ShowQueuedAsync();

                if (confirm == ContentDialogResult.Primary)
                {
                    await Launcher.LaunchUriAsync(new Uri("ms-settings:appsfeatures-app"));
                }

                return(false);
            }

            return(true);
        }