Windows Mobile Support

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Friday, 13 April 2012

Background task in Windows 8 Metro Style App

Posted on 10:28 by Unknown
O aplicatie nativa Metro style este diferita din unele puncte de vedere fata de o aplicatie desktop pentru Windows 7 de exemplu. Daca ati scris aplicatii pentru Windows Phone 7 va pot spune ca din unele puncte de vedere o aplicatie Metro style este mai asemanatoare cu o aplicatie Silverlight pentru Windows Phone 7.
O aplicatie in Metro style poate sa aibe doua stari. Prima stare este starea foreground, cand aplicatia este cea curenta (cea care se afiseaza pe ecran) si ruleaza ca o aplicatie normala. A doua stare este cand aceasta se afla in spate. Nu este aplicatie curenta. In momentul acesta toate firele de executie (thread-urile) sunt inghetate. Aceasta stare poarta numele de suspended. Momentul cand se face switch intre cele doua stari poate sa fie prins de catre programator. Despre cum se face acest lucru o sa vorbim cu alta ocazie.
Astazi o sa vorbim despre cum putem sa executa cod in fundal, cand aplicatia noastra este oprita. Uneori avem nevoie la aplicatie sa putem afisa updateuri pe lock screen sau sa verificam daca pe un anumit socket se intampla ceva (VOIP). Pentru acest lucru au fost creat background task.
Un lucru foarte important care trebuie stiut de la inceput despre background task este ca acesta ruleaza cand sistemul de operare doreste nu cand doreste programatorul. Exista mai multe triggere pe care le putem folosii cand vrem ca un background task sa fie apelat. Prin intermediul acestora codul nostru o sa poata sa fie executat.
Mai jos gasiti lista triggerele care sunt disponibile in acest moment:
  1. ControlChannelTrigger
  2. InternetAvailable
  3. InternetNotAvailable
  4. LockScreenApplicationAdded
  5. LockScreenApplicationRemoved
  6. MaintenanceTrigger
  7. NetworkNotificationChannelReset
  8. NetworkStateChange
  9. OnlineIdConnectedStateChange
  10. PushNotificationTrigger
  11. ServicingComplete
  12. SessionConnected
  13. SessionDisconnected
  14. SessionStart
  15. SmsReceived
  16. TimeTrigger
  17. TimeZoneChange
  18. UserAway
  19. UserPresent
Ne putem imagina ca un background task este ca o combinatie intre un Windows Service si un Windows Task. Are putin din fiecare. Un background task poate sa ruleze in doua "locatii". In functie de cum este seteaza userul aplicatia noastra:
  • Lock Screen App
  • Non-Lock Screen App
Este foarte important sa stim ca in functie de acest lucru, Windows 8 ne aluca un numar limitat de resurse pe care le putem folosii (CPU). In cazul unei aplicatii Lock Screen App, ne sunt alocate 2 secunde de CPU la un interval de 15 minute. In celalat caz ne este alocata o singura secunda la interval de 120 de minute. Atentie, 1 secunda CPU nu este tot una cu 1 secunda normala. De exemplu daca facem un request spre un URL, nu se contorizeaza timpul pana rezultatul vine de la server. La fel exista anumite limitari din punct de vedere a traficului pe care il putem face prin WiFi.
As vrea sa subliniez ca aceste valori s-ar putea sa se schimbe in viitor, din aceasta cauza este bine sa verificati de fiecare data cand un nou release sau update se face la Windows 8 (noi cel putin speram sa se schimbe putin). De exemplu un trigger de tip TimeTrigger poate sa ruleze la un interval de cel putin 15 minute. Asta inseamna ca daca avem un backgroud task care dorim sa fie rulat odata la 2 minute, nu o sa putem face acest lucru sub nici o forma.
Din punct de vedere tehnic, un background task se definieste intr-un assembly separat si trebuie inregistrat. Trebuie avut grija ca tipul de clas library selectat sa fie WinMD si nu DLL. In functe de stare pe care o are aplicatia noastra un background task poate sa fie apelat de catre:
  • aplicatia noastra - cand aplicatia ruleaza si este in foreground
  • Windows 8 - cand aplicatia este suspended sau aplicatia nu ruleaza (terminated)
Un background task poate sa aibe una sau mai multe condititi care sa fie verificare inainte sa fie rulat. De exemplu daca avem un backgroud task care are nevoie de conexiuen de internet nu dorim sa il rulam daca nu avem conexiune. In acest caz putem sa specificam o conditie care sa fie verificata inainte ca task-ul sa fie apelat.
Pentru a inregistra un task este nevoie sa ne instantiam un BackgroundTaskBuilder si sa setam triggerul si conditiile (optional) cand un background task sa ruleze. Dupa acest pas, putem sa apelam metoda Register() care o sa ne inregistreze background task-ul.
BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
builder.Name = "FooBackgroundTask";
builder.TaskEntryPoint = "Foo.FooBackgroundTask";
IBackgroundTrigger trigger = new TimeTrigger(30, true);
builder.SetTrigger(trigger);
IBackgroundTaskRegistration task = builder.Register();
TaskEntryPoint specifica namespaceul si clasa unde clasa noastra este definita.
Exista doua evenimente, pe baza carora din aplicatia putem sa stim care este progresul la task si cand s-a terminat de executat. Merita de mentionat ca este nevoie sa ne inrefitram la aceste evenimente de fiecare data cand aplicatia se porneste. Cand aceasta trece din starea suspended in running nu mai este nevoie sa ne inregistram la aceste evenimente. Prin intermediul metodei BackgroundTaskRegistration.AllTasks putem sa obtinem toate task-urile inregistrate. Dupa ce obtinem task-ul pe care noi il dorim putem sa ne inregistram la evenimente.

var fooBT = BackgroundTaskRegistration.AllTasks.First(x=>x.Name == "FooBackgroundTask");
fooBT.Value.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
fooBT.Value.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
Acuma ca am vazut putem sa manipulam un background task, este momentul sa vedem cum il putem definii.
Clasa noastra FooBackgroundTask, trebuie sa implementeze interfata IBackgroundTask. Aceasta are o singura metoda Run, care este apelata de catre Windows 8 cand task-ul este pornit.
public sealed class FooBackgroundTask:IBackgroundTask
{
private int globalcount;

void IBackgroundTask.Run(IBackgroundTaskInstance taskInstance)
{
// do something
}
}
In interiorul metodei Run se intampla toata magia, putem sa facem orice, atata timp cat ne incadram in CPU time alocat. Prin intermediul taskInstance, care este de tip IBackgroundTaskInstance, putem sa comunicam cu aplicatia noastra care este in foreground. De exemplu putem sa trimitem notificari de tipul progress updateds.
Mai devreme am spus ca un background task poate sa faca apeluri asincrone spre orice alte resurse. Pentru a putea face acest lucru este nevoie sa folosim BackgroundTaskDeferral. Pentru fiecare operatie asincrona ar trebui sa folosim unul nou.
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
IAsyncAction action = //Call async
action.Completed = new AsyncActionCompletedHandler(
(IAsyncAction act, AsyncStatus stat) =>
{
deferral .Complete();
});
Pentru a putea folosii un background task o aplicatie Metro style trebuie sa il declare in manifest. Fiecare background task o sa fie un alt entry point. O aplicatie poate sa aibe mai mult de un background task. Prin manifest se specifica un background task ca si o extensie la care se defineste un entry point si tipul de eveniment pentru trigger. Daca din cod se incearca inregistrarea la un alt tip de trigger, aplicatia o sa crape.
Iar mai jos puteti sa vedeti o schema care prezinta cum este lansat un background task si de catre cine.

