2013-11-18 3 views
1

я разрабатывал приложения с Geofencing, когда застрял на вопрос:BackgroundTaskBuilder Register() вопрос

ArgumentException (Значение не попадает в ожидаемый диапазон) , когда я пытаюсь зарегистрировать фоновую задачу для Geofencing.

Образец из MSDN имеет ту же проблему. Я покажу код из образца для ясности (ссылка на образец: http://code.msdn.microsoft.com/windowsapps/Geolocation-2483de66#content сценарий использования 5, http://msdn.microsoft.com/en-us/library/windows/apps/dn440583.aspx - инструкция по тестированию).

Все, что я сделал:

  1. построить мое приложение в Visual Studio.
  2. Сначала разверните приложение локально и добавьте приложение на экран блокировки в настройках.
  3. Закройте приложение, работающее локально.
  4. Запустите приложение в симуляторе Visual Studio.
  5. Вызов RegisterBackgroundTask (..) (просто нажать кнопку регистр в сценарии 5)

Существует код из образца MSDN, что я прокомментировал для успешного приложения развертывается в Simulator - с тегами ////// [ мои изменения] ////////

async private void RegisterBackgroundTask(object sender, RoutedEventArgs e) 
    { 
     try 
     { 

      // Get permission for a background task from the user. If the user has already answered once, 
      // this does nothing and the user must manually update their preference via PC Settings. 
      //BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync(); ////// [my changes] //////// 

      // Regardless of the answer, register the background task. If the user later adds this application 
      // to the lock screen, the background task will be ready to run. 
      // Create a new background task builder 
      BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder(); 

      geofenceTaskBuilder.Name = SampleBackgroundTaskName; 
      geofenceTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint; 

      // Create a new location trigger 
      var trigger = new LocationTrigger(LocationTriggerType.Geofence); 

      // Associate the locationi trigger with the background task builder 
      geofenceTaskBuilder.SetTrigger(trigger); 

      // If it is important that there is user presence and/or 
      // internet connection when OnCompleted is called 
      // the following could be called before calling Register() 
      // SystemCondition condition = new SystemCondition(SystemConditionType.UserPresent | SystemConditionType.InternetAvailable); 
      // geofenceTaskBuilder.AddCondition(condition); 

      // Register the background task 
      geofenceTask = geofenceTaskBuilder.Register(); 

      // Associate an event handler with the new background task 
      geofenceTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted); 

      UpdateButtonStates(/*registered:*/ true); 

      ////// [my changes] //////// 
      //switch (backgroundAccessStatus) 
      //{ 
      // case BackgroundAccessStatus.Unspecified: 
      // case BackgroundAccessStatus.Denied: 
      //  rootPage.NotifyUser("This application must be added to the lock screen before the background task will run.", NotifyType.ErrorMessage); 
      //  break; 

      // default: 
      //  // Ensure we have presented the location consent prompt (by asynchronously getting the current 
      //  // position). This must be done here because the background task cannot display UI. 
      //  GetGeopositionAsync(); 
      //  break; 
      //} 
      ////// [my changes] //////// 
     } 
     catch (Exception ex) 
     { 
      // HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) == 0x80070032 
      const int RequestNotSupportedHResult = unchecked((int)0x80070032); 

      if (ex.HResult == RequestNotSupportedHResult) 
      { 
       rootPage.NotifyUser("Location Simulator not supported. Could not get permission to add application to the lock screen, this application must be added to the lock screen before the background task will run.", NotifyType.StatusMessage); 
      } 
      else 
      { 
       rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage); 
      } 

      UpdateButtonStates(/*registered:*/ false); 
     } 
    } 

Исключение приходится на строку: geofenceTask = geofenceTaskBuilder.Register();

Может кто-нибудь мне помочь?

P.S. Тот же вопрос на msdn - http://social.msdn.microsoft.com/Forums/en-US/3d69f2f9-93e0-401b-8a13-598dc671fa4f/backgroundtask-register?forum=winappswithcsharp

ответ

1

Это известная ошибка, см. Windows Store 8.1 Location background tasks do not work in simulator. Я до сих пор, чтобы получить ответ, кроме

Вашего вопроса было направлено на соответствующие VS команд разработчиков для исследования

Пожалуйста upvote его!

+0

У вас есть еще одна проблема, и, я думаю, вам просто нужно прокомментировать несколько строк (////// [мои изменения] //////// в моем примере кода) BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager. RequestAccessAsync(); - он понадобится на реальном устройстве, а не на симуляторе. – CatCap

+0

Вы читали шаги воспроизведения? Они такие же, как у вас. –

+0

Это повторяется? «Загрузите образец геолокации, найденный в msdn (http://code.msdn.microsoft.com/windowsapps/Geolocation-2483de66). Откройте Visual Studio 2013 RC и отлаживайте приложение на машине определения местоположения, чтобы включить фоновое задание Geofence (сценарий 5) Отключите отладку. Начните отладку на симуляторе. Измените выпадающий список на сценарий 5 (фоновое геообложение) и получите ошибку в методе OnNavigatedTo ». Я читал, вы ничего не говорили о BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync(); Вот почему, я думаю, вы его не удалили – CatCap

 Смежные вопросы

  • Нет связанных вопросов^_^