Tải bản đầy đủ (.pdf) (47 trang)

Session 01 kho tài liệu bách khoa

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.59 MB, 47 trang )

Advanced Windows Store Apps Development – II


 Create a Background Task

 Consume a Background Task

© Aptech Ltd.

Background Task/Session 1

2


In old Windows versions, it was possible to run multiple applications on the desktop
without disturbing each other.
If an app is not running actively and is not currently visible on the screen, it is
suspended by the operating system.
To overcome this difficulty, the WinRT libraries include a collection of classes called
background tasks.

There are certain conditions or options that can be set for a background tasks. These
conditions are defined by an enumerator class known as SystemConditionType.
The SystemConditionType has following options available in it:
InternetAvailable/InternetNotAvailable – Checks if the Internet is available or not
SessionConnected/SessionNotConnected – Checks if the session connected or
disconnected
UserPresent/UserNotPresent – Checks if user available or unavailable

© Aptech Ltd.


Background Task/Session 1

3


Threading allows running multiple tasks within a single process. The main thread can be forked into
multiple sub threads called tasks. The two types of thread concepts available to execute in the app are a
UI thread and a background thread. The thread pool will queue the threads and are configured and
designed to start execution automatically whenever the processor needs it. The next thread in the queue
will start when the execution of current thread is completed.

Note -The developer can use CreatePeriodicTimer to run the thread repeatedly.

© Aptech Ltd.

Background Task/Session 1

4


To Create and Register a Background Task
Similar to a thread, a background task is a function that runs in the memory of an app without
disturbing the normal execution of other apps. Background task can execute the code in the
memory without making the app active.
Background tasks will be necessary in the following situations:

When some streaming audio is to be played.
A Live Tile needs to update new data from the server.
A Push Notification pops up when the notification is sent or received.
A Lock screen updates when a device is locked or unlocked.


© Aptech Ltd.

Background Task/Session 1

5


Here is a basic implementation of IBackgroundTask:
Code Snippet:
public class SimpleBgTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
// Insert code to perform some activities here
}
}

There are five types of triggers that can be assigned to the current task. These triggers will
automatically start execution of the background task. These triggers are shown in table.

© Aptech Ltd.

Background Task/Session 1

6


To register a background task in an app, the user has to enable background tasks in the
Package.appxmanifest file as shown in figure.


© Aptech Ltd.

Background Task/Session 1

7


Select the System event property as shown in figure.

© Aptech Ltd.

Background Task/Session 1

8


Respond to System Events with Background Tasks
The background task can made to respond to the user through system events. The user has to
declare the Entry point in the app manifest file by selecting the background task from the
declaration tab as shown in figure.

© Aptech Ltd.

Background Task/Session 1

9


To register the Background Task the user has to write the code shown in Code Snippet.

Code Snippet:
private void RegisterBackgroundTask(string n, string p)
{ BackgroundTaskBuilder b = new BackgroundTaskBuilder();
b.Name = n;
b.TaskEntryPoint = p;
b.SetTrigger(new SystemTrigger(SystemTriggerType.InternetAvailable,
false));
BackgroundTaskRegistration t = b.Register(); }

Create a function fnChkReg() to check whether the task is registered or unregistered by writing
the code shown in Code Snippet.
Code Snippet:
private void fnChkReg()
{
foreach (var task in BackgroundTaskRegistration.AllTasks)
{ if (task.Value.Name == “Update”) {
isRegistered = true;
break;
} }
© Aptech Ltd.

Background Task/Session 1

10


Code Snippet (Cont.):
if (isRegistered)
{ RegisterButton.Content = “Unregister”;
lblResult.Text = “Task Registered”; }

else if (!isRegistered)
{ RegisterButton.Content = “Register”;
lblResult.Text = “Task UnRegistered”; } }

Set Conditions for Running a Background Task
The user has to know how to check the conditions and apply them to the background task. These
conditions are checked by using a trigger in the app. Following Code Snippet shows how to set the
SystemTriggerType for the background task:
Code Snippet:
BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
builder.Name = nameofbktask;
builder.TaskEntryPoint = programname;
builder.SetTrigger(new SystemTrigger(SystemTriggerType.InternetAvailable,
false));
BackgroundTaskRegistration t = builder.Register();
© Aptech Ltd.

Background Task/Session 1

11


Handle a Cancelled Background Task
The background tasks are short running processes, which executes the code and restarts
automatically for executing the task again using a timer. The user can cancel any running
background tasks if it is not necessary to run at that time. To cancel the task the user has to declare
the CancellationTokenSource by writing code as shown in Code Snippet.
Code Snippet:
CancellationTokenSource c = new CancellationTokenSource();


On the OnCancelled method write c.Cancel() to stop the task by writing the following Code
Snippet:
Code
CodeSnippet:
Snippet:
private void OnCancelled(IBackgroundTaskInstance sender,
BackgroundTaskCancellationReason reason)
{
c.Cancel();
}

© Aptech Ltd.

Background Task/Session 1

12


Monitor Background Task Progress and Completion
Tasks can be monitored by displaying a message in the UI of the app. The user can set the trigger
to update the status of the task running. For example, if the user needs to execute task
continuously then for every completion of the task, there must be a notification in the UI in the
form of a message displayed in a TextBlock as shown in Code Snippet.
Code Snippet:

if(isRegistered)
{
RegisterButton.Content
lblResult.Text = “Task
}

if(!isRegistered)
{
RegisterButton.Content
lblResult.Text = “Task
}

© Aptech Ltd.

= “Unregister”;
Registered”;

= “Register”;
UnRegistered”;

Background Task/Session 1

13


Run a Background Task Using a Timer
If the user wants to run the task repeatedly after some interval, then the task can be called using a
timer. A class called TimeTrigger is available for this purpose.
Create an instance of this class and set necessary properties to make it work. The timer has to be
declared in the function as shown in Code Snippet.

Code Snippet:
TimeTrigger t = new TimeTrigger(15, false);

Note - The user has to set the time to restart the task, as mentioned in Code Snippet, the task will
execute after every 15 minutes.


© Aptech Ltd.

Background Task/Session 1

14


 Triggers are created in the background task to keep the app stable and to execute the code
without disturbing the UI.
 These triggers are declared with some duration.
 Thus, the triggers can execute the code periodically after an interval from the background of
the app.

Maintenance Triggers
As the maintenance trigger occurs, the device will update the task periodically as set by the user
in the code. This MaintenanceTrigger can be declared by writing code as shown in Code
Snippet.
Code Snippet:
MaintenanceTrigger t = new MaintenanceTrigger(15, false);

Note - MaintenanceTrigger will execute only when the device is plugged into AC power.

© Aptech Ltd.

Background Task/Session 1

15



Declare Background Tasks in the Application Manifest
The user has to declare the background task in the Package.appxmanifest file. To do so, the
user has to right-click the manifest file and select View Code or Press F7 as shown in figure.

© Aptech Ltd.

Background Task/Session 1

16




In the application node, write the code to mention the extension for the background task.



To apply the BackgroundTask extension in the manifest file, the user has to write the code
as shown in Code Snippet in the application tag.

Code Snippet:
EntryPoint=”BGTrigger.App”>
Logo.png” Square30x30Logo=”Assets\SmallLogo.png” Description=”BGTrigger”
ForegroundText=”light” BackgroundColor=”#464646”>
<m2:SplashScreen Image=”Assets\SplashScreen.png” />
</m2:VisualElements>
<Extensions>
<Extension Category=”windows.backgroundTasks” EntryPoint=”Tasks.Update”>

<BackgroundTasks>
<Task Type=”systemEvent” />
</BackgroundTasks>
</Extension>
</Extensions>
</Application>

© Aptech Ltd.

Background Task/Session 1

17


Guidelines and Checklists for Background Tasks
Guidelines:
The user has to follow the guidelines while developing the app.
CPU and Network Quotas
• The user has to maintain the CPU or Network usage limit, as it should not exceed.

Manage Background Tasks
• The app must be written in such a way that each task must be updated in the
event entry, so that the system log helps the user to find errors in an app.

Update App Manifest
• The user has to ensure that all the background tasks are declared in the app
manifest file whenever they are created together with the trigger type.

© Aptech Ltd.


Background Task/Session 1

18


Checklist:
1. Point the correct trigger for each background task.
2. Maintain conditions to check the status while the background tasks are running.
3. Except Tile, Toast or Badge notifications, the user need not display any info in the UI of
the app.
4. There should not be any user interaction in the background task.
5. The background task should not be dependable on the user.
6. Using Maintenance Trigger, check for Registration errors.

© Aptech Ltd.

Background Task/Session 1

19


How to Debug a Background Task?
 The user can debug the code to check the status of the code, if the code is successfully
executing or intervening errors in the task. To check, the user has to select the desired
option such as suspend, resume, suspend and shutdown, update as shown in figure.
 Suspend option halts the task at that point of time and can be resumed as the user selects
the resume option as shown in figure.

© Aptech Ltd.


Background Task/Session 1

20


 As the code is suspended, the user can navigate to Event Viewer to view the system logs of
the tasks. Press Win + R key to open the run command. Type eventvwr.exe and press Enter to
open the event viewer as shown in figure.

© Aptech Ltd.

Background Task/Session 1

21


 When the Event Viewer window is opened the user has to navigate to Application and Services
Logs → Microso → Windows → BackgroundTaskInfrastructure.
 To view the debug logs, the user has to select Show Analytic and Debug Logs option from the
view menu as shown in figure.

© Aptech Ltd.

Background Task/Session 1

22


 The user can now view the Diagnostic menu in the left tree menu as shown in figure. Select
the Diagnostic Menu and select Enable Log option to record all the logs of the background

task.

© Aptech Ltd.

Background Task/Session 1

23


 Now, run the code by resuming and clicking the Register button to register the background
task as shown in figure.

© Aptech Ltd.

Background Task/Session 1

24


 Open the event viewer and refresh the diagnostic menu to view the log created inside. To
view the log, select the log created and then, the user can view the description of the log,
as shown in figure.

© Aptech Ltd.

Background Task/Session 1

25



×