Cam asta a fost despre background task. Inainte sa va apucati sa scrieti un background task pentru aplicatia voastra ar trebui sa va ganditi de doua ori daca aveti nevoie de unul si ar trebui sa tineti seama de urmatoarele recomandari (pe care le puteti gasii si pe MSDN):
  • Design background tasks to be short lived.
  • Design the lock screen user experience as described in the “Guidelines and checklists for lock screen tiles.”
  • Use BackgroundTaskHost.exe as the executable for background tasks.
  • Describe the background task class name or JavaScript file name accurately in the manifest.
  • Use persistent storage to share data between the background task and the app.
  • Register for progress and completion handlers in the app.
  • Register for a background task cancellation handler in the background task class.
  • Register for the ServicingComplete trigger if you expect to update the app.
  • Ensure that the background task class library is referenced in the main project and its output type is winmd.
  • Describe the triggers in the background manifest accurately.
  • Verify if the app needs to be on the lock screen.
  • Do not display UI other than toast, tiles or badges from a background task.
  • Do not rely on user interaction in background tasks.
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in windows 8 | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Service Bus Topic - Automatic forward messages from a subscription to a topic
    Windows Azure Service Bus Topic is a service that enables us to distribute the same messages to different consumers without having to know e...
  • Patterns in Windows Azure Service Bus - Message Splitter Pattern
    In one of my post about Service Bus Topics from Windows Azure I told you that I will write about a post that describe how we can design an a...
  • CDN is not the only solution to improve the page speed - Reverse Caching Proxy
    I heard more and more often think like this: “If your website is to slow, you should use a CDN.” Great, CDN is THE solution for any kind of ...
  • E-Learning Vendors Attempt to Morph Mobile
    The sign should read: " Don't touch! Wet Paint !" I had a good chuckle today after receiving my latest emailed copy of the eLe...
  • Content Types - Level 6: Rich Media
    Level 6: Rich Media NOTE: This is part 7 of 7 and the conclusion of this continuing series; please see earlier posts for more background inf...
  • Publishing our CellCast Widget for iPad
    The rush has been on this week as our development team worked to design a new version of our CellCast Widget specifically for Apple's up...
  • Content Types - Level 5: Courseware
    Level 5: Content and Courseware NOTE: This is part 6 of 7 in a continuing series; please see earlier posts for more background information. ...
  • SQL - UNION and UNION ALL
    I think that all of us used until now UNION in a SQLstatement. Using this operator we can combine the result of 2 queries. For example we wa...
  • Cum sa salvezi un stream direct intr-un fisier
    Cred ca este a 2-a oara când întâlnesc aceasta cerința in decurs de câteva săptămâni. Se da un stream și o locație unde trebuie salvat, se c...
  • Content Types - Level 4: Reference
    Level 4: Reference Materials & Static Content NOTE: This is part 5 of 7 in a continuing series; please see earlier posts for more backgr...

