简体   繁体   中英

Windows Phone 8.1 SmartCard app with background task crashing

I got a problem I am trying to solve for over a week now and I just cannot solve it. I am trying to make a very simple Windows Phone 8.1 app with nfc and smartcard stuff. Later I attempt to use the smartcard emulation, provided by the Class SmartCardEmulator, but for now I just want to have a background task that does stuff when an nfc tag / smartcard is approached. For this question I made a complete new project which contains just the basics. The program keeps crashing when I press the button.

At start I made a blank Windows Phone App Project and a Windows Runtime Component which I added to the solution. The Phone App Project has a reference to the Windows Runtime Component Project.

In the MainPage.xaml I put just a button and a textbox.

The class BackgroundTaskManager is in the windows phone app project and the class TaskOne is in the runtime component project.

In the file Package.appxmanifest I added the background task in the declarations with BackgroundTasks.TaskOne as EntryPoint and System Events as support task types

In the Requirements I enabled NFC

The Errors I get when pressing the button are the following:

A first chance exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll
A first chance exception of type 'System.UnauthorizedAccessException' occurred in SimpleNfcApp.exe
A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.ni.dll
A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.ni.dll

I tried debugging and put the break poin at the start of the RegisterBackgroundTask method in BackgroundTaskManager.cs and it then crashes at the end of doSomething in MainPage.xaml.cs

Here are the sourecodes:

MainPage.xaml.cs

namespace SimpleNfcApp
{
    public sealed partial class MainPage : Page
    {
        public MainPage() {
            this.InitializeComponent();
            this.NavigationCacheMode = NavigationCacheMode.Required;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e) {
        }

        // method put on a button
        private async void doSomething(object sender, TappedRoutedEventArgs e)
        {
            String taskName = BackgroundTaskManager.TaskOneName;
            bool isActive = isTaskActive(taskName);

            if(isActive == false) {
                startTask();
            } else {
                myTextBox.Text = "Task already active";
            }
        }

        // starts a task
        private async void startTask()
        {
            var trigger = new SmartCardTrigger(SmartCardTriggerType.EmulatorNearFieldEntry);
            var task = BackgroundTaskManager.RegisterBackgroundTask(BackgroundTaskManager.TaskOneEntryPoint,
                                                                    BackgroundTaskManager.TaskOneName,
                                                                    trigger,
                                                                    null);
            await task;
            myTextBox.Text += task.Result.ToString();
        }

        // checks if the task is already active
        private static bool isTaskActive(String name)
        {
            foreach (var task in BackgroundTaskRegistration.AllTasks)
            {
                if (task.Value.Name == name)
                    return true;
            }
            return false;
        }

    }
}

BackgroundTaskManager.cs

namespace SimpleNfcApp
{
    class BackgroundTaskManager
    {
        public const string TaskOneEntryPoint = "BackgroundTasks.TaskOne";
        public const string TaskOneName = "TaskOne";
        public static string TaskOneProgress = "";
        public static bool TaskOneRegistered = false;

        // creates and registers the task
        public static async Task<BackgroundTaskRegistration> RegisterBackgroundTask(String taskEntryPoint, String taskName, IBackgroundTrigger taskTrigger, IBackgroundCondition taskCondition)
        {
            if (TaskRequiresBackgroundAccess(taskName))
                await BackgroundExecutionManager.RequestAccessAsync();

            var builder = new BackgroundTaskBuilder();

            builder.Name = taskName;
            builder.TaskEntryPoint = taskEntryPoint;
            builder.SetTrigger(taskTrigger);

            BackgroundTaskRegistration task = builder.Register();

            var settings = ApplicationData.Current.LocalSettings;
            settings.Values.Remove(taskName);

            return task;
        }

        // checks if it is a windows phone app or a simple windows app
        public static bool TaskRequiresBackgroundAccess(String name)
        {
            #if WINDOWS_PHONE_APP
                return true;
            #else

            #endif
        }

    }
}

TaskOne.cs

namespace BackgroundTasks
{
    public sealed class TaskOne
    {
        IBackgroundTaskInstance _taskInstance;
        BackgroundTaskDeferral _deferral;

        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _taskInstance = taskInstance;
            _deferral = taskInstance.GetDeferral();

            int x;
            x = 2 + 2;

            _deferral.Complete();
        }


    }
}

Does anyone see what I am doing wrong? Thanks for reading. greez, Skippy

EDIT:

I added a try catch block around the doSomething method in MainPage.xaml.cs and got a new more telling error message.

A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.ni.dll
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
   at Windows.ApplicationModel.Background.BackgroundTaskBuilder.Register()
   at SimpleNfcApp.BackgroundTaskManager.<RegisterBackgroundTask>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at SimpleNfcApp.MainPage.<startTask>d__0.MoveNext() Second exception caught.

Also, when I change the trigger in doSomething before registering the task, it works. I tried this one:

//var trigger = new SmartCardTrigger(SmartCardTriggerType.EmulatorNearFieldEntry);
var trigger = new SystemTrigger(SystemTriggerType.ServicingComplete, false);

U got error code there

var settings = ApplicationData.Current.LocalSettings;
settings.Values.Remove(taskName);

ApplicationData.Current.LocalSettings - to this file access denied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM