• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Smartphone Challenge: Guidelines for development of network friendly applications
 

Smartphone Challenge: Guidelines for development of network friendly applications

on

  • 3,161 views

 

Statistics

Views

Total Views
3,161
Views on SlideShare
3,152
Embed Views
9

Actions

Likes
2
Downloads
0
Comments
0

2 Embeds 9

http://paper.li 8
http://lanyrd.com 1

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Smartphone Challenge: Guidelines for development of network friendly applications Smartphone Challenge: Guidelines for development of network friendly applications Document Transcript

    • GSM Association Non ConfidentialOfficial Document <WG.NN> Smartphone Challenge: Guidelines for development of network friendly applications Version 0.1 21st September 2011This is a Non Binding Permanent Reference Document of the GSMA.Security Classification – NON CONFIDENTIAL GSMA MATERIALCopyright NoticeCopyright © 2011 GSM AssociationAntitrust NoticeThe information contain herein is in full compliance with the GSM Association’s antitrust compliance policy.<V0.1> Page 1 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>Table of Contents 1  Introduction 4  1.1  Overview 4  1.2  Scope 5  1.2.1  Who should read this document 5  1.2.2  Organisation of the document 6  1.3  Definition of Terms 6  1.4  Document Cross-References 6 2  Network friendliness 7  2.1  Constraints in mobile broadband 7  2.2  Smooth user experience 8  2.2.1  Asynchrony 8  2.2.2  Non-blocking user interface 9  2.2.3  Offline mode 11  2.2.4  Bandwidth awareness 11  2.3  Efficient network connection usage 11 3  Ideal mobile application 15  3.1  Asynchrony 15  3.2  Connection loss and error handling 15  3.3  Caching 18  3.4  Security 22  3.5  Efficient traffic usage 24  3.5.1  Cloud-based transformations, 24  3.5.2  Media Transcoding 25  3.6  Compression 26  3.7  Background / Foreground modes 27  3.8  Application Scaling 29 4  Detailed Recommendations 30  4.1  iOS 30  4.1.1  Asynchrony 30  4.1.2  Connection loss and error handling 31  4.1.3  Caching 32  4.1.4  Security 34  4.1.5  Data formats 35  4.1.6  Compression 37  4.1.7  Background / Foreground modes 37  4.2  Android 40  4.2.1  Asynchrony 40  4.2.2  Offline mode 43  4.2.3  Caching 44  4.2.4  Security 46  4.2.5  Data formats 47  4.2.6  Compression 48  4.2.7  Background / Foreground modes 48  4.3  Windows Phone 49  4.3.1  Asynchrony 49  4.3.2  Connection loss and error handling 54  4.3.3  Caching 57  4.3.4  Security 58  4.3.5  Data formats 59  4.3.6  Compression 59  4.3.7  Background / Foreground modes 60 <V0.1> Page 2 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>5  References 61 Document Management 61  Document History 61  Other Information 61 <V0.1> Page 3 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>1 Introduction1.1 OverviewThe unexpected explosion in the use of data connectivity has taken key industrystakeholders by surprise, in particular network operators who are at the forefront ofdelivering services to customers. This is good news for the industry as a whole as a newdawn of growth and development is at last on the horizon.Nevertheless, the good news is marred by a number of challenges facing network operatorsin sustaining the anticipated growth.A consequence of this success is a greatly increased signalling load at the network levelcompared with a relatively low amount of data traffic. End-users and application developersare impervious to the network’s increased signalling load as it is only visible to networkoperators/service providers. Nevertheless, a great majority of smartphone users experienceless than desired overall user experience in terms of rapid battery drainage, unresponsiveuser interface with seemingly slow network access, non-functional applications, etc.With the launch of 3rd generation cellular networks almost 10 years ago, most industrypundits were toying with a variety of ideas to explain what the possible killer applicationwould be (beyond mobile voice call). However this killer application failed to emerge andinstead the focus shifted to identifying a collection of services that it was hoped would inturn deliver truly compelling mobile applications.Around the same time the term ‘smartphone’ was coined by the mobile industry: a phonesufficiently smart and intelligent that it would be able to act as a Personal Assistant (PA) tothe user by offering a variety of data based services all available at the push of a button.However the failure to deliver on this promise lead to some scepticism from industrycommentators at the time.Nevertheless internet connectivity on notebooks/laptops has increased markedly over timeto the extent that network operators were convinced they would deliver the right level ofincrease in data connectivity for the mobile industry. That meant tuning the mobile networkto cater for browser based internet connectivity and mobile email applications (which do notplace a heavy burden on the mobile network in terms of signalling).More recently the emergence of popular smartphones has posed a challenge for the mobilenetwork as the network signalling load that they generate is significantly higher. This isdriven by a number of factors, one of which is that all aspiring enthusiasts (perhaps with abackground in developing desktop applications) to develop their ideas into networkunfriendly applications that can be easily installed on smartphones.As a result, a key symptom driving change in the industry’s landscape is the unprecedentedsignalling load faced by network operators which is out of proportion to the level of datausage and the generated revenue.Subsequently, the industry has responded by introducing the ‘fast dormancy’ concept in linewith the 3GPP standard where the handset is allowed to determine its own sate and requestits release of the network connection. This has been implemented in what is known as3GPP release 8. However, fast dormancy can be used intelligently to ensure optimum useof the functionality.In addition to using fast dormancy intelligently there are a number of other aspects relatingto the development of network-friendly smartphone applications that need to be considered: a) Optimal use of target platform functionality by 3rd party developers  Leads to better bandwidth usage b) Competent development of 3rd party applications that are user and network friendly<V0.1> Page 4 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>  Provides a much improved user experience that is optimal to the target platform and cellular connectivity including efficient battery usage c) Identifying gaps in smartphone software platforms  To improve performance in terms of network/user friendlinessThis document will focus on items ‘a’ and ‘b’, where a number of key concepts in applicationdevelopment for mobile terminals are explored and pitfalls identified in general terms as wellas per target platform. The study covers iOS, Windows Phone and Android.1.2 ScopeThis document is meant to provide as much information as possible to encourage a betterapproach in developing mobile applications that work with network.In writing the document, popular applications on 3 leading mobile platforms and theircommon use case scenarios have been analysed, focusing on bottlenecks and commonmistakes. The outcome has been aggregated with a view to developing generic architecturalguidelines and recommendations on best practices. The document attempts to increaseawareness of specifics of mobile networks and explain why network applications aredifferent to those which work with local data and why developers should take extra careworking with the cellular network. In addition, specific recommendations are made for eachplatform under consideration.By following the guidelines and recommendations in this document developers are betterequipped to create fit-for-purpose applications; mobile operators will see a reduced strain onnetwork overload and end users will experience more responsive and reliable applications.Developing network efficient applications will benefit developers by: - Improving the overall user experience of network applications, particularly, making them more responsive, providing more control to users - Improving reliability in the unreliable mobile network environment - Providing better user satisfaction by reducing consumption of traffic, which can result in lower customer bills; and also improved battery life of the deviceThe scope of the detailed recommendations is limited to the three platforms, namely iOS,Android and Windows Phone 7. However, the theoretical part of Sections 3 and 4 aregeneric; they can be applied to any platforms.It is worth noting that the document does not cover: - Generic user interface guidelines - Device security - Back end implementation - High level of security which is required in rare cases for specific applications such as banking or enterprise systems - Web applications (HTML 5)1.2.1 Who should read this documentThe document does not explain the basics of developing of mobile application and it isaimed at developers who are able to develop or intend to develop network dependantapplications. The recommendations in Chapter 4 “Detailed Recommendations” are meant toimprove quality of applications relying on cellular network connectivity and how to overcomechallenges that mobile networks introduce.<V0.1> Page 5 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>1.2.2 Organisation of the documentSubsequent chapters are organised in the following order. Section 3 provides the relevant background and lays down the fundamental concepts of the mobile network constraints that are generic to all platforms. Section 4 will follow the theme by considering what an ideal application/platform should be in terms of its characteristics to ensure it is user and network friendly. Section 5 will map the outcome of all preceding chapters to target platforms where specific functionality or limitations are highlighted to assist developers.1.3 Definition of TermsTerm Description1.4 Document Cross-References DocumentRef Number Title<V0.1> Page 6 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>2 Network friendlinessNowadays, regardless of different technology standards, the underlying technologiessupport packetized data connectivity and increased data bandwidth for consumers.Commonly known as mobile broadband the available bandwidth can range anythingbetween around 9.6kb/s and up to 14.4 Mb/s downlink. However, despite the increasedbandwidth mobile networks differ from broadband in most cases – they are less reliable andhave limited variable bandwidth, higher latency, and a non-permanent communicationchannel. Loss of connectivity to the Internet is considered as the normal situation. Batteryresource is precious and continuous use of the network reduces the operation time ofdevices dramatically.By contrast, fixed line broadband connectivity based on cable-modem or ADSL/DSLtechnologies is well established. It provides a consistent data connection of up to 50 Mb/sdownlink due to deploying relatively less complex technologies and the limited terminalmobility it offers.Mobile networks in comparison to the fixed broadband lines, have their own specificrequirements and constraints that should be taken into account at the design anddevelopment stages. These constraints are described in the following section.2.1 Constraints in mobile broadbandThe very nature of mobile broadband access imposes a number of constraints on themanner in which it may be used.  Limited bandwidth: Available bandwidth for cellular networks may vary depending on the geographic coverage and underlying technologies used. On average it is much lower than Wi-Fi connections. When on the move, the bandwidth can dynamically step down.  Data is not always free: Mobile data traffic can be expensive particularly when roaming. It may mean high bills for the consumers, thus requiring careful consideration in any service deployment.  Battery life: Mobile terminals, although small, are a feast of technologies miniaturised into a small physical space powered by a battery. When in full operation, it runs not only a processor with an active screen, but also data communication over cellular network that can significantly impact the battery life. Transferring large amounts of data via cellular network puts the radio access into high drive mode; it can drain the battery fully in collaboration with the active colour screen in matter of few hours. The more careful the use of network, screen and processor resources, the longer a device can be used on a single charge.  Network reliability: Mobile cellular networks cannot by nature guarantee reliable connectivity at all times. This is mainly due to blind spots in mobile coverage and the limitations of deployed technologies, in particular when the user is on the move. Roaming between cells or moving in heavily built up areas can result in lost packets, increased latency, reduced network speed, often losing connectivity completely. However these are simply a normal part of a mobile terminal’s daily usage patterns.  Security: As users do not always have direct control over their wireless networks, they can be connected to public Wi-Fi hotspots or even to spoofed networks, meaning that user’s privacy can be compromised or identity stolen. Hence, developers should not assume that wireless networks are secure. Authentication, secure protocols and a cautious approach to content transmission should be adopted in all development.<V0.1> Page 7 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>When network communication is optimized, the overall user experience is greatly improvedand therefore all possible methods of optimal data transmission should be adopted (efficientprotocols, caching, compression, data aggregation, etc.).Although many customers have access to more reliable Wi-Fi networks at home, work orpublic places, the primary access to the Internet is via cellular network. Developers often donot take this into account and do not perform field testing of their applications, hopinginstead that customers will find a reliable connection somehow. Development in simulatedenvironments running on fast and well connected laboratory machines may never uncoveruse cases experienced in real life and therefore day to day testing on a device connected tocellular network is essential.2.2 Smooth user experienceAlthough, network efficiency may be understood as an efficient usage of traffic, it is alsoimportant to pay attention to the reality of mobile devices and mobile networks. In particularit is a common experience that the connection can be lost or data transfer delayed. Theuser experience of network friendly applications should be adjusted accordingly with theview to smooth the impact of such problems.2.2.1 AsynchronyThe first assumption to be made is that any response in mobile network might be delayed ornot delivered at all. To ensure a smooth user experience, an application’s architectureshould not solely rely on a sequence of responses, but be ready to deliver results to the enduser even if not all the data has arrived.To explain the problem in general terms, consider the simple example of a basic item listwhere thumbnails are used to show how network requests can be handled. Figure 1 showsthe sequence of requests required to download if all requests had been madesynchronously: Figure 1 – Synchronous requestsIn this example the list contains 3 items with a thumbnail image for each item.If the same requests were sent in parallel, then the timeline will be as shown in Figure 2: Figure 2 – Asynchronous requestsShould the network connection be reliable with constant speed, the end user will not noticethe requests had been sent in parallel. The overall loading time will not show a tangibledifference. However, such an arrangement can only exist in ideal networks where nolatencies and connection interruptions are prevalent.<V0.1> Page 8 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>In reality however, the same sequence can result in the arrangement in Figure 3, where animage that has been requested earlier may be received much later and some requestsmight not receive any responses at all. Figure 3 – Asynchronous requests in realityIf an application waits to receive every single response and does not progressively showresults to the end user before completion of the entire cycle (as described above), it is clearthe user might not see anything whatsoever, facing a blank page instead.This simple example demonstrates a few important considerations that should be taken intoaccount when architecting applications that rely on mobile network connectivity. 1. Network connections should be arranged in an asynchronous manner; meaning they should not be in the same thread with user interface. This separation will ensure that delayed responses will not block the user interaction entirely. 2. Where possible, the end user should see the progress of data loading. This could be done by using progress bars, placeholders or a simple network indicator. In our example, text information can be displayed already when the list is loaded without waiting for images to arrive. As soon as an image is loaded it can be displayed immediately (see Figure 4 below) Figure 4 – Timeline of asynchronous request 3. Applications should assume that any of the requested responses may fail to arrive and an appropriate user interface should keep the user informed of the progress in a manner that softens the impact without appearing as if the software has crashed or hung.2.2.2 Non-blocking user interfaceA blocking User Interface (UI) is an instance of user interaction where the user is faced witha single UI element while all other functionality is disabled. These normally pop up from an<V0.1> Page 9 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>application as soon as there is a delay in receiving relevant data, or when the applicationlogic’s decision tree is unable to proceed because it has encountered a missing data item.However, in reality there are a very few cases where the network interaction should blockthe user from initiating any other operations. For example, when on a login page, a usercannot progress any further until access is granted. However, even here it should bepossible to cancel signing in if a mistake has been spotted in the entered data (or pass thecontext to another application such as the phone dialler).In most cases, network operation should be completed in the background, allowing user tocancel or switch to other views. It is inappropriate to allow a web browser to block thescreen with the message “Loading” until the whole page is loaded. Figure 5 – Non-blocking user interface examplesWhen designing an application’s UI and its decision making tree it is important to distinguishbetween a user initiated network connection and that of performing a secondary functionthat is not explicitly requested by the end user. This may define how user should be notifiedof the progress and errors relating to the operation.For example, if the user requests a web page to be loaded and the browser fails to connectto the server, then a modal error message should be displayed. However, if a secondarycontent such as image has not been delivered, then there is no point in showing a modalerror message for each picture item, it would be more sensible to show placeholders withbroken images instead.Another good example of showing unhelpful error messages is that of untimely and out ofcontext error messages, something that appears in some offline games. Whenever, thesegames are launched with no network activity, an error message is often shown that reads“Could not connect to server”, probably as a result of failure to send game statistics back tothe server. The user is not even waiting for any result from server at this point in time andany untimely, irrelevant message can create an unnecessary break in the user experience.<V0.1> Page 10 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>2.2.3 Offline modeThere are many occasions when a mobile terminal cannot be connected to the network forsome reason. As a developer, it is important to factor in the following problems in thearchitecture design: 1. On loss of network connection, the end user should understand the reason why an operation could not be completed. 2. To prevent data loss (due to limitations of devices and networks), it is very important to provide functionality to save the current data with the option to retry/resume the activity at a later time. - Examples of user disappointment include losing long text string that had been typed on a small mobile keyboard when it is clear the application cannot send the text to the server; or when, after downloading a huge chunk of data, it is not possible to resume downloading and the whole process needs to be started all over again. 3. The user should be notified of any functionality that is not available in the offline mode. 4. It is far more desirable to allow users, if possible, to continue using an application with data stored in offline mode for later synchronisation when network connection has reestablished. 5. The application can also scan for data connectivity in background mode without affecting operation in offline mode.A number of mechanisms are proposed in this document as possible solutions foraddressing the issues highlighted above.2.2.4 Bandwidth awarenessApplications with excessive network dependency, such as audio or video streaming, requirean assured level of data transmission speed. Considering that a variety of wirelesstechnologies such as GPRS, EDGE, 3G or Wi-Fi may be in use, it would be sensible tocheck first what underlying carrier is in use in order to request an appropriate quality ofcontent from the server; and notify user about the possible additional cost of using mobiledata. If the application needs a more precise estimation of speed, then it would bereasonable to measure or dynamically adjust the quality of streamed data according tolatencies.Furthermore, the application should be capable of monitoring changes to carrier and dataspeed at any given time, due to, for example, users leaving a Wi-Fi Hotspot or a cellularhandover such as 3G to GPRS taking place due to poor signal quality.2.3 Efficient network connection usageWe have already highlighted the constraints and limitations of wireless technologies.Operating within these limitations means the frugal use of data upload/download that alsohas a monetary impact when roaming.An obvious limitation to bear in mind of is the amount of data transferred which impacts onthe cost of the data plan, especially in roaming, user experience responsiveness and batterylife. Any optimization of traffic will be appreciated by end users, so double check if allnetwork transfers are really necessary, protocols are chosen optimally and that caching isused appropriately.Apart from data traffic, there are a few hidden pitfalls in the 3G network that may causeadditional inconveniences. These lie in the implementation of Fast Dormancy which tries to<V0.1> Page 11 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>minimise network signalling and battery consumption, both important problems given theincreasing number of smartphones and online applications.When a device requests sending/receiving data over the cellular network, it switches into adedicated channel state that consumes about 60-100 times more power compared to theidle mode. However, the process of switching between states requires sending networksignals that also take a certain amount of time. For example, switching from Idle toDedicated Channel (DCH) should exchange 24-28 signals taking about 2 seconds. The costof switching between states excludes the option of disconnecting the device immediatelyafter finishing every network connection. Keeping the device in a high power state also isnot an option as it will drain the battery rapidly.Between the Idle and Dedicated Channel states there are few more states that come intouse. Fast dormancy technology defines an algorithm that dictates when a device can beswitched to lower state after the last data transmission. Figure 6 below shows how thepower drops after a certain period of inactivity in data transfer. Times T1 and T2 are networkdependent. Figure 6 – Power Consumption – Example 1<V0.1> Page 12 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>Once the state has switched to the lowest, establishing a new data connection will need toexchange about 24-28 signals with the network which takes about 2 seconds.Considering this behaviour we can consider the case when the application has many shortconnections over a specific period of time: Figure 7 – Power Consumption – Example 2Areas filled in red in Figure 7 shows the overhead in battery usage compared to thescenario presented on Figure 8 where all data connections were synchronised andcompleted in the same time. Figure 8 – Power Consumption – Example 3Although, most the timers and conditions of switching between the cellular states arenetwork dependant, it is good to know to at least example of approximate characteristics.According to tests that have been done by XMPP,<V0.1> Page 13 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN> - Dedicated channel (the highest level) consumes about 380mA which can drain average Android device or iPhone battery within less than 4 hours. Time before dropping to lower state is ~8 seconds - FACH (shared channel – intermediate level) consumes about 140mA. In order to keep this state and prevent switching into the higher power mode, the packet sizes must be around 128 bytes and after deducting TCP and TLS overheads it leaves only about 70 bytes of actual data. Timeout before switching to lower state is around 8 seconds. Battery life can reach maximum 7 hours in this mode.In summary, the general recommendation for developers is to transfer data in one go anddo not spread network activities, whenever it is possible.ReferencesXMPP on Mobile Deviceshttp://xmpp.org/extensions/xep-0286.html#sect-id115219<V0.1> Page 14 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>3 Ideal mobile applicationWe have already established the type of constraints that mobile applications encounter,where all critical resources (such as battery, memory and processor) have certain limits.However, key generic characteristics of functionality or use case scenarios have yet to bedefined; a topic which is addressed in subsequent sections.3.1 AsynchronyThe concept of asynchrony has already been introduced briefly in chapter 3. There are 2main aspects to asynchronous network connections: 1. Network connections should not block the main thread responsible for handling user interface and system events. 2. If network requests do not depend on each other, they should be handled in parallelAsynchronous networking would always imply separate threads; although it makes trackingof results and the state of an application non-trivial. This drawback, however, is wellunderstood and competent solutions are still provided.The architecture of applications is driven by the APIs that platform vendors provide. To agreat extent, the quality of most application implementations is dependant on the platformvendor’s level of generic API support and optimization at a platform level. For example,creating separate threads and managing them effectively should already be part of theunderlying features of a target platform to allow the developer to save time and effort in notreinventing the wheel.In this context the ideal APIs should have the following features:  Creation and management of the network connections can be done from the main thread; however, the calls can lead to separate threads that are managed by framework transparent to user  All changes of states, received data, errors and timeouts are event driven  The connection can be cancelled at any time  The design of APIs allows the simple management of several connections at the same time.Developers are recommended to establish connections within a single connectivity sessionwhenever it is possible to avoid loosing dedicated channel state, which is described inSection 2.3. This would reduce network signalling and depending on the communicationpattern there can be a significant impact on a device’s battery life.3.2 Connection loss and error handlingMonitoring connectivity status and error handling are extremely important as mobilenetworks are by definition unreliable.Most platforms provide information on current connections. It is essential to check if thedevice is connected at all (e.g. not out of network coverage). Sometimes it becomesnecessary to identify the type of connection: cellular mobile network or, for example, Wi-Fi.Although the actual bandwidth can not be predicted precisely (as it depends on manyfactors, like signal strength, current network load, etc.), developers may assume that:  Wi-Fi networks are generally faster than cellular mobile networks  Traffic over Wi-Fi is relatively cheaper in comparison, or can be absolutely freePrior to commencing any network connectivity, it is worth checking if the device isconnected at all, and if it is important, check what is the type of the current connection. If the<V0.1> Page 15 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>device is not connected, then the application can switch to offline mode and let the userwork with cached data only. This would avoid handling inevitable network exceptions andnotifications for each network error; the overall user experience can be much smoother ifthe user can avoid constant error messages. However, if the application switches into offlinemode, it would be good to monitor the device connectivity status and as soon as the devicegets connected, the application can switch back into online mode. If there is any data tosynchronize between the server and client, the synchronization can be initiated at that pointRequest typesWhen establishing the connection, different approaches can be used to display the activityto users and determine how to handle network problems should they happen. Networkrequests can be identified as user initiated if it is going to deliver the main information thatuser had requested. User initiated network requests can also be considered as primary.Non-user initiated requests are those that are created by scheduled activities or triggered bya change in a system state, such as geo-location tracking and sending usage statistics to aserver.Secondary requests usually occur from the result of the primary request and do not bringany critical information to the user. Examples of secondary requests could be thumbnails ina friends list (list of names is critical), stylesheets or images in web page.CancellationIdeally, the user should see the progress or an indication of the primary request’s progress.It is also sensible to make the primary request cancellable, but it depends on the nature ofthe content and how it is displayed in the user interface.As a general rule if it is possible to perform any other operations on the same UI screen, it isa good practice to ensure ‘cancel’ is available as an option to terminate the request.A good example when cancellation improves usability is the web browser, which is justanother network-enabled application. A user can load different web pages on the samescreen, so if loading of one page takes too long or there was a mistake in entering theaddress, the user can always cancel the request and open different web site.When the primary request is cancelled then subsequently all secondary requests should beautomatically cancelled as well.Error handlingMobile applications should always be prepared for handling situations when networkrequests fail. Most probably any secondary requests can fail without a major impact on theuser experience. Sometimes it is appropriate to indicate subtly in the UI that information forsecondary request can not be delivered, such as broken image placeholders in webbrowsers or silhouette images in a contact list.When a primary request fails, it means that the main functionality can not be completed andthis is where error handling becomes important for the user experience.As proposed earlier, it makes sense to distinguish between a user initiated request andnon-user initiated (scheduled). If the request was user initiated and the information isexpected to be delivered as soon as possible (lets say within 1 minute), then errornotification can be done in a modal error notification with options ‘Retry’ or ‘Retry later’ ifappropriate.If a request is supposed to take longer time, and the user expects it to be guaranteeddelivery at any time later, for example, downloading music, downloading an electronic bookor a digital issue of a magazine, then in case of network failure, the application canautomatically try to reestablish the connection and if 3-5 attempts have failed, then therequest can be suspended (but not cancelled) with an option for manual resume later. It is<V0.1> Page 16 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>also important to not lose any downloaded data and to be able to resume the downloadfrom the place where it has stopped rather than starting from scratch.Retry mechanisms can vary and depend on importance and volume of downloaded data.Possible solutions can be: 1. Simple counting of failed attempts since the connection was first established (often the easiest solution). 2. The number of failed attempts within a certain period of time. For example, if the connection is lost more then 5 times within the last hour, then the request can be suspended. This can be a more reliable technique to avoid short but regular network problems, for instance, when a device is moving away from one network cell to another the connection can be lost when it switches between cells, but when the cell is providing good coverage, the request can be processed successfullyIf the request is not user initiated then error notification can be either non-modal with a retryoption or not shown at all. But, if the request is scheduled and repetitive, then it would makesense to change the interval dynamically to avoid reestablishing connections too frequentlyduring network loss over a long period of time. Recommended retry intervals are 1 minute,then 5 minutes and then 15 minutes. More frequent retries will drain the battery very quickly.Resuming large downloadsThe HTTP protocol supports requesting parts of files that can be used for resumingdownloads. If the server supports it and the content can be returned split (i.e. content is notdynamic), then the server may include HTTP Header as described in sections 14.5 and 3.12of RFC2616: Accept‐Ranges: bytes  Having this indicated, the client can send subsequent requests for part of the file specifyingrange what shall be downloaded, for example, to download first 500 bytes: Range: bytes=0‐499  Or for segment starting from 9500th byte: Range: bytes=9500‐  An HTTP response with partial content should have HTTP Status 206 (Partial Content) if therequested range is correct, otherwise, there will be status 416 (Requested range notsatisfiable). See Section 14.35 of RFC2616 for more details.Section 3.3 below describes how the verification of cached version can be done in HTTPusing ETag; and it is also possible to retrieve partial content with preceding verification ofthe content version by HTTP request header If-Range, as specified in Section 14.27 ofRFC2616. The idea is that the value of header If-Range should contain ETag value and thesame request should also have a Range header specifying what part of content is to be<V0.1> Page 17 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>received if ETag is valid. If server verifies ETag, then the partial content should be returned,otherwise, the full version of the updated content will be sent.Though the client can also use Range header with conditional headers such as If-Unmodified-Since or If-Match, if the condition fails then client should handle the HTTPstatus code and a new request for retrieving the updated content. If-Range header can helpto do this in a single request using either ETag or last modified date.Support for resuming downloads is extremely important for large content transfers on mobiledevices, especially with the growing number of tablet devices, where quality of content isrelatively high for a big display size. For instance, a single issue of a digital magazine canbe 200-400 Mb and it would be incorrect to redownload the whole file if the network failsafter downloading several hundreds megabytes of data.The following summarises the topics discussed thus far: 1. Check connection availability. 2. In offline mode use cached data. a. For any outgoing request that includes user-entered data the data should be saved locally and an attempt made to deliver to the server. b. If it fails to deliver the request, then the user should be asked if the request shall be retried or retried later (with permanent saving in case the application is terminated). 3. If the primary request is done in online mode, then it should be displayed with a progress indicator and if it fails then the user should be notified a. If the primary request is supposed to take more than 1 minute and the user expects to get the result however long it takes (download application, song, new magazine issue, e-book, etc), then automatic retry should be implemented. b. If several consecutive retries have failed, then manual retry can be implemented c. It is good to indicate the progress of secondary requests, however, failure of them is not important and can be displayed only as a special placeholder (broken image placeholder for instance). d. If the request is user initiated then error notification can be modal. e. For repetitive scheduled requests, the retry interval should be dynamically increasing during long periods of network loss.3.3 CachingThe main idea of any caching is using more effective means of storage or transfer in orderto decrease the amount of data stored or transferred via slower channels. For networkapplications and especially in mobile networks, the cache becomes an essential part.However, there are a few common challenges relating to the overall reliability of the solutionand ensuring the delivery of up-to-date information to the user.<V0.1> Page 18 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN> Client Network Server 1 2 3 Local cache Server cache Server Figure 9 – CachingAlthough the entire client/server solution may contain many different levels of cache,generally two categories are supported: local cache and server cache. Local cache is usedto minimize the number of network requests and increase the speed of displaying results.The server cache works together with the local cache in order to decrease the amount ofdata transferred via the network, whilst ensuring that the user gets the latest version of theinformation.The diagram above shows the journey of a regular request from a mobile client to a webserver: 1. On the first stage the client checks if the requested content is stored in local cache and if it is still valid. If the content is valid, then the data goes back to the user immediately without sending any requests to the network. 2. If the local cache contains data but needs validation, then the client includes a version or checksum or the last modified date of the content that client already has. If server can not find any newer version of the content, it notifies client that the local version can be used without sending the whole file over the network. 3. If there is no local version of the file, or the data is not up-to-date, then the server sends the latest version over the network. With proprietary implementations (depends on the nature of the requested data), it might be possible to send only changes to the local version.When an application is being designed, it is worth defining what types of content are goingto be used and specify the caching strategy accordingly:  Content can be cached without further validation. For example, if content has a unique identifier and can not be modified on server side, such as static photos in user albums (usually new photos can be added or old photos deleted, but not modified).  Content can be cached locally, but needs validation with the server. A good example is the user’s profile or profile picture which usually does not change very often but occasionally may be updated.  Content can not be cached at all. Examples: audio streaming, chat, etcDepending on the privacy of the content and security of local storage, some cacheablecontent shall not be kept on device.Local caches face the following problems:  Size limitations – Device storage is always limited and depending on the application or the data, the cache should be limited to the corresponding size. Sometimes, it may worth giving user an option to define cache size.<V0.1> Page 19 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>  Invalidation of content – Usually web content has expiration date that can be defined by server; however, it also can be defined manually depending on the nature of the data.  Prioritisation of content – As the storage is limited and eventually cache will be filled to its limit, new entries in the cache should replace old ones with the lower priority. The cache storage may have different strategies for this – removing the least frequent used, the oldest or the biggest entries.With HTTP version 1.1 the cache control became part of the standard and is well describedin section 14.9 of RFC2616, which sets out the options for defining if content can becached, the expiry date and the versioning of the content.The HTTP protocol defines a mechanism for checking if the client’s cache has the sameversion as the server. If the server recognises that the client has the up-to-date version ofthe requested data, then the response will consist only of HTTP headers and the wholecontent is not sent which can considerably reduce the network traffic.The general idea is that on the first request the server sends a response with an additionalheader that can indicate the version of the content. The second request already comes fromthe client with information about the version to the server and if the server does not haveany updates to it, it replies with HTTP Status Code 304 (Not Modified), or, otherwise, itsends the full content with the new version indication.The version can be indicated simply by the last modified date in the Last-Modified HTTPresponse header (See Section 14.29 of RFC2616 for more details). The consequentrequest should come with HTTP request header “If-Modified-Since”, as defined in Section14.25 of RFC2616 or “If-Unmodified-Since”, as defined in Section 14.28 of RFC2616.ExampleFirst request: GET /image.png HTTP/1.1 Host: www.example.com Connection: keep‐alive  First response: HTTP/1.1 200 OK Cache‐Control: max‐age=31536000 Content‐Type: image/png Date: Mon, 21 Feb 2011 12:41:47 GMT Expires: Tue, 21 Feb 2012 12:41:47 GMT ETag: "11f‐49bc3eabc9c80" Last‐Modified: Tue, 08 Feb 2011 11:47:46 GMT Content‐Length: 28702 Connection: Keep‐Alive  <V0.1> Page 20 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>Consequent request: GET /image.png HTTP/1.1 Host: www.example.com If‐Modified‐Since: Tue, 08 Feb 2011 11:47:46 GMT Connection: keep‐alive  Response: HTTP/1.1 304 Not Modified Date: Mon, 21 Feb 2011 12:44:07 GMT  This example shows that consequent requests can produce huge savings, in this case itresponded only with short headers that are less than 1KB rather than 28KB of actualcontent, and it also gives reliability in delivering up-to-date content, so if the server hadmore recent copy of the picture, then, instead of 304 HTTP status, it would reply with 200status and the full content.Content can also be marked with ETag (entity tag) (see Section 3.11 of RFC2616) and theymust be unique across all versions of all entities associated with a particular resource.When ETag is received from the server, then the client can use HTTP request headers:  “If-Match” [RFC2616 section 14.24] – to deliver only the version that is requested, otherwise HTTP Status Code 412 (Precondition Failed) is returned  “If-None-Match” [RFC2616 section 14.26] – to deliver only if the server has any other versions other than the client has, otherwise HTTP Status Code 304 (Not Modified)  And “If-Range” [RFC section 14.27] – to deliver part of file (using Range header) only if ETag matches, otherwise the whole file is delivered.Taking the same example, it can be seen that the first response also includes ETag, so theconsequent requests either contain either only one condition or both conditions for ETagand last modified date, for example:ExampleConsequent request: GET /image.png HTTP/1.1 Host: www.example.com If‐None‐Match: "11f‐49bc3eabc9c80" Connection: keep‐alive  <V0.1> Page 21 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>Response: HTTP/1.1 304 Not Modified Date: Mon, 21 Feb 2011 12:44:07 GMT  3.4 SecurityAlthough many aspects of security apply to both mobile applications and mobile platforms,this section is meant to bring to attention aspects of Network Security, covering secure dataexchange between mobile device and cloud web services. The key aspects are mainly:  Classification of information  Authentication of users on Web Services  Secure data exchangeThe following aspects of security have to be always taken into consideration by solutiondesigners, but they are out of the scope of this document:  Device Security o Aspects of device access security, such as device unlock and remote wipe of storage in case of device loss  Content protection o Access control to users personal data including Personal Contact Information, Address Book, Call History, SMS Messages, Mobile Wallets, Current Location, Passwords, VPN keys, etc.  Encryption of locally stored data o Protection against attacks o Considering Internal and External factors, damage caused by malicious software and virusesClassification of informationWhen designing network enabled applications, it is important to understand user concernsin regards to the data the user consumes or shares with the cloud. In a simplistic way thedata is classified as:  Public – information which is freely available in the Internet, can be found by other users and cannot be associated with a particular user.  Private – the data which can be somehow associated with the user, leading to compromised security.Below is the list of some examples supporting the above definitions:  Use case #1: Application provides read-only access to the information which can be easily found in the internet by other users. Classification: Public  Use case #2: Application presents the same information as in Use Case #1, but some feedback is collected and stored in the cloud. This can be customer preferences, history of articles viewed, user comments or rating of the content. Classification: Private – as data associated with the user can be potentially used against him. The same data can be classified as Public in case it is anonymized –<V0.1> Page 22 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN> this however, must be made clear to the user. User consent is required in both cases.  Use case #3: Productivity application, such as "TODO list", synchronizes data to the cloud. Classification: Private – user could store sensitive information in the application, such as holiday dates, which can potentially indicate presence of user in his home. User consent is required  Use case #4: Messaging application; Social networking application Classification: Private – user can exchange sensitive information which could potentially compromise his security. User consent is required in this caseWhen the data flow and sensitivity of transferred information is understood it is a good timeto estimate the impact on the user in case of establishing monitoring ("Sniffing") of suchtraffic by an unauthorized party. Sniffing of user traffic may occur on Internet connectionsprovided by public Wi-Fi access points, those provided by small businesses, or can evenhappen in unregulated corporate environments. It may take seconds for an intruder tointercept the Authentication token of application’s communication channel and impersonatethe user. A number of examples of such intrusions can be found on YouTube, such asimpersonation of social networking users.AuthenticationAccess to any Private data must be put under control and this is normally achieved byauthenticating the client. The most basic authentication is achieved by validation of a pre-registered client ID with a password. Although client ID is most frequently just a personalemail address of the user, device ID can also represent a client.It is important to differentiate Device Authentication from Device Identification, where thelatter does not require validation of account with password and often used just to tracecustomers. Solutions relying on Device Identification pose security threat if involved withhandling Private data, as transfer of device to a different person if lost, stolen or sold, willautomatically provide access to the data of the previous user.Never use static device IDs such as Device Serial Number, Telephone Number or IMEI inclear form, use either obscured device IDs (can be hash code based on the listed IDs) orautomatically provisioned Unique Identifiers (UID).User authentication can also be implemented by integration into Third-party Authenticationproviders, such as Google ID, FaceBook ID or Microsoft Passport. For this reason refer toAPIs provided by these vendors or adopt open protocol OAuth (http://oauth.net).Authentication must be performed every time the application establishes a new session.Whichever approach is used for this purpose, it is important to ensure that:  Authentication is performed using secure authentication protocols – HTTP Basic authentication is not enough, HTTP digest would be more appropriate; however in some cases, even stronger methods are required  Proprietary implemented authentication, must be performed over secure SSL/TLS based communication channel  When a session is established, user or device credentials are not exchanged over an unsecured connection, so that Session IDs, Application PINs, Service Passwords, etc. are never exposed as these will provide an open door for intruders.Strong AuthenticationFor stronger authentication implement Multi-factor authentication which involvescombination of 2 or more stages of authentication. Variety of approaches exists and as anexample can be a combination of User and Server authentication, where verification of the<V0.1> Page 23 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>server is performed by client using additional security certificates. This type ofauthentication is used by businesses for implementation of Virtual Private Networks (VPNs).Secure data exchangeImplementation of secure communication using HTTP over SSL/TLS protocols (HTTPS)within the applications is not always favoured due to required additional effort; although,sometimes client applications would be the less affected. Indeed, extra effort is needed forimplementation of secure solutions, however the investments you will put into security ofyour product will be highly regarded by customers. In many cases, the additional effort maybe only needed to purchase and install a trusted certificate on the server and update theclient to use HTTPS instead of HTTP.Encryption/decryption of traffic may have an impact on user experience, as additionalprocessing time at both ends contributes to higher latency. This also has an impact onbattery life. On high-end devices, such as iPhone, these drawbacks are addressed byhardware accelerated encryption, which maximizes application performance.Input ValidationFollowing general guidance that any input to the application should be validated, it becomeseven more important with network applications, as the data can always be damaged, ordeliberately crafted input to cause damage in your software.The consequences of invalidated user input can be either crashes of the application or evenrunning malicious software which can destroy sensitive data or even steal private data byexploiting breaches such as buffer overflow, format string vulnerabilities, stack overflow orrace conditions.Although, many programming languages check input in standard APIs to prevent bufferoverflows, native languages such as C, C++ and Objective C put this responsibility ondeveloper. Even though, managed languages do try to prevent it, they still may be linked tonative C libraries, and sometimes, open-source libraries that are not protected from defectsand potential security problems.Ideal platformSuch a platform would:  Support seamless secure user and server authentication  Provide secure transport by default  Provide secure storage for credentials3.5 Efficient traffic usage3.5.1 Cloud-based transformations,There is a category of mobile network applications that use data from public resources suchas news web sites. However, using public resources which are not under the developer’scontrol poses several risks as it fails to exploit standardized APIs, and is often inefficient: 1. The format of data (HTML code) can be changed at any time which may cause application failure on the customer’s device. 2. The amount of data that is needed for the application might be significantly more than is necessary increasing network traffic and latency.In this case, it is highly recommended to check if there are any APIs (Web Services)provided from this resource that are standardized, less likely to be changed and containless unnecessary mark up information. If no APIs are available, then the developer can alsoconsider creating their own Web Service in order to have full control over the protocol anddata being transferred between device and server. In this case, even if the website changes<V0.1> Page 24 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>its HTML code, then only the Web Service should be updated with the client remainingunchanged.As the development of a server and Web Service might be out of the developer’s skill set,some existing third party tools can be used for this. A good example is Yahoo Pipes(http://pipes.yahoo.com) which provides a graphical user interface to aggregate, manipulateand mash up content from different sources around the web. Results can be delivered asRSS or JSON.A few examples of types of operations can be done with Yahoo Pipes: 1. Fetch data from different sources like feeds, web page, Google or Yahoo search, Flickr photos 2. Custom input data can be used as an external parameter. For example, it can be a search query 3. String manipulations such as regular expressions, text analyser, translation, etc 4. Location builder from a string 5. Mathematical operations 6. Filtering and sorting of the resultThe picture below shows an example Yahoo Pipe that aggregates the results of search from4 different sources, sorts the items by date and filters out non-unique titles and compiles aresult of maximum 40 news stories. It would even have been possible to combine the feedsof different languages and automatically translate them before aggregation. Figure 10 – Yahoo Pipes solution3.5.2 Media TranscodingIf the inefficiency in text based data formats can be improved by compression, the case formedia formats – pictures, audio and video – is somewhat more complex as the quality of themedia has a huge impact on its size. Therefore special care should be taken whentransferring media.<V0.1> Page 25 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>Most mobile phones have fairly low (i.e. few-megapixel) cameras; however, if an applicationuploads a picture taken by this camera for a social-network website, which will reduce thesize of any picture, there is no point in sending the original quality. The difference in sizecan be around 30-50 times, which also makes the same difference in time that takes toupload the picture.The same applies for downloading pictures to a mobile application. If the picture issupposed to be displayed only on the mobile display, then there is no point in downloadingthe original size. This is always applicable, for example, for thumbnails, however, for full-screen photos some additional overhead might be allowed to allow users scaling up theimage.The size of video files can be enormous if a smartphone has an HD camera; in this case itmight not be possible to upload a video over the cellular network without transcoding to alower quality file.If an application has video playback functionality, then a few points should be taken intoaccount: 1. It is better to not exceed resolution of the display where the video is going to be played(mobile device display or external display) 2. If the video should be played in real time, then the bandwidth of current network shall be checked to identify the appropriate bit rate of video that can be played without constant delays. 3. Progressive download and download resuming (section 3.2) may be usedApple puts strict requirements for applications regarding online video in applications,particularly if the video exceeds either 10 minutes duration or 5 Mb of data in a five minuteperiod, you are required to use HTTP Live streaming; otherwise Progressive Download canbe used.The ideal APIs on the platform to ensure that developers can leverage media transcodingwould be: 1. Basic image resizing 2. Audio codecs that would allow quality reduction (and size) of the audio 3. Reducing video quality and resolution in order to reduce size of video media. 4. Support of media streaming protocols such as HTTP Live Streaming or RTSP3.6 CompressionThe HTTP protocol defines mechanism of transferring data in compressed ways, if theserver can support it. Statistically, most servers do support it and, usually, enablingcompression is a very simple task for the most popular web servers.Compression can be very effective for text data by reducing overall on average by 80%. Forbinary content, like photos or videos, however, compression does not give much effect.The main idea of the HTTP compression is that if the client supports any of the standardcompression methods such as GZip, Deflate (zlib) or LZW, then it mentions it in the requestto the server and then if the server supports the listed methods it can send a compressedresponse.The indication that the client supports compressions is sent via HTTP HeaderAccept-Encoding.<V0.1> Page 26 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>Example request indicating that client supports GZip and Deflate compression methods: GET  /  HTTP/1.1 Accept‐Encoding:  gzip,  deflate Host: www.example.com Example response indicating that content is compressed: HTTP/1.1 200 OK Content‐Length: 438 Content‐Type: text/html; charset=UTF‐8 Content‐Encoding: gzip … …  RFC2616 section 14.3 and section 3.9 explains Accept-Encoding header in more details,and particularly, what can be useful is defining priorities (importance) of using differentmethods. HTTP compression technique includes negotiation, to make sure that both theclient and server support the same compression methods. Therefore, apart from standardcompression methods, clients and servers can even implement more efficient compressionfor certain types of content.In order to simplify usage of compression for developers, the ideal API for HTTP clientwould support the main compression methods GZip, Deflate (zlib) and compress (LZW) withthe corresponding Accept-Encoding header added by default and the contentdecompressed by default. However, developers would also be able to disable it or redefinehandling of compression in order to support custom compression methods.ReferencesRequest compressionhttp://httpd.apache.org/docs/2.0/mod/mod_deflate.html#inputSpeed Web delivery with HTTP compressionhttp://www.ibm.com/developerworks/web/library/wa-httpcomp/3.7 Background / Foreground modesMost mobile platforms support some distinction between background and foreground modesfor applications. The precise distinction varies from platform to platform but typically anapplication is said to be in the background if no part of its UI is visible and the user is unableto interact with it.Given that a user is unable to interact with an application that is in background mode,careful consideration should be given to this aspect of its design to ensure that unnecessarywork is not carried out whilst in this mode. Ensuring that the application minimizes itsresource footprint whilst in background mode will generally help to improve the userexperience of the foreground application.<V0.1> Page 27 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>More specifically the application will receive some indication from the platform when atransition between modes occurs and should take advantage of this to gracefully release (orotherwise disable) the following application components  Handlers  Timers  Network transactions  Memory/Objects  Media codecs  File & databasesSpecial attention should be given to applications that interact with the network on a regularbasis as this drains the battery and generates signalling traffic. In most cases applicationsshould not need to interact with the network whilst in background mode (given that there isno way to present results, unless it uses notifications system) and so network activity shouldbe prevented when the application is in this state. Idle screen widgets (e.g. weather / newswidgets) are common culprits here; however, it does not apply for applications such asinstant messengers, as they need to be connected all the time.However there can be no hard and fast rules in this area – for instance a music player islikely to want to continue to decode audio even when in background mode. But at the veryleast the developer should review the detailed operation of the application in each state toensure its resource footprint is appropriate.Similarly applications that do need to interact with the network whilst in background modeshould consider alternative approaches. For example it may be possible to aggregate thetransactions of several applications so that the background application can “piggy-back” itstransactions onto those of others. A common reason for background applications to accessthe network is to poll a server, however a better approach is to use push notification(if supported).The HTTP “Keep-Alive” mechanism is frequently used as the basis for push notificationsystems however this only works well if there is a centralized client side component forreceiving/routing notifications (i.e. as part of the platform e.g. Android C2DM).In case push notifications are not available or not suitable of some reason, keep-alive connections can be usedinstead to replicate push notification mechanism and avoid frequent polling of data. The main advantage ofkeep-alive over polling is that connection can be kept without frequent transfer of data and therefore, thecellular state can be switched to lower power; however, if there is anything to be delivered from server, it canbe done immediately. It would also necessary to make sure that connection is still alive by sending non-frequent data packets (minimum 10 minutes, but apple recommends ~26 minutes).Some platforms provide a richer (more fine grained) application lifecycle than others.Developers should exploit the lifecycle to its fullest to achieve the best user experience.For example it may be desirable to retain a group of thumbnails across several applicationstates that represent the “active” cycle of the application (where “active” might encompassbackground as well as foreground modes) but release them across states that represent aless active cycle. Failing to consider the target lifecycle can result in applications thatperform well on one platform having poor performance when ported to another.Applications should also consider altering their resource footprint in response to changes indevice state. In some cases changes in device state may fall within the scope of theapplication lifecycle (e.g. an incoming phone call is likely to result in the application makinga transition to background mode), however other changes in device state may lead to adifferent form of notification (applications may need to register to receive screen lock eventnotifications for instance). A useful approach is to treat each device state transition as aseparate use-case and identify those uses-cases that impact on the application. Using this<V0.1> Page 28 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>approach would (for instance) show that in the case of the music player mentioned earlier itmight be worth shutting down the audio decoder task when the speaker is muted.3.8 Application ScalingWhen designing a mobile application it is important to design it so that network activity is notconcentrated at specific times and is tolerant of geographical loading problems:  Handsets are frequently synchronised to a standard clock source so frequent updates using exact times may cause short overloads to the application servers and the radio network  The network capacity of a local area will be significantly lower than the product of the number of handsets and their assigned bandwidth. On occasions there may be large numbers of users in a specific location<V0.1> Page 29 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>4 Detailed RecommendationsIn previous chapters theoretical foundations of the developer’s guidelines have beendescribed and relevant principles explained in some detail. In the following, those principlesare mapped to limitations of each target platform (iOS, Android and Windows Phone 7).4.1 iOS4.1.1 AsynchronyAn application’s main thread is responsible for all activities including handing of the systemmessages, input events, etc. iOS makes sure that the main thread is always alive by amechanism called WatchDog which can terminate the process if it does not respond withincertain time (approximately 20 seconds). Therefore, if any synchronous operations arecalled, the developer needs to be sure that these operations can be finished as fast aspossible. This becomes very critical for networking and especially in the mobile networkenvironment, as network timeouts are much longer than the watchdog’s. For example,Domain Name Resolution will be timed out after 30 seconds of not having any responsefrom the network.The design of iOS APIs is done to simplify development as much as possible, and in mostcases developers do not even need to think about creating separate threads, as everythingis done transparently and asynchronously. However, some of the methods hidesynchronous networking which should be used very carefully and only in separate threads.Apple provided a list of such methods in WWDC’10 which is:  Utility methods: ‐initWithContentsOfUrl:  +stringWithContentsOfURL:   DNS: gethostbyname  gethostbyaddr  NSHost (Mac OS X) +sendSynchronousRequest:returningResponse:error: As it was explained before, network asynchrony is not just calling network functions from themain thread to not block UI, but also handling requests and responses independently fromeach other. This can be done by using requests queues and, although standard iOS SDKdoes not provide this functionality, there are a few third party libraries that provideimplementations of request queues.“Three20” library wraps Foundation’s classes such as NSURLRequest, NSURLConnection toadd an extra functionality, for example, more advanced caching, queues and retrymechanism. The advantage of using the “Three20” network module can be significant if thenetwork activities are integrated with any other “Three20” modules, especially with its userinterface.Another library that gives rich network functionality is ASIHTTPRequest. Unlike “Three20”,this library wraps lower level C API – CFNetwork, however, it is an Objective C library.Some developers may even prefer ASIHTTPRequest rather than standard Foundation API,as it implements many additional features such as:  Requests queue  Simple API for sending POST requests with files attached and post values<V0.1> Page 30 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>  Tracking progress of a single request or the whole queue with automatic update of UIProgressView  gzip compressed request bodies  Resuming interrupted downloads Section 3.2  Background-mode requests  Client certificates support Section 3.4  Automatic support of network indicator  Automatic retry  Persistent connections – to reuse single HTTP connections for a several small requestsReferencesASIHTTPRequest documentationhttp://allseeing-i.com/ASIHTTPRequest/How-to-use4.1.2 Connection loss and error handlingArchitecturally, it would be better to apply the MVC pattern to separate data handling fromthe user interface and the main application logic, where the Model would be the best placeto isolate data loading, error handling and connection loss, and the use of other datasource such as local database or local cache if required.As described in Section 3.2, it is good idea to make the application aware of the currentnetwork status and if no network is connected, then the application can immediately switchto offline mode avoiding network errors.Apple provides sample code in project “Reachability” (see reference below) which can beused for detecting network status and notifying about any changes. Generally, the methodreachabilityForInternetConnection would be appropriate for most of the cases.If the application detected that there is no internet connection and offline mode should beused, then local data shall be used. The simplest solution without building a local databasewould be to use standard NSURLRequest, but with custom cache storage that supports on-disk cache (as described in Section 4.1.3) and cache policy parameter set toNSURLRequestReturnCacheDataDontLoad. This will avoid attempts to establish a networkconnection that is going to fail, and will return the result immediately, if anything has beencached. The rest of application can be left unchanged with error handling as if it was usingthe network.For any network request that uploads data to a server regardless of size, for instance,uploading picture, or even updating status on a social network, it is advisable to use TaskCompletion API to make sure that content can be delivered even if the user minimizes theapplication. Subsequently, it is also important to make sure that entered content is not lostin case of the network failure and can be retried without need to reenter the data (or retakethe picture.Long downloads, such as, music files, digital issues of magazines or any other large files,shall be resumeable and if the server and the content support HTTP partial download, thenthe request for restoring download from any part of the file can be initiated by adding HTTPRange header: <V0.1> Page 31 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>// Requests part of file starting from 1024th byte [URLRequest setValue: @"bytes=1024‐" forHTTPHeaderField: @"Range"];  ReferencesReachabilityhttp://developer.apple.com/library/ios/samplecode/Reachability/Network reachabilityhttp://blog.ddg.com/?p=244.1.3 CachingThe Foundation framework provides simple to use cache management, giving developerscontrol over what can be cached and where. Standard NSURLCache is very limited and,although, the full MacOS X version supports both on-disk and on-memory caches, but theiOS version can store only in memory. Furthermore, by default the capacity of memorycache gets set to zero, meaning that even memory cache will not work if it is not enabledexplicitly.A simple test shows that memory capacity is set to zero by WebView (even if it is not usedin the UI) from a separate thread. To make the matters worse, it is also not documented atwhat point this happens – perhaps as a result of a bug or a hidden feature. Therefore asimple and reliable workarounds would be to subclass NSURLCache and redefine methodsetMemoryCapacity which will ignore all calls with value 0 and will pass through all othervalues to the original method.Example: ‐(void)setMemoryCapacity:(NSUInteger)memoryCapacity {     if (memoryCapacity == 0) {         return;     }      [super setMemoryCapacity:memoryCapacity]; } The standard class NSURLRequest includes a parameter cachePolicy which can retrievethe following values: NSURLRequestUseProtocolCachePolicy – the default cache policy for the protocol that is being used for the particular URL request. Suitable for most of the cases in online mode. NSURLRequestRelaodIgnoringCacheData – ignores any local cache and will try to load data from the originating source. Suitable for online mode and for certain use cases, when data should not be cached, for example, for keep-alive connections. NSURLRequestReturnCacheDataElseLoad – returns data from cache even if it is expired. If there is no cached version, then it will try to download the data from the originating source. Suitable for certain types of content such as static photos.<V0.1> Page 32 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN> NSURLRequestReturnCacheDataDontLoad – returns data only if has been stored in local cache and does not attempt to retrieve it from the origination source if there is no cached version. Suitable for offline mode.Example: // Creating URL request NSURLRequest  *theRequest  =  [NSURLRequest  requestWithUrl:     [NSURL URLWithString:@”http://www.hudriks.com/example.html”]     cachePolicy:NSUrlRequestUseProtocolCachePolicy     timeoutInterval:60.0];  // Initiation the connection with the request NSURLConnection  *theConnection  =  [[NSURLConnection  alloc]     initWithRequest:theRequest delegate:self];  if (theConnection) {     // Prepare for receiving the data } else {     // Handle the error }  The framework also allows the response to be altered before it gets stored into local cacheby implementing connection:willCacheResponse:. Usually, this method is used to avoidcaching of some private date, and some implementations do not cache any traffic that goesthrough encrypted protocols such as HTTPS.If in-memory cached is used, it would be reasonable to clean up the cached data if theapplication receives a memory warning.Currently, the standard NSURLCache does not support all features of HTTP cache such asconditional HTTP request headers, for instance, “If-None-Match”, “If-Modified-Since”, thathas been described in Section 3.3.Although, the default NSURLCache is very limited and can not help much for implementingoffline mode, the API still gives a solid framework that can be used for simple integration ofthe developer’s own implementation of cache or own subclass of NSURLCache class.There are a few implementations of custom cache classes:  “Three20” framework (see reference below), that has been developed for the facebook application, gives also choice of type of cache storage such as Memory, Disk or Network and provides separate in-memory storage specifically for images to optimize performance. However, their cache is not subclass of NSURLCache and requires using their request classes as well  SDURLCache – subclass of NSURLCache with on-disk cache support.Cache in web applicationsYahoo! did a research how mobile Safari works in iPhone regarding caching and some keyfacts can be used for architecting and implementing web applications:<V0.1> Page 33 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>http://yuiblog.com/blog/2008/02/06/iphone-cacheability/In order to be cached by Safari, the HTTP content should include either “Expires” or“Cache-Control” header. Expires: <Expiration time in GMT Format> Cache‐Control: max‐age = <Expiration time in seconds>  The browser’s cache applies a limit to the cacheable content, which should not be largerthan 25 KB (or 15 KB according to the latest tests) of uncompressed data. Even if it istransferred using HTTP compression, the browser will still uncompress it before trying to putit into cache. This means, that the correct distribution of content over small files and theminimisation of each file, particularly, JavaScript, CSS and HTML, becomes highlyimportant for the performance of mobile web applications.ReferencesThree20 Frameworkhttps://github.com/facebook/three20SDURLCache classhttps://github.com/rs/SDURLCacheURL Loading System Programming Guidehttp://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/4.1.4 SecurityAlthough the iOS operating system is based on Mac OS X and most of the security hasbeen inherited from there, because of the differences in the usage, there are somediscrepancies in the APIs and security models.iOS security is based on three main services in the Core Services layer, which are:  Keychain Services – secure storage of passwords, keys, certificates and other secrets.  Certificate, Key and Trust Services – creating and managing certificates, creating encryption keys, encryption and decryption of data, signing and verification of digital signatures.  Randomization Services – cryptographically secure pseudorandom numbers.On a higher level, CFNetwork and subsequently URL Loading System use these services,for instance for providing secure transport protocols and supporting SSL and HTTPSconnections.<V0.1> Page 34 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN> Figure 11 – CFNetwork Component DiagramKeychain Services has major difference from the Mac OS X version. In Mac OS X, keychainsecurely saves passwords and if an application requests information from there, then user isasked to give permission by entering his password. In iOS the device is already secured byPIN number, and, therefore, user is not asked to enter any passwords or confirmations,however, keychain allows accessing the data only by signed applications, and eachapplication has individual storage and can not access information from any otherapplications.As mentioned earlier, URL Loading System supports the HTTPS protocol by default, sodevelopers do not need to put any extra effort in establishing a secure connection with theserver (if the server also supports HTTPS).Apple has also done great job in supporting developers to develop secure software anddevelopers are highly recommended to familiarise with documents from Apple DeveloperNetwork:  Secure Coding Guide. The document covers all aspects of security and not only network security. Explains in details topics such as Buffer Overflow, Stack Overflow, Input Validation, how these can be used by attackers to run malicious code and how this can be avoided. The design of secure user interface is also touched in the document which explains that security should not compromise usability of an application.  Security Overview. Gives more details about cryptography and secure APIs in iOS and Mac OS X.  Keychain Services Programming Guide. Contains section related to keychain services in iOS and gives guidance about how the relevant APIs should be used.  Certificate, Key, and Trust Services Programming Guide. Explains how the APIs for managing and using certificates and encryption/decryption of the data should be used.4.1.5 Data formatsJSONJSON is very popular these days and some web sites provide access to their APIs onlyusing JSON rather than XML.The most widely used Objective-C JSON parsers are YAJL, JSON Framework and TouchJSON (see references below). Each of these have their own advantages anddisadvantages.<V0.1> Page 35 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>YAJL is sequential access parser which is similar to SAX parser for XML. As it does notneed to keep all data in memory, the obvious advantages are low memory footprint andparsing speed which would be suitable for huge amounts of data or even streams of data.The Touch JSON library shows good results in speed benchmark and it has very simple touse API. For example, to parse JSON into NSDictionary object, the code looks like this: SBJSON *jsonParser = [[SBJSON new] autorelease]; NSString *jsonString = ...; return [jsonParser objectWithString:jsonString error:NULL];  It can be even simpler by using NSString extensions: NSString *jsonString = ...; return [jsonString JSONValue];  Encoding to JSON can be done by NSObject extension: NSString *jsonString = ...; NSDictionary *data = ...;  jsonString = [data JSONRepresentation];  XMLiOS SDK provides only the event-driven XML parser NSXMLParser which works in the sameway as the SAX parser, but instead of callback functions it sends messages to its delegate:  parser:didStartElement:namespaceURI:qualifiedName:attributes:   parser:foundCharacters:   parser:didEndElement:namespaceURI:qualifiedName: There is also alternative 3rd party event-driven XML parser called AQXMLParser that givesconsiderable memory savings.If the application needs a tree-based parser, despite memory consumption, it is possible touse the libxml2 library that is already included in iPhone, however, it is a pure-C interface.The other alternative might be using Objective-C Touch XML framework which is a wrapperfor the libxml2 library.ReferencesYAJL<V0.1> Page 36 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>http://github.com/gabriel/yajl-objcJSON Frameworkhttp://github.com/stig/json-frameworkTouch JSONhttp://github.com/schwa/TouchJSONAQXMLParserhttp://github.com/AlanQuatermain/aqtoolkitTouch XMLhttp://github.com/schwa/TouchXML4.1.6 CompressioniOS supports compression (gzip and deflate) by default and automatically adds“Accept-Encoding” header to all requests and then decompress the response. Thisincreases the efficiency of data traffic for most network enabled applications in theAppStore.ASIHTTPRequest library supports gzip only and “Three20” also supports gzip and deflateas it wraps the standard NSURLRequest.4.1.7 Background / Foreground modesWith version 4 iOS started supporting multitasking on almost all devices apart from iPhone2G, iPhone 3G and corresponding models of iPod Touch. However, iOS multitasking is notthe same as developers are used to on desktop operating systems. The main difference isthat iOS multitasking limits background activities due to the limited resources of thehandset, and also due to the different usage of mobile applications.iOS gives developers 7 different background services that can be implemented in theapplications:  Fast application switching - suspending application with preservation of its state and quick resume.  Push notifications - deliver information from backend to application that is not currently running in foreground.  Local notifications - scheduling of delivery of push-style notifications, while an application is suspended or closed.  Background audio - play audio content through the unified playback system on the device while application is in background.  Task completion - gives extra time to complete a task in background.  Location and navigation - tracking the location changes.  Voice over IP - make and receive calls using an internet connection .Almost all these services may involve network activities (apart from fast applicationswitching and local notifications), and extra care should be taken to not reduce batteryperformance of the user’s device and also to not overload thenetwork.Push notification is a well optimised technology compared to polling data, however, if it isnot used carefully, it can cause problems in the network, mainly, related to simultaneousbroadcast of notifications to many devices (latest news, some offers, etc).<V0.1> Page 37 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>Other background services such as background audio, task completion, location andnavigation and voice over IP, usually can be used for establishing frequent networkconnections, and can therefore drain the battery very quickly without the user noticing, asthe services runs in background. The general advice here is to consider which data requiresimmediate delivery and which can be aggregated with its delivery postponed to a later time.The Task Completion API gives some flexibility for developers to run almost any code,however, the intention is to give the application extra time to finish activities that havealready started while the application is in background. As soon as they are finished, theapplication can be suspended without using any resources.This can be very useful for network operations that may take long time or require a certainlevel of reliability, for instance uploading pictures, or sending a text message/email. To starta connection in background, method beginBackgroundTaskWithExpirationHandler: inUIApplication should be called and when the activity is finished or it has failed, thenendBackgroundTask: should be called.However, if the Task Completion API is not used, then the corresponding delegates forNSURLConnection are still called after resuming the application, and if the application hasbeen resumed within the network timeout (by default, 60 seconds), then the response maystill be delivered, otherwise, delegate didFailWithError: is called.Backward compatibilityAs multitasking is not supported on iPhone 3G and 2G and iPod Touch 1st and 2ndgenerations, even if they have iOS 4 installed, it is important to check if application can usethe corresponding APIs on the device.This can be done as follows: [[UIDevice currentDevice] isMultitaskingSupported]  Or if([someObject respondsToSelector: @selector(methodForMultitasking)) {     ! [someObject methodForMultitasking]; } else {     // ... }  Network usageIn order to maintain connections in VOIP applications, iOS provides a mechanism to set akeepalive handler with setKeepAliveTimeout:handler: on UIApplication, which will becalled automatically by the system. The minimum interval is 10 minutes, however, Applerecommends to use 29 minutes which seems to be the most optimal for maximising batterylife.The operating system does not guarantee that keepalive handler will be called exactly at therequested time, as it performs various optimisations for waking up the system and aligningseveral timers to be triggered in the same time if necessary.<V0.1> Page 38 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>Device statesApart from supporting multitasking, the application should also be aware of different states,such as screen lock/unlock, switching to phone call and back to the application. This,mainly, can be done by handling applicationDidBecomeActive:,applicationWillResignActive:. If there are any heavy operations that use the device’sresources (graphics, network), then it would be better to suspend them if possible.iOS also allows the application to prevent device going to sleep mode as follows: [[UIApplication sharedApplication] setIdleTimerDisabled: YES]  If the application relies on a network connection and needs to be connected even when thedevice is in sleep mode, then the parameter UIRequiresPersistentWi‐Fi shall be addedinto Info.plist file. Without this parameter the Wi-Fi will be disconnected after a while.ReferencesAudio Session in screen lockhttp://developer.apple.com/library/ios/#qa/qa2008/qa1626.html<V0.1> Page 39 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>4.2 Android4.2.1 AsynchronySection 2.2.1 sets out the generic principles surrounding the use of asynchrony to enhanceuser experience during network activity, these principles are as applicable to Android as toother platforms, and their use is not restricted or impeded in any way by the Androidplatform/application architecture.It may be worthwhile to consider elaborating the technique slightly to introduce some notionof “throttling” to avoid fully saturating the bandwidth that is available on the currentconnection. This will improve the overall user experience (by allowing network requestsfrom other parts of the UI to continue to be satisfied) and improve resilience to adversenetwork conditions (a fully saturated connection is more likely to lead to failed requests).4.2.1.1 Implementation DetailsAndroid implements the subset of the Apache Http APIs org.appache.http.* to supportnetwork activity using the “blocking” I/O model. Non-blocking I/Oorg.apache.http.impl.nio.* is not supported at present, so this means that it necessaryfor applications to implement asynchrony using standard Java constructs and the supportingclasses provided by the Android framework.Figure 12 shows the classes that are required to support asynchrony in a simple Androidapplication. The application fetches and displays a bitmap from the network in response to abutton press. It consists of two activities MainActivity,  ShowBitmapActivity and ahelper class AsyncHttpReq. Figure 12 – Asynchrony exampleFigure 13 shows the execution sequence of the application. Broadly speaking this has fivephases each of which run asynchronously with each other.<V0.1> Page 40 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN> Figure 13 – Asynchrony example – Sequence diagramEach phase illustrates a different aspect of asynchrony in the context of the Androidframework: 1. The application’s MainActivity class is responsible for creating the initial UI (including a button click listener). More importantly it creates an instance of Handler that will be used to receive asynchronously coarse-grained status messages during the course of the http request. 2. The button listener’s onClick method is invoked asynchronously when the user presses the button. At this point an instance of AsyncHttpReq is constructed and its Thread is started. 3. Some time later the Thread associated with the AsyncHttpReq will run. It sends a message back to the handler to indicate that processing of the request has begun. A further message is sent with the result when the request is complete (or times out). These messages are sent asynchronously. 4. Http activity uses the blocking APIs and may take some time to complete depending on network conditions and size of the image. 5. When the handler receives a message indicating that the request has been successful it starts the UI to display the bitmap.<V0.1> Page 41 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>This example does not implement throttling, each request will be processed as soon as theassociated Thread is run possibly saturating the available bandwidth. In its simplest formThrottling could be implemented using a queue and limiting the number of requests that canbe active at any one time.After Android 1.5 a lightweight method is introduced by the platform to simplify the task. Autility class called AsyncTask is written to provide a convenient, easy-to-use way to achievebackground processing in Android applications, without worrying too much about the low-level details (threads, message loops etc). It provides call-back methods that help toschedule tasks and also to easily update the UI whenever required. You could have a lookof the example showing how to use it in article “Painless Threading” (see below). Howeverplease keep in mind AsyncTask is a lightweight solution with some limits: 1. AsyncTask uses a static internal work queue with a hard-coded limit of 10 elements. That means if you want to download 30 images from the server, the work queue would quickly overflow and many of your tasks would get rejected. 2. AsyncTask cant survive your Activity being torn down and recreated on the other side. 3. You can not interact with background thread and exceptions are not well handled.In most cases, AsyncTask is what you need, but for complex cases where above limitsarises you have to build your own worker/handler solution.ReferencesPainless Treadinghttp://developer.android.com/resources/articles/painless-threading.html4.2.1.2 Non-Blocking User InterfaceUnresponsive user interfaces are perhaps the commonest cause for user frustration with aparticular application. As far as Android applications are concerned there are two reasonsthat typically lead to a blocked UI: Unavoidable delays and unresponsive applications.Unavoidable DelaysIt is quite common for an application to be faced with unavoidable delays for instance whendownloading large files from the network or processing large images. However even when adelay is unavoidable the application should try to ensure that the UI is not blocked.Android provides some UI widgets to help to improve the user experience during theseperiods. When the delay is known to be brief (less than five seconds say) it is acceptable touse the ProgressDialog (see Figure 14 below). Figure 14 – Android ProgressDialog<V0.1> Page 42 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>These still block the UI but are at least preferable to a frozen screen. For longer delays theProgressBar view can be incorporated as part of the layout and driven from a helper threadassociated with the current Activity. This allows the other parts of the UI presented by theActivity to remain active.Unresponsive ApplicationsWhen an application blocks the Android UI for more than a few seconds will lead to the“Application Not Responding” (ANR) message, requiring the user to choose whether tocontinue with the operation or to abandon the application completely. Figure 15 – Activity Not Responding DialogPlainly this is very undesirable behaviour. Most often the user will close the applicationleading to the wasteful loss of its internal data-structures. These will need to be recomputedif the user subsequently reruns the application.To avoid this applications should be structured to minimise the amount of work done in anymethods that run in the main thread (typically the Activity life-cycle methods e.g.onCreate(), onResume()). For Activities the easiest way to do this is to off-load the workto a child thread and provide a Handler class which the child can use to indicate when thework is complete.Similar restrictions also apply to BroadcastReceivers however the solution in this case is toprovide a Service to do the work as the short life of BroadcastReceivers also impacts anychild threads <todo: SRB:check this!>Garbage collection can also lead to noticeable delays in the user interface. To a certainextent this is unavoidable but minimizing the number of objects that are created in mainthread methods will provide some mitigation against this problem.4.2.2 Offline modeA common problem with the design of mobile applications is that their default assumption isthat a connection is always available and the lack of a connection is treated as a cornercase or error condition. This approach is reinforced through the common use of emulators(which are effectively always connected) during the development process.A safer approach is to assume that a connection is seldom available and design thearchitecture of the application accordingly. This approach tends to encourage thedevelopment of stronger abstractions between the application and its data and this in turn islikely to lead to an architecture that lends itself more easily to the kind of asynchronousimplementation discussed earlier. Taking this approach to its logical extreme applicationswould direct all network traffic to a local service implementing a shared intelligent localpersistent cache.<V0.1> Page 43 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>Whatever approach the developer decides to take Android provides several options forstoring and accessing persistent data.ReferencesData Storagehttp://developer.android.com/guide/topics/data/data-storage.htmlBandwidth AwarenessThe Android Connectivity Manager can be used to determine the state of networkconnectivity. Applications can also register to receive a notification when the network statechanges.Where a throttling strategy has been used (as outlined in Section 2.2.4) knowledge aboutthe state of the connection could be used to dynamically alter the throttle settings e.g. toincrease the number of simultaneous requests that are allowed when a Wi-Fi connection ispresent.4.2.3 Caching Http-cache is supported by the browser on Android but not the http APIs, therefore extra effort is needed to support http-cache in applications. According to RFC-2616, a possible sequence diagram could be as following: Figure 16 – Http Caching – Sequence diagram<V0.1> Page 44 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>The full implementation of http cache is laborious. Apache HttpClient implementsCachingHttpClient, a drop-in replacement for a DefaultHttpClient, to provide anHTTP/1.1-compliant caching layer, but it is not available under Android. So you have toimplement the flow in Figure 5 manually. A simple conditional get can be implemented asbelow: class ConditionalGetExample {     String entityTag = "";     String lastModified = "";          public void start() throws HttpException, IOException {         HttpClient client = new DefaultHttpClient();         HttpGet request = new HttpGet(("http://www.apache.org”);                 setHeaders(request);         HttpResponse response = client.executeMethod(method);         processResults(response);       }                      private void setHeaders(HttpGet  request) {         request.setHeader("If‐None‐Match", entityTag);         request.setRequestHeader("If‐Modified‐Since", lastModified ));     }          private void processResults(HttpResponse response) throws HttpException {         if(response.getStatusLine().getStatusCode() ==             HttpStatus.SC_NOT_MODIFIED) {             Log.d(“Http cache”,              "Content not modified since last request");             return;         }          else {             entityTag = retrieveHeader(method, "ETag");             lastModified = retrieveHeader(method, "Last‐Modified");             // process fresh content here!         }     }      private String retrieveHeader(HttpResponse response, String name)         throws HttpException {         Header[] headers = response.getHeaders(name);         String value = ""; <V0.1> Page 45 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>        if(header.length > 0) {             value = header[0].getName();         }         return value;     } }  If you are using HttpUrlConnection from Java.Net package, then Javas response cachemechanism might be another approach to do the job. There are three abstract classes:ResponseCache, CacheRequest, CacheResponse. You need to extend these classes foryour own cache implementation. The flow of events is something like the following:  A concrete class of ResponseCache registers with the system by using the static method ResponseCache.setDefault(ResponseCache).  There are two methods in the ResponseCache that are invoked by the protocol handlers. get() returns a CacheResponse and put() returns a CacheRequest.  When you create a URLConnection and attempt to read content the appropriate stream handler is created and it checks for the content in the cache by invoking ResponseCache.get().  If the content is found in the cache, it is returned. Otherwise a request is sent to the origin server, the received response is then passed on to ResponseCache.put() to see if the content is cacheable (based on the response headers) and possibly store it in the cache.You could find a reference implementation in the article specified below. Work of cache-ability determination, placing the resource content in the cache, evicting the content basedon the “Expires” or “Date” headers, and retrieving the resource will be done by your owncache implementation.ReferencesUsing ResponseCache in an Android Apphttp://codebycoffee.com/2010/06/29/using-responsecache-in-an-android-app/4.2.4 SecurityAndroid exposes a number of standard Java APIs to support security:  java.security package provides classes and interfaces supporting the security framework: - Generation and storage of public cryptographic keys. - Message digest and signature generation. - Secure random number generation.  javax.crypto package provides additional classes and interfaces for common cryptographic operations: - Symmetric, asymmetric, block and stream ciphers. - Secure streams and sealed objects.  javax.security.* packages<V0.1> Page 46 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN> - Authentication and authorization. - Public key certificates.The whole framework is “pluggable” in the sense that the underlying cryptographyimplementation is abstracted away from the public APIs so that 3rd party providers can besupported. Android makes use of two security providers: Bouncy Castle and the ApacheHarmony APIs. These are explicitly instantiated in the java.security package, extensiveuse of which is made throughout other parts of the Android framework to support e.g.HTTPS, SSL Webkit browser etc.Use of these APIs within the context of Android is not well documented – API Javadoc only,security as a topic within the Google developer documentation only covers applicationsecurity not network security. However as the APIs are standardized there are plenty ofgeneric examples of their use outside of Android.4.2.5 Data formatsAndroid includes support for both JSON and XML interchange formats.JSON support is provided by four classes in the org.json package:  JSONArray – Indexed sequence of values.  JSONObject – Set of name/value mappings.  JSONStringer – String conversion.  JSONTokener – Parse JSON encoded strings into corresponding objects.  android.util – Provides two further classes for reading/writing JSON encoded stream of tokens (includes examples).JSON is standardized through RFC 4627 and so not unsurprisingly plenty of examples of itsuse can be found on the web. The Android framework itself makes fairly extensive use ofJSON – for example Android In-App Billing transaction information is contained in a JSONstring.Android support for XML is provided by the following packages:  org.xml.sax – Core SAX APIs  org.xmlpull.* – Support for XML pull parsing.  javax.xml.datatype – XML/Java type mappings  javax.xml.namespace – XML namespace processing  javax.xml.parsers – Processing for XML documents supporting pluggable parses for SAX and DOM.  javax.xml.transform.* – Transformations from Source to Result with support for DOM, SAX2 and stream- and URI-specific transformations.  javax.xml.validation – API for the validation of XML documents.  javax.xml.xpath – API for the evaluation of XPath expressions (a simple concise language for slecting nodes from and XML document).  android.xml – XML utility methodsAgain the Android framework itself makes extensive use of XML – e.g. the Androidapplication manifest, UI layout files and internationalization all use XML.<V0.1> Page 47 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>4.2.6 CompressionAndroid supports gzip and deflate compression for HTTP content. However compression isnot enabled by default and so developers wishing to take advantage of this feature mustexplicitly add the “Accept-Encoding” header to the request and handle the received contentaccording to its “Content-Encoding” header.4.2.7 Background / Foreground modesIn all Android recognizes five different process states:  Foreground process: This is the part of the application that is currently visible and with which the user is presently interacting. More precisely an application is considered to be in the foreground between calls to the onResume() and onPause() methods, so typically the onPause() method is where application data ought to be persisted and CPU intensive tasks terminated (e.g. application threads, animation + other content rendering).  Visible process: Although this part of the application is no longer in the foreground some of its UI components are visible. An example of this would be when a dialog is in the foreground partially obscuring the other activity’s UI.  Service process: These are started by startService() and do not fall into either of the previous process states as services do not present a UI. Service processes keep running until they are explicitly stopped or the system runs out of memory.  Background process: Activities whose onStop() method has been called. As no part of the activity’s UI is visible it is assumed that these processes can be killed at any time (by implication this means that the application must have saved its state correctly as a side effect of earlier life-cycle methods).  Empty process: These are retained to improve start-up performance of other components.For Activities Android also provides the onSaveInstanceState() to help with persistence.This is called (immediately prior to onPause()) when the application is to be destroyed bythe system and allows the developer to discriminate between this condition (when the usermight expect the application’s state to be restored the next time it is run) and the case whenthe user has shut down the application (an might therefore expect the application to runfrom the start the next time it is run).For activity lifecycle methods from onPause() onwards the application process can be killedat any time after the method returns.<V0.1> Page 48 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>4.3 Windows PhoneFor a general overview of Windows Phone networking refer to the following article:Networking in Silverlight for Windows Phonehttp://msdn.microsoft.com/en-us/library/ff637320(VS.95).aspx4.3.1 AsynchronyWindows Phone 7 is the newest of all the current generation of Smartphone platforms. It isdesigned to operate in multithreaded mode and support asynchronous communication outof the box. All network access in WP7 is asynchronous and the main network APIs do notexpose synchronous methods to minimise the impact on the performance of the UI. Asnetwork resources can be accessed in a number of ways, it is important to understand themultithreaded architecture of WP7 Silverlight framework. Every Silverlight application willhave the following threads by default:  UI thread – responsible for handling user input, drawing new visuals, and calling back to user code  Main thread – responsible for handling user code, such as loading and processing of data, implementing business logic, etc.It is essential to keep the UI thread as free as possible as maintaining a lightweight UIthread is the key factor of a responsive application. Access to the network resources can beperformed from both the user code and XAML mark-up. All objects referenced from XAMLare downloaded and processed asynchronously by the Silverlight engine itself. Networkresources accessed from the user code are handled by the APIs of the System.Netnamespace which includes:  WebClient class – provides common methods for sending data to and receiving data from a resource identified by a URI. WebClient is a wrapper class around the HttpWebRequest class and can be easier to use because it returns result data to your application on the UI thread. WebClient supports events. WebClient is a higher level API than HttpWebRequest with callbacks made on UI thread and support of events  HttpWebRequest class – is a lower lever API compared with WebClient and provides richer functionality and better control over HTTP communication. Callbacks are implemented through a delegate function and made on the Main threadAlthough both of these classes support asynchronous communication only, it is important tounderstand the differences between them.WebClient classThis class is designed for use from Silverlight controls that are hosted in a XAML page. Itprovides simplest way of accessing network resources but must be used carefully as itoperates in the UI thread and may have impact on the responsiveness of the user interfaceif not used carefully. When using this class make sure that all code referenced by eventhandlers only performs tasks that are related to updating the UI, otherwise this will delay thereturn of control to the UI thread and will make UI operation sluggish.<V0.1> Page 49 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>Here is an example: try {     System.Uri uri = new Uri("http://www.bing.com");     WebClient webClient = new WebClient();      // Assign callback event handler     webClient.OpenReadCompleted +=          new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);     // Create a HttpWebrequest object to the desired URL     webClient.OpenReadAsync(uri); } catch (Exception ex) {     // TODO: your exception handling code     webClientTextBlock.Text =         "Exception raised! Message: " + ex.Message; }   void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {     try     {         using (StreamReader reader = new StreamReader(e.Result))         {             webClientTextBlock.Text = reader.ReadToEnd();         }     }     catch (WebException ex)     {         // TODO: your exception handling code         webClientTextBlock.Text =             "WebException raised! Message: " + ex.Message +              "nStatus: " + ex.Status;     }     catch (Exception ex)     {         // TODO: your exception handling code         webClientTextBlock.Text =             "Exception raised! Message: " + ex.Message; <V0.1> Page 50 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>    } }  HttpWebRequest classThis class is designed for use from the user code and should normally be considered foraccessing data feeds, submitting data to the cloud and manual handling of static networkresources. Callbacks are processed via AsyncCallback delegate function and are made onthe Main thread. This means that all code updating the UI must be synchronised with the UIthread, otherwise access to any UI controls or UI related classes (such as BitmapImage)will result in a System.InvalidOperationException. In order to synchronise output withthe UI thread it is necessary to invoke the code through a dispatcher. Dispatcher.BeginInvoke(() => { /* UI update code */ });  Before invoking the dispatcher ensure that you finish the processing of all non-UI relateddata. Keep this block of code as compact as possible, only perform UI updates and don’tperform any unnecessary calculations as anything executed here may further delay therendering of the UI.Here is an example of how to use the HttpWebRequest class: try {     System.Uri uri = new Uri("http://www.bing.com");     // Create a HttpWebRequest object to the desired URL     HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);      // Start the asynchronous request     IAsyncResult result = (IAsyncResult)httpWebRequest.BeginGetResponse(         new AsyncCallback(ResponseCallback), httpWebRequest); } catch (WebException ex) {     // TODO: your exception handling code     Dispatcher.BeginInvoke(() =>     {         httpWebRequestTextBlock.Text =             "WebException raised! Message: " + ex.Message +             "nStatus: " + ex.Status;     }); }  <V0.1> Page 51 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>catch (Exception ex) {     // TODO: your exception handling code     Dispatcher.BeginInvoke(() =>     {         httpWebRequestTextBlock.Text =             "Exception raised! Message: " + ex.Message;     }); }   private void ResponseCallback(IAsyncResult result) {     try     {         HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;         // Obtain WebResponse from the callback result parameter         WebResponse webResponse = httpWebRequest.EndGetResponse(result);          using (Stream responseStream = webResponse.GetResponseStream())         using (StreamReader responseStreamReader =             new StreamReader(responseStream))         {             // Read response body             string contents = responseStreamReader.ReadToEnd();             // Invoke dispatcher to access UI thread             Dispatcher.BeginInvoke(() =>             {                 // Update UI control                 httpWebRequestTextBlock.Text = contents;             });         }     }     catch (WebException ex)     {         // TODO: your exception handling code         Dispatcher.BeginInvoke(() =>         {             httpWebRequestTextBlock.Text =                 "WebException raised! Message: " + ex.Message +                 "nStatus: " + ex.Status;         }); <V0.1> Page 52 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>    }     catch (Exception ex)     {         // TODO: your exception handling code         Dispatcher.BeginInvoke(() =>         {             httpWebRequestTextBlock.Text =             "Exception raised! Message: " + ex.Message;         });     } }  Managing asynchronous requestsIn most cases the monitoring of asynchronous requests is not necessary as responses willautomatically fail in the case of network errors resulting in WebException being raised.Network error exceptions must be always handled appropriately by your code, but in somescenarios it will be necessary to implement the following:  Timeout handling – in asynchronous programming, it is the responsibility of the client application to implement its own time-out mechanism  Cancellation of requests – in some scenarios, for example when the user desires to manually terminate network requestsIf your application requires management of asynchronous requests for any reason, you willhave to implement a technique allowing you to store references to all issued requests inyour procedure and pass the states of requests across asynchronous calls within thethread. This technique is based on storing parameters related to individual request in theRequestState class. In order to implement timeout handling and cancellation ofasynchronous requests, follow this article:http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.abort(v=vs.80).aspxTip: Always remember that WebClient callbacks are made on the UI threadTip: Keep non-UI related code out of the dispatched code when using HttpWebRequestReferencesHttpWebRequest classhttp://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v=VS.95).aspxWebClient classhttp://msdn.microsoft.com/en-us/library/system.net.webclient(v=VS.95).aspxUnderstanding Threadshttp://msdn.microsoft.com/en-us/library/ff967560(v=vs.92).aspx#BKMK_ThreadsMaking Asynchronous Requestshttp://msdn.microsoft.com/en-us/library/86wf6409.aspx<V0.1> Page 53 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>4.3.2 Connection loss and error handlingRegardless of the network error recovery strategy chosen for your application, it isabsolutely necessary to ensure that:  your application never crashes due to a network error  informs the user about network issues in an unobtrusive wayYour error recovery strategy may be quite simple, just instructing the user to restart theapplication in order to refresh, or may be more sophisticated implementing offline mode withmanual or automatic retry or network status monitoring features. Depending on your chosenstrategy here is a list of facts and options worth considering:  XAML referenced network resources are loaded automatically by Silverlight and are difficult to monitor. You will have to load these resources into the UI yourself in order to have a better control  Always catch exceptions from WebCllient or HttpWebRequest when initiating requests and reading responses, otherwise your application will crash. The WebException.Status property contains a WebExceptionStatus value that indicates the source of the error. Code samples for your convenience are given in the previous section 4.3.1 Asynchrony.  Monitor errors globally and integrate network health flags into ViewModel so that you can consistently report connectivity errors and perhaps offer a recovery actionIf all network resources are managed through user code, then consider the following:  Design the data transfer routine in a way that it can be restarted at any time. You are likely to have more than one routine for different parts of your application  Manage asynchronous network requests in a way allowing safe cancellation of them. Example technique is covered in the previous section 4.3.1 Asynchrony -> Managing asynchronous requests.  Store successfully loaded resources in persistent storage, so that you do not reload them every time – this will be a part of an offline mode implementation. Don’t forget to clean up the cache. See sections 4.3.3 Caching for extra information  Monitor connection status events in order to automatically restart failed data transfer routinesImplementation of good recovery strategy will be simpler if your application follows Model-View-ViewModel (MVVM) design pattern. In this case you only have to deal with errors atthe data layer and report status to the UI through ViewModel.MVVM design pattern is well covered in this article: http://msdn.microsoft.com/en-us/magazine/dd419663.aspxAutomatic retryConsider implementing automatic retry only when performing lengthy or scheduled datatransfers. Don’t perform the retry immediately after the failure, as the failed networkinterface requires time to recover. Also, limit the number of retries, otherwise applicationmay quickly kill your battery. Here is an example of a good algorithm:  First retry after 1 minute  Second retry after 5 minutes  Third (and last) retry after 15 minutesTip: Consider Automatic retry for network applications which work under Lock ScreenChecking network connection status<V0.1> Page 54 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>Checking whether the network connection is established or not on Windows Phone 7 isimpractical as this information is not immediately available to your application. It may take acouple of seconds in order to determine the type of current network connection.This information is obtained via the NetworkInterfaceType property of theNetworkInterface class of the Microsoft.Phone.Net.NetworkInformation namespace. TheNetworkInterfaceType property returns one of the following values:  Wireless80211   Ethernet   MobileBroadbandGSM   MobileBroadbandCDMA   None Below is an example of how to obtain status and monitor changes of network connectiontype: using System; using System.Net.NetworkInformation; using System.Threading; using System.Windows; using Microsoft.Phone.Controls; using Microsoft.Phone.Net.NetworkInformation;  namespace ConnectionStatus {     public partial class MainPage : PhoneApplicationPage     {         // Indicates type of the current connection to the internet         private NetworkInterfaceType internetConnectionType;          // Main Page Constructor         public MainPage()         {             InitializeComponent();              // Subscribes to the Network Address Change notifications             NetworkChange.NetworkAddressChanged += new         NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);         }          // Standard Page_Loaded event handler         private void PhoneApplicationPage_Loaded(object sender,             RoutedEventArgs e) <V0.1> Page 55 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>        {             CheckCurrentNetworkType();         }          // Network Address Changed notifications event handler         private void NetworkChange_NetworkAddressChanged(object sender,             EventArgs e)         {             CheckCurrentNetworkType();         }          private void CheckCurrentNetworkType()         {             // Checking the network type is not instantaneous             // so it is advised to always do it on a background thread             ThreadPool.QueueUserWorkItem((o) =>             {                 // Determining type of current network interface                 internetConnectionType =                     Microsoft.Phone.Net.NetworkInformation.                     NetworkInterface.NetworkInterfaceType;                  // Synchronizing with the UI thread in order to update control                 Dispatcher.BeginInvoke(() =>                 {                     textBlockConnectionType.Text =                         internetConnectionType.ToString();                 });             });         }     } }  Bandwidth awarenessIn general the developer of a mobile application doesn’t care how the application’sinteraction with the Internet is routed; i.e. whether it goes over the cellular connection or aconnection to a local Wi-Fi hotspot. However for some applications the type of connectionmatters. Examples are applications that can offer an enhanced experience over a high-bandwidth Wi-Fi connection or those that want to take care not to over-use a broadbandmobile network.The following example demonstrates how to implement low and high resolution playback ina media playback application:<V0.1> Page 56 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>http://msdn.microsoft.com/en-us/library/microsoft.phone.net.networkinformation.-networkinterface.networkinterfacetype(v=VS.92).aspxReferencesNetworkInterface classhttp://msdn.microsoft.com/en-us/library/microsoft.phone.net.networkinformation.-networkinterface(v=VS.92).aspx4.3.3 CachingCaching of network resources is only partially supported by the Silverlight engine. TheSilverlight UI has in-memory resource cache which is designed for improving renderingperformance and optimisation of memory. In most cases this cache is filled with localresources, but network resources can be referenced as well. From the perspective ofcaching in general it only provides an advantage for network resources referenced multipletimes from within the XAML mark-up. As this cache is stored in memory it isn’t persistentand all data is lost with every process restart. When it is most important to improve theperformance of applications during the tombstoning cycle, this feature becomes absolutelyimpractical as all data loaded from the network is lost as soon as application is closed orsuspended.The bad news with respect to HTTP caching is that both WebClient and HttpWebRequestdo not implement any caching features. Implementation of caching features for yourapplication definitely requires additional effort but depending on requirements it might bepossible to put in place some simple workarounds:  Cached data feed – before parsing a recently downloaded XML or JSON data feed, first save it locally and then parse. Next time check whether you have to reload this data based on a fixed time interval. If not, load it from the local storage and process. This provides a good solution to Windows Phone Tombstoning  Image Cache – the approach here is to save downloaded images to the isolated storage first and then update the UI. If the namespace of image URL references is consistent it may be possible to implement simple naming for images files stored in one folder; otherwise a more sophisticated naming algorithm is needed. For any subsequent requests, first check whether you already have a copy of requested image, and then load it from the folder. This can be good for images that never change, otherwise you will have to implement content expiration policy and integrate it with your serverA few other tips:  bear in mind that not all data should be cached and this depends on the sensitivity of the information, its dynamic nature, etc.  some data may never change and therefore expire, such as logos  design independent data loader classes which can be reused throughout your application  don’t integrate the data loader with the UI, always feed data through ViewModel  use HttpWebRequest class with data loader, as it gives you the ability to access storage APIs and ViewModel on the Main thread from the callback delegate; synchronization with the UI thread will happen in ViewModel  the server component may already implement an expiration policy and communicate it via “Cache-Control”, “Last-Modified” or “ETag” HTTP headers (see RFC 2616 for<V0.1> Page 57 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN> full specification). It is relatively easy to read these attributes from WebResponse classBelow are a few examples from Windows Phone 7 community:Offline Data Cache in Windows Phone 7http://blogs.msdn.com/b/ukadc/archive/2010/10/21/offline-data-cache-in-windows-phone-7.aspxImage Caching on Tombstoninghttp://briankassay.com/blog/?p=954.3.4 SecuritySecure HTTPS communication is transparently supported by Windows Phone at all levelsincluding Silverlight UI framework (XAML referenced resources) WebClient andHttpWebRequest APIs. No additional effort on client is required in order to establishconnection with a server over HTTPS protocol: // Uri to secure resource System.Uri uri = new Uri("https://service.live.com"); WebClient webClient = new WebClient();  Or // Uri to secure resource System.Uri uri = new Uri("https://service.live.com"); // Create a HttpWebRequest object to the desired URL HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);  AuthenticationAt release date of this document, Windows Phone only supports Basic Authenticationprotocol which does not encrypt user name nor user password. However, in order toimplement secure authentication using Basic Authentication protocol, it is only necessary toensure that:  communication at the time of authentication is performed over encrypted HTTPS connection  data exchange after authentication is always performed over HTTPS connectionIt is not enough to encrypt user credentials and exchange them over unencrypted HTTPprotocol or authenticate user over HTTPS and afterwards communicate over HTTP as theuser’s Authentication token can be stolen and credentials compromised.Tip: Always communicate over HTTPS when using unencrypted authentication otherwiseuser credentials will be compromisedMutual authenticationAlthough you can install trusted certificates on the Windows Phone, in the current release,the platform does provide access to the installed certificates from applications. As a result<V0.1> Page 58 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>you cannot implement mutual authentication scenarios – scenarios in which the client sendsits own certificates to the web service in addition to receiving one.Storing user credentialsIsolated storage on Windows Phone is considered secure. However, make additional effortto encrypt user credentials before saving. This will protect user credentials in cases whenaccess to the application storage can be obtained as result of physical device theft,following a jailbreak or via accessing devices’ backup files. Windows Phone supports anumber of encryption protocols including AES, SHA1 and SHA256.Use example from the following source in order to encrypt your data:http://robtiffany.com/windows-phone-7/dont-forget-to-encrypt-your-windows-phone-7-dataReferencesWeb Service Security for Windows Phonehttp://msdn.microsoft.com/en-us/library/gg521147(v=vs.92).aspxSecurity for Windows Phonehttp://msdn.microsoft.com/en-us/library/ff402533(v=VS.92).aspxSystem.Security.Cryptography Namespacehttp://msdn.microsoft.com/en-us/library/system.security.cryptography(v=VS.95).aspx4.3.5 Data formatsWindows Phone 7 provides extensive support for XML-based services out-of-the-boxincluding WCF, XML serialization, DOM parser, Language Integrated Query (LINQ), XSDvalidation, etc.JSON is only partially supported which currently includes a limited serializer. For richersupport of JSON, you may consider Open Source product Json.NET (see reference below)which has a more flexible serializer, LINQ, conversion of JSON to and from XML.ReferencesJson.Nethttp://json.codeplex.com/DataContractJsonSerializer classhttp://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer(v=VS.95).aspx4.3.6 CompressionThe current Windows Phone 7 APIs do not support HTTP compression and fixing this issueis extremely difficult due to a number of limitations. Although decompressing contentencoded with GZip and Deflate algorithms is not difficult, and open source libraries such asSilverlight SharpZipLib are available, integration with WebClient and HttpWebRequestAPIs is not possible at this time. This is caused by protection put on HTTP Header “Accept-Encoding”.Example: // The following code will throw ArgumentException with the following message: <V0.1> Page 59 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>// The Accept‐Encoding header cannot be modified directly. // Parameter name: name httpWebRequest.Headers[HttpRequestHeader.AcceptEncoding] = "gzip"; 4.3.7 Background / Foreground modes rd3 party applications on Windows Phone platform can only work in the foreground andunder the Lock Screen if permitted to do so. Every time a normal application loses focus orcalls Launcher or Chooser, it is immediately instructed to shut down and is given 10seconds to save data. This process, called Tombstoning, supports navigation interface andapplication with some tools allowing the application to restore save and then restore it statewhen reactivated. Tombstoning, if not properly addressed, can have a significant impact onnetwork traffic, and user experience in general as applications often reload data from thenetwork when they are reactivated. This is considered a bad practice and always has to beaddressed by developers. Where appropriate, delay frequent updates – for instance don’trefresh a weather feed if the data was loaded minutes ago.ReferencesSilverlight SharpZipLibhttp://slsharpziplib.codeplex.com/Execution Model for Windows Phone (Tombstoning)http://msdn.microsoft.com/en-us/library/ff769557(v=vs.92).aspx<V0.1> Page 60 of 61
    • GSM Association Non ConfidentialOfficial Document <WG.NN>5 References1. WWDC 2010 Sessions 207, 208 - Network Apps for iPhone OS2. WWDC 2010 Session 200 - Core OS Networking3. WWDC 2010 Sessions 105, 109 - Adopting Multitasking on iPhone OS4. Network Efficiency Task Force Fast Dormancy Best Practices; GSM Association5. URL Loading System Programming Guide, Apple6. Error Handling Programming Guide, Apple7. Cocoa Fundamentals Guide, Apple8. RFC2616 – Hypertext Transfer Protocol HTTP/1.19. RFC2617 – HTTP Authentication: Basic and Digest Access Authentication10. Secure Coding Guide, Apple, 201011. Security Overview, Apple, 201012. Certificate, Key, and Trust Services Programming Guide, Apple, 201013. Keychain Services Programming Guide, Apple, 2010Annex 1Annex 2Document ManagementDocument HistoryVersion Date Brief Description of Change Approval Editor / Authority CompanyV0.1 21-09-2011 Updated input for TSG Kick-off TSG DTAGOther InformationType DescriptionIt is our intention to provide a quality product for your use. If you find any errors oromissions, please contact us with your comments. You may notify us at prd@gsm.orgYour comments or suggestions & questions are always welcome.<V0.1> Page 61 of 61