Categories

  • .NET
  • .NET nice to have
  • #if DEBUG
  • 15 iunie 2011
  • 15 octombrie 2011
  • 2011
  • abstracta
  • action
  • adaugare
  • ajax
  • Amsterdam
  • Android
  • aplicatii
  • App Fabric
  • Apple iSlate
  • array
  • as
  • ASP.NET
  • AsReadOnly
  • Assembly comun
  • async
  • Asynchronous programming
  • asyncron
  • Autofac
  • AutoMapper
  • az
  • Azure
  • Azure AppFabric Cache
  • Azure backup solution
  • Azure Storage Explorer
  • azure. cloud
  • backup
  • BCP utility
  • bing maps v7
  • BitArray
  • BlackBerry
  • blob
  • BlobContainerPublicAccessType
  • breakpoint
  • bucuresti
  • C#
  • cache
  • CallerMemberName
  • CellCast
  • Certificate
  • CES
  • change
  • ChannelFactory
  • clasa
  • classinitialize
  • clean code
  • click event
  • close
  • Cloud
  • Cluj
  • cluj-napoca
  • Code contracts
  • code retrat
  • codecamp
  • CollectionAssert
  • Compact Edition
  • compara
  • Comparer T .Default
  • CompareTo
  • comparison
  • comunitate
  • concurs
  • Conditional attribute
  • configurare
  • connection string
  • container
  • content type
  • control
  • Convert
  • convertAll
  • convertor
  • cross platform
  • CRUD
  • css
  • custom properties
  • custom request
  • DACPAC
  • Daniel Andres
  • data sync service
  • database
  • date time
  • datetime
  • debug
  • default
  • delegate
  • dependency injection
  • deploy
  • DeploymentItem
  • design patterns
  • Dev de Amsterdam
  • development stoage
  • dictionary
  • diferente
  • digging
  • director
  • Directory.Exist
  • disable
  • dispatcher
  • dispose
  • dropdown
  • dynamic
  • EF
  • email
  • encoding
  • entity framework
  • enum
  • enumerable
  • Environment.NewLine
  • error
  • error 404
  • error handling
  • eveniment
  • event
  • ews
  • excel
  • exception
  • exchange
  • exita
  • explicit
  • export
  • extension
  • field
  • File.Exist
  • finalize
  • fire and forget
  • Fluent interface pattern
  • format
  • func
  • GC.SuppressFinalize
  • generic
  • getdirectoryname
  • globalization
  • gmail
  • hackathon
  • Hadoop
  • handle
  • HTML
  • html 5
  • Html.ActionLink
  • http://www.blogger.com/img/blank.gif
  • HttpModule
  • IComparable
  • IE
  • ienumerable
  • IIS
  • image
  • implicit
  • import
  • int
  • internationalization
  • Internet Explorer
  • interop
  • Ioc
  • IP Filter
  • iPhone
  • iQuest
  • IStructuralEquatable
  • ITCamp
  • itspark
  • java script
  • javascript
  • July 2012
  • KeyedByTypeCollection
  • KeyNotFoundException
  • Kinect SDK
  • lambda expression
  • LightSwitch Microsoft Silverlight
  • linq
  • list
  • lista
  • lista servicii
  • liste
  • Live Connect
  • Live ID
  • load
  • localization
  • lock
  • m-learning
  • MAC
  • Mango
  • map
  • mapare
  • mapare propietati
  • messagequeue
  • meta properties
  • method
  • MethodImpl
  • Metro App
  • Microsoft
  • Microsoft Sync Framework
  • mlearning
  • mlearning devices
  • Mobile Apps
  • mobile in the cloud
  • mobile learning
  • mobile services
  • Mobile Web
  • mongoDb
  • monitorizare
  • msmq
  • multitasking
  • MVC
  • MVC 3
  • MVVM
  • namespace
  • nextpartitionkey
  • nextrowkey
  • Ninject
  • nivel acces
  • no result
  • normalize
  • nosql
  • null expcetion
  • null object pattern
  • NullReferenceException
  • OAuth API
  • office
  • offline
  • Open ID
  • openhackeu2011
  • operations
  • operator
  • optimization
  • option
  • outputcache
  • OutputCacheProvider
  • override
  • paginare
  • pagination
  • path
  • persistare
  • Portable Library tool
  • Post event – CodeCamp Cluj-Napoca
  • predicate
  • predictions
  • prezentare
  • process
  • proiect
  • property
  • propietati
  • query
  • ReadOnlyCollection
  • ReadOnlyDictionary
  • referinta
  • reflection
  • remote
  • reply command
  • request
  • request response
  • resouce
  • REST
  • REST Client
  • RESTSharp
  • ronua
  • rss
  • rulare
  • salvare in fisier
  • sc
  • schimbare timp
  • select
  • select nodes
  • send
  • serializare
  • serialization
  • Server.Transfer. Resposen.Redirect
  • service bus
  • ServiceBase
  • servicecontroller
  • sesiune
  • session
  • Session_End
  • Session_Start
  • setup
  • Sibiu
  • signalR
  • Silverlight
  • sincronizare
  • Single Responsibility Principle
  • SkyDrive
  • skype
  • smartphones
  • smtp
  • Snapguide
  • sniffer
  • socket
  • solid
  • spec#
  • sql
  • Sql Azure
  • SQL CE
  • sql server 2008 RC
  • SRP
  • startuptype
  • stateful
  • stateless
  • static
  • stergere
  • store
  • store procedure
  • stream
  • string
  • string.join
  • struct
  • StructuralEqualityComparer
  • submit
  • switch
  • Symbian
  • Synchronized
  • system
  • tabele
  • table
  • techEd 2012
  • tempdata
  • test
  • testcleanup
  • testinitialize
  • testmethod
  • thread
  • timer
  • ToLower
  • tool
  • tostring
  • Total Cost Calculator
  • trace ASP.NET
  • transcoding
  • tuplu
  • tutorial
  • TWmLearning
  • type
  • unit test
  • unittest
  • UrlParameter.Optional
  • Validate
  • validation
  • verificare
  • video
  • view
  • ViewBag
  • virtual
  • visual studio
  • VM role
  • Vunvulea Radu
  • wallpaper
  • WCF
  • WebBrower
  • WebRequest
  • where clause
  • Windows
  • windows 8
  • Windows Azure
  • Windows Azure Service Management CmdLets
  • windows live messenger
  • Windows Mobile
  • Windows Phone
  • windows service
  • windows store application
  • Windows Task
  • WinRT
  • word
  • workaround
  • XBox
  • xml
  • xmlns
  • XNA
  • xpath
  • YMesseger
  • Yonder
  • Zip

Blog Archive

  • ►  2013 (139)
    • ►  November (17)
    • ►  October (12)
    • ►  September (10)
    • ►  August (7)
    • ►  July (8)
    • ►  June (15)
    • ►  May (12)
    • ►  April (17)
    • ►  March (16)
    • ►  February (9)
    • ►  January (16)
  • ▼  2012 (251)
    • ►  December (9)
    • ►  November (19)
    • ►  October (26)
    • ►  September (13)
    • ►  August (35)
    • ►  July (28)
    • ►  June (27)
    • ►  May (24)
    • ▼  April (18)
      • Directory.GetFiles - odd result
      • WIndows 8 versions
      • How to integrate Facebook in a Windows 8 Metro Sty...
      • DataContract and XMLIgnore attribute
      • Cannot serialize member ... because it implements ...
      • Bug on Windows Phone 7 Exchange Client Automatic R...
      • Windows Azure Media Service - Overview
      • DB error not handled by the web application
      • ITCamp 2012
      • "This Week in mLearning" Podcast: Week #2
      • Background task in Windows 8 Metro Style App
      • URI in Windows 8 Metro Style App
      • How to read/write data from Windows Metro Style App
      • VS2011 BETA: Error : DEP3000 : Attempts to stop th...
      • Dependency Injection framework for WinRT - Widows ...
      • Manifest refereces file 'Bing.Maps.dll' which is n...
      • Luni 09.04.2012 - Emisiune live despre Windows Azure
      • New Podcast - "This Week in mLearning"
    • ►  March (17)
    • ►  February (20)
    • ►  January (15)
  • ►  2011 (127)
    • ►  December (11)
    • ►  November (20)
    • ►  October (8)
    • ►  September (8)
    • ►  August (8)
    • ►  July (10)
    • ►  June (5)
    • ►  May (8)
    • ►  April (9)
    • ►  March (14)
    • ►  February (20)
    • ►  January (6)
  • ►  2010 (26)
    • ►  December (1)
    • ►  November (1)
    • ►  October (1)
    • ►  June (2)
    • ►  May (1)
    • ►  April (4)
    • ►  March (1)
    • ►  February (1)
    • ►  January (14)
Powered by Blogger.

About Me

Unknown
View my complete profile