UNIT1
Introduction
If potential customers cannot reach your services, they're lost potential customers. Smartphones, tablets, and other non-traditional devices are pervasive within the market. Therefore the responsibility is on developers to assist customers get a product anywhere. Whether you’re a content provider, Product Company, or Service Company, expanding product reach is important. And one among the foremost effective ways to succeed in farther is to simplify a message in order that it are often delivered to a wider audience.
As of September 2011, Nielsen reports that 40 percent of all mobile consumers within thus over the age of 18 have smartphones. Wired states as of November 2011 that global smartphone usage has reached 30 percent.
A. Why Is Mobile Development Difficult?
The answer to the present question is that the same that plagues application developers for Mac and Windows, web developers, and mobile developers as seen from the general public eye. So-called killer apps aren't defined solely by what they are doing or how they appear, but rather by how they fulfil a requirement and codify it for the user.
Couple that with the more intimate nature of a mobile application, and therefore the more rigid UI design patterns of the mobile device and you get an ideal storm of potential problems.
The good news is that with proper planning and research, you target your potential clients and begin imposing your own parameters on the matter at hand, and therefore the rest are often accounted for within that scope.
Mobile development is difficult because the paradigms of design and functionality differ between it and kinds of development that have existed for many years. It’s still new, the technologies change rapidly, and not all of the answers are known. What makes an excellent app different from a good app? Design? Utility? These are all things to be mindful of while developing your app.
There are four major development targets. Each of the native frameworks comes with certain expectations and a user base. BlackBerry is usually utilized in education and government, whereas the iPhone and Android user base is way more widespread. Windows Phone 7 being the newcomer is employed primarily by developers and hasn’t necessarily hit its stride yet.
IOS, the technology that's run on Apple mobile devices, has benefits and limitations specific to its development cycle. The base language is Objective-C, with Cocoa Touch because the interface layer. At this point iOS are often developed only using Apple’s XCode, which may run only on a Macintosh.
The Android framework, on the opposite hand, is written in Java, and may be developed using any Java tools. The precise tooling recommended by Google and therefore the Android community is Eclipse with the Android toolkit. Unlike iOS, it are often developed on PC, Mac, or Linux. Like Android, the BlackBerry device framework is additionally written in Java; however, it's limited therein the Emulator and Distribution tools run only on Windows at this point.
The newest native framework on the market is Windows Phone 7 and its framework sits on top of the Microsoft’s .NET Framework. The language of choice is C# and therefore the framework lies during a subset of Silverlight, Microsoft’s multiplatform web technology. It also has the limitation that the Microsoft Windows Phone tools run only on Windows.
There are many myths related to mobile application development. It’s cheap, it’s easy, it’s unnecessary, you can’t make out without an outsized team, and you shouldn’t need to buy it.
Myth #1: It is inexpensive to develop a mobile solution.
As previously mentioned, mobile development isn't cheap. This doesn't include any development time, design time, and deployment time, or any potential money lost by taking too long to get to market. Iterative design and development are often expensive. Finding a cheerful medium is important to achieve success when developing a mobile solution.
Myth #2: It’s easy to develop a mobile solution.
Future we discuss the way to leverage existing data, use new technologies to show that data, interpret the nuances of the native development platforms, and use the newer third-party platforms for mobile application development. Additionally, plan to make learning these topics easier than simply hitting your favourite search engine and searching for tutorials. The method of developing a mobile application easier.
Myth #3: We don’t need a mobile presence.
With the smartphone market growing at such a large rate, and therefore the ease with which mobile applications become available through the market applications on the device and the markets’ respective websites there's an outsized set of potential customers to succeed in. Not everyone must become a mobile developer.
Myth #4: You need a large development team.
Many single-developer companies are successfully releasing quality applications on the various platform markets. Certainly, a jack-of-all-trades can take a thought from wireframe to plug. That being said, without a significant QA resource, development resource, and design resource it are often difficult to interrupt away from the cookie-cutter sort of applications very prevalent within the market.
Myth #5: Sweat equity can pay for the application.
Not to disparage the act of making a start-up, and to not fly within the face of innovation, but potential and dreams don't always a fortune make. Working with a partner to develop a product or solution with no capital isn't easy.
Eventually, something has got to give; when bills are available it's generally the “side project” that falls by the wayside. Believe that before you start. Good luck if you begin on the road to becoming a contractor it's not a simple path to travel. Now that you simply know what mobile technologies are out there, which you understand the varied myths surrounding mobile development.
There are variety of third-party frameworks for mobile development. The thought of the “write once and deploy to several languages” is that the key force driving these frameworks. There are a couple of different types: interpreted, translated, and web. Translated frameworks take a single language and use a one-for-one replacement to develop a binary within the native language. Web frameworks use the native language’s control for displaying web page, and stick developer-generated HTML web applications in it.
They also use plugins to afford native device functionality inside the online application. Lastly are the interpreted frameworks: immediately the Mono products are the only ones that fall under this category. They use a rewrite of the .NET Framework to interpret the code during a native application.
A. Appcelerator Titanium Mobile Framework
Released in December 2008, with support for iOS 5 and Android 4.0, Appcelerator is additionally looking to release a version which will build and deploy to BlackBerry. The framework heavily utilizes a JavaScript API, and therefore the build process creates source code within the languages you build to. IOS gets an Objective-C source and project binary, and Android gets a compressed Java source and project binary. Titanium effectively translates its specific JavaScript objects into native objects.
B. Nitobi PhoneGap
Released in March 2009, Nitobi was acquired by Adobe in late 2011. It’s now up to version 1.2, with support for iOS, Android, BlackBerry, WebOS, Symbian, and Windows Phone 7. This framework uses standard HTML5 and CSS3 elements wrapped in the native web browser controls to simulate a native application.
C. MonoDroid and MonoTouch
This newly formed company is formed from the first Ximian Team after being acquired by Novell. Later discontinued by Attachmate, Xamarin is now the developers and maintainers of the MonoTouch and MonoDroid products. The Mono project itself is an open source implementation of the .NET Framework in order that C#-based .NET applications are often developed on systems aside from Windows.
MonoTouch
Initially developed by the Mono Team, MonoTouch is way of developing iOS apps using .NET and the Mono Framework. First released in Q3 2009, the Mono Team maintain the project, and version 5 released Q3 2011 includes iOS 5 support.
MonoDroid
Compared to MonoTouch, this project is in its relative infancy, with the first major release in Q2 2011. MonoDroid helps users to develop and distribute Android applications using Windows and the Visual Studio environment.
A. Mobile Web Presence
It’s not a matter of if you would like a mobile web presence, it’s a matter of how fast are you able to get it done. In 2010, quite 63 million people within the accessed the web from a mobile device. Technology research firm Gartner states there'll be quite 1.7 billion mobile Internet users worldwide by 2013. Without a mobile web presence, you're missing out on customers; if you are doing not have a mobile web presence, your competitors will. Establishing a mobile presence early could get you a very important start during a fast-growing technology.
Figure 1.5(I)the increase within the number of mobile Internet users
Looking through the Google Analytics of quite 60 websites that we work with, the share of mobile traffic was about 19 percent in 2011. Across the web, this tends to get on the high end, with most others reporting between 10 and 15 percent. With mobile traffic as high because it is, and growing more popular, it's time to have a mobile website.
Most reputable companies have an internet site, but many don't translate very well to a mobile device. A mobile web presence takes the desktop site content and renders the knowledge to be easily consumed on a mobile device. In recent years, Internet users and customers have begun to relate the design of a company website to how reputable a business is. Although not always the case, a well-developed and maintained website with fresh content informs the user or customer that the company cares about them, and needs to form sure they have the tools required to comfortably do business.
Mobile Content
A mobile website experience is different from the desktop view. With a limited screen size, new usability techniques are developed to assist people view and navigate data. Mobile web browsers do the simplest job they will , providing rich tools for panning and zooming through an internet site , but commonly used, complex drop-down menus make mobile navigation troublesome.
Navigation is one among the most important, and sometimes most difficult, areas of mobile website design. It’s common to present users with thinned-down content they will access on a mobile device. When within the planning stages of your mobile website project, plan for time to develop a content strategy. Following figure is an example of a company with an excellent deal of content on its normal website. A drop-down menu with multiple levels wouldn't provide the simplest interaction on a mobile device. Figure shows the mobile rendering.
Figure 1.5(II) Desktop website of a commercial site
Figure 1.5(III) Mobile version of site
Mobile Browsers
Let’s give credit to the developers of mobile web browsers. Mobile browsers are built to render websites not intended to be displayed on small devices also provides tools to zoom, pan, scroll, and highlight links help make browsing normal websites more tolerable. Following figure shows the highest five mobile browsers. In 2011 notice the rise of usage from the Android browser and therefore the decrease of usage from the BlackBerry browser, which coincides with the Android bumping BlackBerry off the highest spot for market share for mobile devices in 2011.
Figure 1.5(IV) Top five mobile browsers
Following Table shows the mobile browser share throughout the planet. It’s important to understand this share also. Different countries favour different devices. For instance , if most of your customers are within the South America, you'll want to make sure your mobile website renders well on Symbian devices.
Figure 1.5(V) shows Mobile OS Market Share by Country as of February 2012
Mobile User Browsing Behaviour
Not all mobile web presences should be created equally. So as to make an excellent mobile interface, you should spend time identifying behaviours of mobile users. Although this phase is simply asking a couple of internal employees, it’s important to research how the mobile version of the present website will differ, and design for that behaviour. The subsequent list gives some reasons why users might need access to your mobile content:
- Repetition: Users are returning to your site constantly. It’s possible they're sitting on the page and hitting refresh to visualize new content. The question is, is site content changing frequently enough that users would come and check for updates? Sports scores, weather reports, and stock quotes are kinds of content that require to be available, and fast, on mobile devices.
- Boredom: Maybe users try to pass time within the lobby of a doctor’s office. They’re surfing the online like they are doing within the comfort of their house, but publicly. They might have heard a radio announcement a few cleaning service and have an interest, in order that they navigate to the company’s page to find out more information about the offer while they're passing the time.
- Urgency: Users are out and about and have the urge for a hamburger. They required to find the nearest open burger joint.
B. Mobile Applications
The decision to make a mobile application are often difficult. It’s not a choice to rush into, and it requires an excellent deal of thought. A mobile application are often a chance to enhance interaction with customers, create brand awareness, and even create additional revenue. But if the objectives of the app are unclear, customers are often upset, and money are often lost.
In a June 2011 study, mobile analytics company Flurry found that point spent using mobile applications surpassed time spent using the mobile browser only within the us ; other countries haven't become as “app crazed” because the United States. Figure shows these figures. With users spending this much time in mobile applications, its worthwhile looking into creating a mobile app if your business domain features a good fit.
Figure 1.5(VI) Mobile browsing behaviour in the U.S.
You’re a Mobile App If . . .
Developers wish to find a particular answer to all or any of the world’s problems, but the world isn't as black-and-white as we all may like. The subsequent list provides some scenarios where a native app would be the simplest solution:
- If you required graphics and processing power
- If you required the use of the device’s camera
- If you have to use the device’s microphone
- If you required access to the device’s address book
- If you require access to the device’s media library
- If you will be using the market for payment
- If you require use of push notifications
- If you need to run as a background service
- If you have to design a game
When to Create an App
Mobile apps offers how for patrons to attach with a brand, if done correctly. a reasonably UI that gives no value are going to be rated poorly within the market or iTunes. Simply because you develop an app doesn't mean it'll be successful: it must provide value.
You're just beginning to develop a mobile strategy or are performing on it for a few time, don't let the allure of a mobile app trap you into making a choice.
New Revenue Sources
Monetizing your hard work are some things all mobile app developers want, whether it’s to extend your job security or for private gain. The mobile trend has opened new ways for developers/companies to form money off their apps.
• In-app purchasing for mobile applications has revolutionized digital commerce. People are trying to find convenience, and may purchase tangible and digital goods with one click, reducing buyer hesitation. Adobe reports that 62 percent of consumers with mobile devices are purchasing goods through those mobile devices, which equates to billions in revenue.
A more debated use of in-app purchasing/micropayments was developed within the Smurfs Village app for iOS. The Smurf Village app is a time-elapsed game, targeted at children. To hurry up the sport, you'll purchase Smurf Berries at varying rates from $5 to $99. Consider the amount of injury little child could do on a Sunday afternoon to your credit card.
• With print media on the decline, many traditional media companies have seen the trend that individuals are purchasing digital content. This has been popular subscription-based services, like magazines or newsletters. New tools within both iOS and Android provide APIs to sell content. This technology has brought new life to a dying industry.
Figure 1.5(VII) Plans to develop an app
Types of Mobile Apps
When development of your mobile app is finished and therefore the app is being deployed to the market, you're required to place it into a category within the market to allow users to get your app more easily. Within all markets, apps are divided into categories, and a few categories are more popular than others. It’s common across all of the markets to see games being a large percentage of the kinds of apps available for the platform. Figure shows a distribution of apps in Android Market provided by AndroidZoom.
Figure .5(VIII) Types of apps in the markets
Do People Really Want to Put Your App on Their Mobile Device?
A study from Nielsen across a good range of phone users have found that iPhone users install the most applications, coming in at 40 apps.
Although users will visit many websites during a day, they're going to install only a couple of apps. Does your app provide enough value that the user goes to require the time to download it and keep it in their list of installed apps? the only thanks to determine if you app has value is user research. This research are often an easy question/answer session among peers, or might be a proper user research study.
Figure 1.5(IX)Average number of apps installed per platform
Resources
Do you have the developers on staff to develop the app? If you are doing not have the staff, are you ready to gauge a mobile developer’s talent? Are you willing to try and do what it takes to support the app or do you have to consider outsourcing the event to a professional firm? These are a number of the questions you would like to ask yourself before jumping into creating a mobile app.
Support and Maintenance
Mobile apps are software projects like any other. They take care and feeding; a little more than a standard website. Mobile development is same as desktop development in many ways. Once you deploy it, it’s deployed and there is not a good way to update the app. You can’t force users to get updates to the app, and when they find a bug you fixed two versions ago, they will give you poor feedback in the market. When you publish an update of your app to the market, it shows up in the available downloads, but many users do not update their apps.
The developer accounts for iOS, Android, and BlackBerry contain tools that show the stack traces of runtime errors that are uploaded from your app on the customer’s phone. Be proactive, and go through the logs and look for errors before someone know about them.
Development of Your Mobile Solution
If you are planning on creating a mobile app, you support iOS and Android. Depending on the industry, you take on BlackBerry; schools and government agencies are big BlackBerry users. When it comes to the initial development of the app, you have many choices and development platforms to choose from (native vs. Non-native).
Some platforms supports iOS apps to be created without using Objective-C, but do you have the in-house staff to make these decisions? If you decide that creating mobile apps is part of your strategy, we recommend that you spend time with someone who has worked in mobile environments before. Not just a few web videos actually take the time to sit down with a mobile developer to see the tricks of the trade. Many issues arise with emulators, SDK versions, and small things that are difficult to find in the documentation, that pair programming with someone who has created an app on that platform could point out.
Benefits of a Mobile App
Not only will your marketing department get to brag about your newly developed mobile application using the latest technology, but numerous other reasons exist why it may make sense to develop a mobile app as opposed to a mobile web app.
Make Use of the Native Devices Features
It will always be easier to stretch the hardware boundaries of a mobile app. Great features like in-app purchasing don't have an equivalent tight integration with the UI and OS unless you're creating a native app. Even if you choose to travel with a non-native solution like Titanium, PhoneGap, or MonoTouch, these solutions are slow to adapt new features during a platform’s OS .
Sometimes it’s not about being on the bleeding edge of technology; it’s just delivering value to your customer.
Offline Content
Many business apps got to display changing data to the user. Depending on the business domain, a mobile web app might not be an honest idea. For instance, a mobile application that lists all of the state legislators requires the information of the app to return from someplace. The capital in Michigan doesn't get reliable cellular coverage, so for this app to function properly, an offline caching strategy should be used.
When having the info stored locally, you should also define a technique on how that offline data goes to be updated. Is it updated when the app is updated through the market or perhaps there a background service that checks to ascertain if the device has access to the web, and prompts the user if they might wish to obtain a refreshed set of information? Mobile apps have an extended history, and rich set of tools for developers to anticipate the app working without Internet connectivity.
Richer User Experience
Users generally provide higher ratings for apps that have the native interface. Regardless of how nice the iOS interface is, if you create an Android app and supply UI elements from iOS, users are more likely to rate your app lower.
Users search for apps that have a UI that's according to the remainder of the apps on their device. It’s possible to make HTML and CSS that provide these interfaces on a mobile web app, but it can get difficult. Many developers choose creating interfaces that don't resemble iOS, Android, Windows Phone 7, or BlackBerry. It’s a design the developer created on their own. Such a design strategy can work, as long because the right amount of user interface research has been performed. In most cases, however, it’s best to only persist with the UI you must be working with, which is that the native UI for the platform.
Ease of Discovery
Markets provide an area to present your app to the globe. Most users aren't using a search engine to find apps for his or her mobile devices; they're using the built-in search tools within the installed market tool.
Push Notifications
In recent years, text messages became the preferred communication over instant messaging among youngsters. A moment notification on your mobile device means an instantaneous response is predicted . Push notifications simulate an equivalent behaviour of text messages, but are app based. Push notifications alert users of something that they must remember of instantly: a new e-mail, a new tweet, or another little bit of information which will be important to the app that was downloaded.
Increased Customer Feedback
Businesses often hope to create brand loyalty through apps. When loyalty has been achieved, you'll maximize this loyalty within the app, asking for feedback about your company. Quick polls, short forms, and rich integration with social media services like Facebook and Twitter can provide a level of feedback that's not seen with mobile web apps.
Your App as a Mobile Web App
Mobile web apps are a particularly popular solution to the “mobile app versus mobile website” problem, because they're relatively easy to make and maintain. The popularity of mobile web apps has grown proportionately to the popularity of smartphones. In 2001 alone, an estimated 1.5 million mobile web apps were downloaded.
Mobile web apps, during a nutshell, are mobile apps created using HTML and CSS, viewed in mobile web browsers. Mobile web apps differ from mobile websites by having a focused application purpose, like native mobile apps do.
Figure shows an example of a mobile web app that has been designed with the platform UI in mind, during this case different interfaces for the iPhone and iPad. A good mobile web app will have business logic abstracted into a standard library. This may leave platform-specific UI code to be created that calls into this common library, keeping the app easily maintainable.
Figure1.5(X) Mobile web apps
Mobile web apps span across many categories of apps. In some cases, like shopping, mobile web apps are more popular choices. Figure shows a comparison of mobile web apps versus native apps.
Figure 1.5(XI) Mobile web app vs. App Store categories
Mobile web apps have a beautiful development story. Designers, front-end web developers, and even back-end web developers can create app using HTML and JavaScript with familiar tools. With the introduction of HTML5, many features are added to mobile browsers that help achieve this functionality. Table shows an inventory of mobile capabilities between the varied mobile platforms.
Figure 1.5(XII) Native vs. HTML5 Device Features
If you're trying to find a quick solution which will be developed with resources you'll have already got access to, a mobile web app could also be the higher solution. The following benefits may sway your decision in favour of making a mobile web app:
- Easier to get started: HTML may be a popular technology, so there's a good chance that the developers on the team will have already got experience with the language. Besides the convenience of use of the language, there are not any start-up costs, licenses, or large SDKs to download as there's with native app development. Most developers are willing to find out something new, but are overworked. Once they want to get into something, they need to try to it now, not need to await two weeks before they will get going.
- Easier cross-platform development: Creating a mobile web app will make it easier for you to make a codebase where parts of it are often shared. Depending on the app type, be prepared to make a new UI for every platform deployment.
- HTML5 offers rich features: we've all heard that HTML5 makes it easy to make mobile web apps. HTML5 offers great new features that make mobile web apps a viable solution rather than developing a mobile app. The reality is that HTML5 is simply a tool during a mobile developer’s belt, and with it, developers and designers can provide apps to users that are usable and compete with native mobile apps.
- Easier updates: Not all users will update your mobile app. But if you've got control over what the user sees, app updates are often made at any time. This is often one among our favourite features about mobile web apps. With a mobile web app, there's no complicated process for publishing it's a bit like launching any regular website.
- No approval process: With a mobile web app, there are not any constraints on if your app are often published or not. When the Google Voice app wasn't approved within the iTunes store, Google released a mobile web app that provided an equivalent functionality without the iTunes hassle.
Many of today’s mobile applications are personalized and aren't useful if they will only access the information on the phone. For a user to get, for instance, sports scores, retrieve stock quotes, or perform accounting work, the mobile device must communicate with one or more servers. The simplest thanks to achieve this communication is through web services.
Web Service
A web service enables two electronic devices to communicate over the web . The world Wide Web Consortium (W3C) defines web service as “a software designed to support interoperable machine-to-machine interaction over a network.” In practice this suggests a server communicating over port 80 or port 443 in plain text to the client.
Other methods of communication are remote procedure calls (RPC), the distributed component object model (DCOM), and therefore the common object request broker architecture (CORBA). These methods of communication don’t work well through the web thanks to firewalls and therefore the data formats they use. Typically their data formats are specific to whatever tool created the service, and it becomes a significant challenge to have a Java application read data from a .NET or C++ application.
They generally also use a selected port, which needs IT departments or, even worse, home users, to troubleshoot and configure their firewalls to permit the appliance to communicate. Finally those technologies don’t work well through the web because they aren’t designed to figure with the Hypertext Transfer Protocol.
Examples of Web Services
Think how easily an application are often written using that data. This is often the ability of web services. By making your data easily consumable through web services, others can use the information you've got created in ways you never imagined.
Not convinced yet? What if you wanted to display the weather for Lansing, Michigan, on your web page? How hard would that be to program? For starters, you'd need to purchase equipment to measure the temperature, wind speed, and humidity, which might be expensive. Then you'd need to program that equipment to report the data to an internet server, which might then display that information on your website .
This is sounding difficult, and there are many issues that haven’t been addressed yet, like reliability. Rather than doing all that work, leveraging an internet service are going to be much faster. Simply type this URL into an internet browser: http://www.google .com/ig/api?weather=Lansing,MI. No equipment required, no risk of schedule overruns, and if requirements change and therefore the software must display the weather for Lake Odessa rather than Lansing, you only replace the Lansing,MI on the end of the URL with Lake Odessa,MI.
Advantages of Web Services
The primary advantages web services provide are simple access and simple consumption. Web services advantages stem from simplicity. Usage of web services for data exchange has exploded thanks to these advantages.
Web services are easy to access because they use an equivalent World Wide Web technologies like web browsers and web servers that power the web . These technologies have proven to be robust and work great for web services even as they work great for delivering sites . they need no firewall issues with special ports like other communication technologies, and every one modern programming languages provide how to get sites and, therefore, to consume web services.
The second advantage of web services over other technologies is that the censurability, which is that the ability to know what the server is communicating. Web services use plain text for this. Other technologies like RPC, DCOM, and CORBA use the in-memory representation of their objects for transmission or use a custom data exchange format. These complexities make it expensive for languages to interoperate with the data. The memory representations don’t have friendly text like , which most of the people can guess contains zip code information; the server might send something like 1011111100001010, which could represent many pieces of data .
For communication to occur between two people they have to talk the same language. Computer systems work an equivalent way they also got to use the same language. Most computer languages that are widely known, like C++, enable humans to speak to computers. But those computer languages are hard for both computers and humans to know because computers only understand zeros and ones, and represent all data as zeros and ones.
For example, the number 5 is represented as 00000101 during a computer. A lowercase h is represented as 01101000, and 01001000 represents an uppercase H. Binary representations are the most efficient way for 2 computer systems to exchange data.
One of the explanations web services are so successful is due to their self-describing nature. Rather than giving variety like 5 and hoping the user of the web service knows that 5 may be a weight, an age, or dollars, the 5 is described during a service like this: . This states clearly the measurement is for length and is 5 inches.
Format choice is an important decision it impacts the convenience of accessing the web service and therefore the performance of your application. When designing a web service, consider how the service are going to be accessed. For instance , mobile devices have less processing power than their desktop counterparts, and therefore the different platforms (BlackBerry, Windows Phone, Android, and iOS) have different programming APIs available for accessing and consuming the information.
The two self-describing formats that have began for web services are XML and JSON. i like to recommend sticking with one among these two formats to maximize the convenience of consuming the services and maximize developer productivity.
EXtensible Markup Language (XML)
XML was designed as how to explain documents, but it took off as an information interchange format after it had been introduced. XML was envisioned to be an easy human-readable language; for instance, an individual object are often represented like this in XML:
<person>
<firstname>David</firstname>
<lastname>Smith</lastname>
</person>
And the same person can also be represented like this:
<person firstname=”David” lastname=”Smith” />
Both XML fragments are easy for an individual to know , but different representations make it harder for programmers to write down correct software. Having one agreed-upon representation of the information will speed up your development effort.
XML enables you to define the language systems wont to communicate by creating an XML Schema Document (XSD). This permits software to verify an XML document conforms to a predefined contract. For instance , the XSD can specify that the value of a movie must be variety . XSD also provides the benefit of enabling tools to get code supported the XSD. Programmers can increase productivity by feeding their programming tool an XSD fi le and getting back code they will immediately use to interact with the data. Without the XSD file programmers need to write code to know the XML.
One of the explanations for selecting XML is that the maturity of the platform. It's been around since February 1998. It's many tools around it XPath, XQuery, XSLT, and XSD. Since it's a mature language, many systems work well with XML. These advantages make XML a good choice for data interchange and it's going to even be required for a few projects to figure with existing systems.
EXtensible Stylesheet Language Transformations (XSLT)
XSLT is employed to transform a document into another representation. Initially it had been envisioned as primarily changing XML data documents into representations for human consumption, like XHTML. Another common use is applying an XSLT transformation to at least one application’s XML output to be used by another application that doesn’t understand the original representation.
The following example shows how XSLT can transform an XML data fragment for display on a web page. This fragment: <person><age>30</age></person> would better be displayed on a web page like this: <span>Age:30</span>.
The following XSLT will loop through each element in the XML with the name of person. Within each person node, the XSLT will then output the span tag with the value of the age element included within the span tag.
<xsl:template match=”/”>
<xsl:for-each select=”person”>
<span>Age:<xsl:value-of select=”age”/></span>
</xsl:for-each>
</xsl:template>
XQuery
XQuery is used to retrieve a subset of data from a full XML document, same as a SQL query is used to retrieve a subset of data from a database. This example represents how to get the total amount paid for this sample order:
<order>
<item price=”50” currency=”USD” name=”metal gear” />
<item price=”25” currency=”USD” name=”plastic gear” />
</order>
The following XQuery returns the sum:
Sum(doc(‘orders.xml’)/order/item/@price)
A. JSON
JavaScript Object Notation (JSON) was created in 2001 and came into use by Yahoo in 2005. JSON has few rules, few base types, and is human readable. JSON schema enables document validation, but this is often rarely used. JSON may be a great format for transmitting data between systems because it's simple, text based, and self-describing.
A person can be represented in JSON like this:
{
FirstName : “David”,
LastName : “Smith”
}
One thing to observe out for is how dates are represented in JSON. There's no base kind of date and there's no standard way to represent dates. It's recommended to represent dates using the International Standards Organization 8601 format. In ISO-8601 dates appear as if this: 1997-07- 16T19:20:30.45+01:00. Representing dates in ISO-8601 keeps them human readable, ensures programming languages can parse them, and keeps time zone information.
Choosing ISO-8601 because the default data interchange format for projects may be a good idea. Using JSON will reduce the amount of your time spent handling serialization issues.
B. Transferring Nontextual Data
Both JSON and XML create human-readable text documents. What happens if a service must transmit or receive a picture , a video, or a PDF document, like a check image for a financial service or a video clip for a public safety service? this sort of nontextual data is named binary data.
When transmitting binary data as text, it must be Base64 encoded so it are often represented with the remainder of the information. Base64 encoding comes with two downsides. First, the size of the text representation increases by 33 percent. Second, there's additional processing overhead by both the sender and receiver for encoding or decoding the Base64 data to binary and the other way around.
Creating an Example Web Service
The technologies behind creating a consumable web service, shows the way to create a consumable web service during a Linux Apache PHP environment, and three different service delivery technologies on the Microsoft .NET stack like WCF, OData, and ASP.NET MVC.
Using the Microsoft Stack
The .NET platform has a variety of technologies enabling the easy creation of consumable web services.
Creating the Datastore
The example services will expose a simple data model consisting of two tables: Leagues and DerbyNames. a number of the Gravity Works staff are Roller Derby fans. They noticed the players had interesting names and decided their information would make a good example service.
Open SQL Server Management Studio 2008 and connect with the local SQL Server instance running on the machine. Open a new query window and run the SQL-Server-CreateDerby-Database script to make the tables and insert the information used for the rest of the walkthroughs:
After running the script, SQL Server Management Studio will display “Query Executed Successfully.” The walkthroughs during this section use this database to retrieve data.
Using Windows Communication Foundation
Windows Communication Foundation (WCF) may be a .NET Framework library designed for developers to make communication endpoints for software. Web services are software communication endpoints, so on the surface WCF looks like a perfect choice for creating consumable web services. Unfortunately, WCF is meant for a broad number of communication scenarios, and this broad set of capabilities introduces a lot of complexity that's not necessary for web services. For instance , WCF supports reliable sessions, transactions, TCP, named pipes, Microsoft Message Queuing, activity tracing, and Windows Management Instrumentation.
This walkthrough assumes the following software is installed:
- ASP.NET 4.0
- Visual Studio 2010
- IIS 7.5
- Microsoft SQL Server 2008 R2
1. Open Visual Studio and choose File ➪ New Project to create a new project.
2. Within the New Project template selection screen, open the Visual C# node and choose the WCF node.
3. From the WCF project type’s display, select WCF Service Application. If that project type doesn't display, confirm that the filter at the top of the dialog box is set to .NET Framework 4.
4. Set the project name to DerbyNamesService and click on OK.
For simple database access this walkthrough uses LINQ to SQL. LINQ to SQL is an Object Relational Mapper technology that ships with the .NET Framework. Using LINQ requires an additional project regard to System.Data.Linq.
To add the reference, right-click the References node of the DerbyNamesService project and choose Add Reference. In the Add Reference dialog box, find System.Data.Linq and click Add button.
After adding the System.Data.Linq reference, you would like to make a category to access the information. To try and do this, right-click the DerbyNamesService project and choose Add ➪ New Item.
In the Add New Item dialog box, select Class, name it DerbyContext, and click on the Add button.
The DerbyContext class will provide the information. To display the data as .NET objects, add two extra code files: DerbyNames and Leagues. The DerbyNames class contain the data on a derby player. Make the DerbyNames.cs file contain this code:
Using System;
Using System.Data.Linq.Mapping;
Namespace DerbyNamesService
{
[Table]
Public class DerbyNames
{
[Column(IsPrimaryKey = true)]
Public int DerbyNameId;
[Column]
Public string Name;
[Column]
Public string Number;
[Column]
Public DateTime? DateAdded;
[Column]
Public string League;
}
}
The Leagues class consist information about the derby leagues like the league name. Make the Leagues.cs file contain this code:
Using System.Data.Linq.Mapping;
Namespace DerbyNamesService
{
[Table]
Public class Leagues
{
[Column(IsPrimaryKey=true)]
Public int LeagueId;
[Column]
Public string LeagueName;
[Column]
Public string URL;
[Column]
Public string StateProvince;
[Column]
Public string CountryCode;
}
}
The DerbyContext is the class providing access to the database from the DerbyService class. Modify the DerbyContext.cs has this code:
Using System.Data.Linq;
Using DerbyNamesService;
Namespace DerbyNamesService
{
Public class DerbyContext : DataContext
{
Public Table<DerbyNames> DerbyNames;
Public Table<Leagues> Leagues;
Public DerbyContext()
: base(“Data Source=.;Initial Catalog=DerbyNames;
User Id=webUser;Password=webuser;”)
{
}
}
}
In the Visual Studio Solution Explorer, rename Service1.svc to DerbyService.svc then rename IService1.cs to IDerbyService.cs. If Visual Studio prompts if you want to rename all project references, click Yes. This step is simply a cleanup step to rename the default files Visual Studio creates. The IDerbyService interface defines the contract for the service, this interface will expose the operations the service provides. Change the IDerbyService.cs file to contain the subsequent code:
Using System.Collections.Generic;
Using System.ServiceModel;
Namespace DerbyNamesService
{
[ServiceContract]
Public interface IDerbyService
{
[OperationContract]
Public IEnumerable<DerbyNames> PlayerNames();
[OperationContract]
Public IEnumerable<Leagues> Leagues();
}
}
With the contract defined, a category to implement the operations defined by the IDerbyService contract must be created. The DerbyService.svc.cs file will implement the contract. In other words, the contract states what the service will do and therefore the DerbyService actually does the work. Open the DerbyService.svc.cs file and replace the existing code with the subsequent code:
Using System.Collections.Generic;
Using System.Linq;
Using System.ServiceModel.Web;
Namespace DerbyNamesService
{
Public class DerbyNames : IDerbyNames
{
[WebGet(UriTemplate=”/PlayerNames”)]
Public DerbyName GetNames()
{
//get all the names from the database.
Var names = new DerbyContext().DerbyNames.ToList();
Return names;
}
[WebGet(UriTemplate=”/Leagues”)]
Public IEnumerable<Leagues> Leagues()
{
//Get all the leagues from the database.
Var leagues = new DerbyContext().Leagues.ToList();
Return leagues;
}
}
}
Previously when Visual Studio asked to rename project references, it was only referring to C# code. The DerbyService.svc markup contains text that needs to be updated. To make the change Visual Studio missed, right-click the DerbyService.svc file and select View Markup.
Change the text Service=”DerbyNamesService.Service1” to Service=”DerbyNamesService .DerbyService” to match the class renaming you performed earlier. To make the service accessible it needs to be specified in the web.config. In this context, the service endpoint is effectively a website to which you connect your client code. This site will receive communications from your client over HTTP, and return objects from your data source as text. To specify the service endpoint, insert the following XML as a child node of the system.servicemodel node:
<services>
<service name=”DerbyNamesService.DerbyService”>
<endpoint binding=”webHttpBinding”
Contract=”DerbyNamesService.IDerbyService”/>
</service>
</services>
To make the service return XML for easy consumption by mobile devices, insert the following XML as a child node of the behaviors node:
<endpointBehaviors>
<behavior>
<webHttp defaultOutgoingResponseFormat=”Xml”/>
</behavior>
</endpointBehaviors>
The final web.config should look like this:
<?xml version=”1.0”?>
<configuration>
<system.web>
<compilation debug=”true” targetFramework=”4.0” />
</system.web>
<system.serviceModel>
<services>
<service name=”DerbyNamesService.DerbyService”>
<endpoint binding=”webHttpBinding”
Contract=”DerbyNamesService.IDerbyService”/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior>
<webHttp defaultOutgoingResponseFormat=”Xml”/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled=”true”/>
<serviceDebug includeExceptionDetailInFaults=”false”/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled=”true” />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests=”true”/>
</system.webServer>
</configuration>
After all that work, the service is coded and configured. Click the solution and start debugging. Visual Studio will launch the ASP.NET Development Server and launch the system default browser with a URL similar to http://localhost:13610. The number is the port on which the ASP.NET Development Server is delivering requests. Add /DerbyService.svc/PlayerNames to the end of the URL to get the PlayerNames.
With the service returning data, you can now have some fun! Using the Chrome Developer Tools will show the service response payload is 3.07KB. You can open the Chrome Developer Tools by using the keystroke Ctrl+Shift+I in Google Chrome.
Change the protocol to JSON and see what happens. WCF makes this change easy. Open the web.config fi le and find the webHttp node under the behaviour node. Change the defaultOutgoingResponseFormat from XML to JSON. The node should look like this:
<webHttp defaultOutgoingResponseFormat=”Josn”/>
Then rebuild the project and navigate back to the ASP.NET Development Server URL /DerbyService.svc/PlayerNames. On my machine, Chrome developer tools show the response size is now 2.22KB, which may be a 28 percent reduction in size from the XML format. This reduction in size will end in faster transfer times, especially for larger data services. I recommended using JSON because the default format and providing XML as long as the requirements demand it.
The next improvement to form is getting URLs that make more sense. The URL /DerbyService .svc/PlayerNames doesn’t look nice. a far better URL would be /RollerDerby/PlayerNames. ASP.NET routing is that the easiest method to get the URL /RollerDerby/PlayerNames.
Routing is made into ASP.NET, but to get it to work with the service you would like to feature one reference. Expand the DerbyNameService project node, right-click References, and choose Add regard to mention Add Reference dialog box. Select the .NET tab and fi nd System .ServiceModel.Activation. Click ok to add the System.ServiceModel.
Right-click the DerbyNames project and choose Add New Item from the menu. From the Add New Item dialog box, select Global Application Class, and click on the Add button to add it to the project.
Find the Application_Start method within the worldwide .asax file and add the subsequent line of code within the method:
RegisterRoutes(RouteTable.Routes);
Below the Application_Start method, add the following method:
Private void RegisterRoutes(RouteCollection routes)
{
Routes.Add(new ServiceRoute(“RollerDerby”,
New WebServiceHostFactory(), typeof(DerbyService)));
}
The RouteTable class is in the System.Web.Routing namespace. The WebServiceHostFactory and ServiceRoute classes are in the System.ServiceModel.Activation namespace. Add these using statements at the top of the file to resolve the references:
Using System.Web.Routing;
Using System.ServiceModel.Activation;
For ASP.NET routing to work, WCF requests need to fl ow through ASP.NET. To turn this feature on, open the web.config file and find the serviceHostingEnvironment element. Add the attribute aspNetCompatibilityEnabled=”true” . The serviceHostingEnvironment element should look like this:
<serviceHostingEnvironment multipleSiteBindingsEnabled=”true” aspNetCompatibilityEnabled=”true” />
ASP.NET routing also requires the service class be attributed stating it supports ASP.NET compatibility. To enable this, open the DerbyService.svc.cs class and add the AspNetCompatibilityRequirements attribute like this:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
The AspNetCompatibilityRequirements attribute is in the System.ServiceModel.Activation namespace, which requires the following using statement:
Using System.ServiceModel.Activation;
After making those changes, compile and run the project. Navigate to the URL /RollerDerby/ PlayerNames and the same JSON document displayed in Figure will display. The browser displays the strange looking page as shown in Figure.
Figure 1.7(I) A typical 404 page
Using Chrome Developer Tools shows the response has the correct 404 code. This is the same result when navigating to the root service: /RollerDerby. It would be better if missing pages were controlled by the DerbyService class. Fortunately, the WebGet attribute applied to the service methods gives control of the URLs.
To deliver a 404 page that doesn’t expose the underlying technology as WCF, add the following method to the DerbyService class:
[WebGet(UriTemplate=”*”)]
Public void ErrorForGet()
{
Throw new WebFaultException(HttpStatusCode.NotFound);
}
The method name doesn’t matter. The functionality is coming from the UriTemplate parameter. The asterisk means if there isn’t a better match, run this attributed method for the request. The HttpStatusCode class is in the System.NET namespace, which requires the following using statement:
Using System.Net;
Change the DerbyService class so it does not implement the IDerbyService. Because it is not using the IDerbyService, add the ServiceContract attribute to the DerbyService class, which requires the following using statement:
Using System.ServiceModel;
The final change to remove the response body is a web.config change. Find and remove the Services node along with its child service node. After rebuilding, running the application, and navigating to /RollerDerby/THIS-PAGE-DOES-NOT-EXIST, the page returns a 404 error with an empty body.
It is important for web services to be discoverable. Users may try to navigate to /RollerDerby. The service is currently configured to give a 404 error at that URL. It would help users to expose the PlayerName and Leagues operations of the service from the /RollerDerby URL so the users can find the supported service operations.
To expose the services, open the DerbyService class and add the following method:
[WebGet(UriTemplate=””)]
Public Stream Root()
{
WebOperationContext.Current.OutgoingResponse.ContentType = “text/html”;
String html = “<a href=\”PlayerNames\”>Player Names</a><br /><a” + “href=\”Leagues\”>Leagues</a>”;
Return new MemoryStream(Encoding.UTF8.GetBytes(html));
}
The Stream and MemoryStream classes are in the System.IO namespace, and the Encoding class is in the System.Text namespace. Add these two using statements:
Using System.IO;
Using System.Text;
After building the project, running it, and navigating the browser to /RollerDerby, users are able to discover the operations the RollerDerby service provides.
The final code for the DerbyNamesService should look like this:
Using System.Collections.Generic;
Using System.IO;
Using System.Linq;
Using System.Net;
Using System.ServiceModel;
Using System.ServiceModel.Activation;
Using System.ServiceModel.Web;
Using System.Text;
Namespace DerbyNamesService
{
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Required)]
[ServiceContract]
Public class DerbyService
{
[WebGet(UriTemplate=”/PlayerNames”)]
Public IEnumerable<DerbyNames> PlayerNames()
{
Var names = new DerbyContext().DerbyNames.ToList();
Return names;
}
[WebGet(UriTemplate=”/Leagues”)]
Public IEnumerable<Leagues> Leagues()
{
Var leagues = new DerbyContext().Leagues.ToList();
Return leagues;
}
[WebGet(UriTemplate = “*”)]
Public void ErrorForGet()
{
Throw new WebFaultException(HttpStatusCode.NotFound);
}
[WebGet(UriTemplate = “”)]
Public Stream Root()
{
WebOperationContext.Current.OutgoingResponse.ContentType = “text/html”;
String html = “<a href=\”PlayerNames\”>Player Names</a><br />
<a href=\”Leagues\”>Leagues</a>”;
Return new MemoryStream(Encoding.UTF8.GetBytes(html));
}
}
}
The final web.config should look like this:
<?xml version=”1.0”?>
<configuration>
<system.web>
<compilation debug=”true” targetFramework=”4.0” />
</system.web>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior>
<webHttp defaultOutgoingResponseFormat=”Json”/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled=”true”/>
<serviceDebug includeExceptionDetailInFaults=”false”/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled=”true”
AspNetCompatibilityEnabled=”true” />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests=”true”/>
</system.webServer>
</configuration>
As shown WCF is a flexible framework deliver consumable web services to clients. The drawback of using WCF for web services is the complexity of the technology stack. With all the flexibility WCF provides, using it to deliver text data over HTTP is using a small percentage of the framework.
Using Open Data Protocol (OData)
The Open Data Protocol (OData) may be a web protocol for querying and updating data during a standard way. OData has many querying capabilities like getting the count, expanding related entities, paging, and lots of filter options. Examine the capabilities on http://www.odata.org. Microsoft created the technology and has released it under the Open Specifi cation Promise, which suggests Microsoft has granted everyone license to use the OData technology. OData may be a great choice for web services that make , read, update, and delete data without complex business rules. OData has especially advanced querying capabilities that make it flexible for several projects.
This walkthrough assumes the following software is installed:
- Visual Studio 2010
- IIS 7.5
- Entity Framework 4.0
- SQL Server 2008 R2
1. Open Visual studio and select File ➪ New Project.
2. From New Project menu, select ASP.NET Empty Web Application.
3. Name the service ODataDerbyService and click OK.
To deliver data from the service, this instance uses Entity Framework. Entity Framework is an Object Relational Mapper released by Microsoft. Meaning it'll bind your database to C# objects directly without the user wanting to do any of the work .
Right-click the ODataDerbyService project and choose Add New Item.
From the Templates tree, find Data then select the ADO.NET Entity Data Model template. Enter DerbyData.edmx for the name and click on the Add button.
On the primary screen of the Entity Data Model Wizard, select Generate from Database and click on Next. On subsequent screen of the wizard, click the New Connection button. If you're connecting to SQL Server on an equivalent machine as you're developing thereon ask it by the local instance address. For the server name enter a dot (.). For the database name select DerbyNames from the drop-down list. Then click OK.
After clicking OK on the Connection Properties dialog box, Visual Studio are going to be back within the Entity Data Model Wizard. Click Next to continue.
On the Choose Your Database Objects step of the wizard, check Tables, leave the remainder of the settings at their defaults, and click on Finish.
With the information model created, subsequent step is to feature the OData service. Right-click the ODataDerbyService project and choose Add New Item. From the Add New Item dialog box, within the Installed Templates tree select the web node then select WCF Data Service. Name it DerbyService.svc then click the Add button.
Visual Studio has done most of the work to form OData expose the database as a web service. To form the service access the information model created earlier, open the DerbyService.svc.cs class and find the comment /* TODO: put your data source class name here /* . Replace that comment with DerbyNamesEntities like this:
Public class DerbyService : DataService
Now the service is connected to the information. However, by default OData doesn’t expose any of the information for security reasons. To show the 2 tables from the model, uncomment this line:
Config.SetEntitySetAccessRule(“MyEntityset”, EntitySetRights.AllRead);
And change the string “MyEntityset” to “*” like this:
Config.SetEntitySetAccessRule(“*”, EntitySetRights.AllRead);
That is all the configuration required to confi gure an OData service. Build the project, run the project, and if Visual Studio doesn’t point the browser to the DerbyService.svc URL, navigate to /DerbyService.svc/. Figure shows leads to Google Chrome.
OData is showing DerbyNames and Leagues collections are available.
Figure 1.7(II) Chrome displaying service results
In the browser address bar add /DerbyNames after DerbyService.svc. The service responds with an XML document showing the DerbyNames from the database. Notice the DerbyNames XML document isn’t color coded because the content type request header is application/ atom+xml rather than application/xml. OData uses the Atom and AtomPub format to represent collections.
Also notice the DerbyNames XML document has links like http://localhost:25457/DerbyService.svc/DerbyNames(1) . That link is to the URL showing the DerbyName with a primary key of 1. This starts to point out the facility of OData. OData provides many querying capabilities. The document is telling consumers the way to query the service for a specific instance of a set item.
To expand upon the querying capabilities, enter this URL:
/DerbyService.svc/DerbyNames?$filter=League eq ’Lansing Derby Vixens’
The query string is telling the OData service to return items from the DerbyNames collection where League is up to “Lansing Derby Vixens.” OData responds by returning all the players within the system from the Lansing Derby Vixens league.
OData does have the capability to return JSON. Unfortunately, the WCF Data Services implementation doesn't implement the $format query parameter specified within the OData specification. Instead, the WCF Data Services implementation responds with JSON only the HTTP accept request header is about to “application/json”. Unfortunately, some programming platforms don't support changing request headers. The subsequent procedure shows the way to make the service return JSON without modifying the request headers on the client.
First, the service code must have access to all or any incoming requests before the requests are put into the OData pipeline. To get access to the requests, right-click the ODataDerbyService project and choose Add New Item. Within the Add New Item dialog box Installed Template tree, select Web. From the Templates select Global Application Class. Click the Add button to make the code file within the project.
The Global class features a method named Application_BeginRequest, which is named when an HTTP request enters the application. This is often a good spot to change the HTTP accept request header before WCF Data Services processes the request. To alter the request header, insert the subsequent line within the Application_BeginRequest method:
Protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Request.Headers[“accept”] = “application/json”;
}
Unfortunately, the ASP.NET Development Server doesn't allow modifying the request headers, but IIS 7.5 does. For this method to work within the debug environment requires using IIS Express rather than the ASP.NET Development Server.
To change the environment, right-click the ODataDerbyService project and click on Properties. From the properties window navigation tree select the web tab. Within the Web tab find the Servers section and choose the radio button to be used Local IIS Web Server. Mark the use IIS Express checkbox and accept the Project URL.
Close the property window to save lots of the changes. Build the project, run it, and alter the browser URL to /DerbyService.svc/DerbyNames?$filter=League eq ’Lansing Derby Vixens’ . The document is now returned in JSON rather than XML.
For this question , changing the format to JSON resulted during a 75 percent reduction within the size of the document.
OData also enables inserting and updating data. Open the DerbyService.svc.cs file and alter the config.SetEntitySetAccessRule second parameter from EntitySetRights.AllRead to EntitySetRights.All. This may make all data altogether tables readable and writable. To set rights on a specific table use a line like this: config.SetEntitySetAccessRule(“tableName”, EntitySetRights.All);
Using ASP.NET MVC 3
ASP.NET MVC may be a web framework released by Microsoft. It follows the model-view-controller pattern. This separation provides benefits like easy testability and providing different views of an equivalent model. These features make ASP.NET MVC an excellent choice for creating web services.
This walkthrough assumes the subsequent software is installed:
• ASP.NET 4.0
• ASP.NET MVC 3
• Visual Studio 2010
• IIS 7.5
• Microsoft SQL Server 2008 R2
To get started you would like a project. Open Visual Studio and choose File ➪ New Project. From the New Project dialog box, select the web node from the Installed Templates tree then select ASP.NET MVC3 Web Application. Name the project MVCDerbyService and click on okay to create the project.
On the New ASP.NET MVC 3 Project Template dialog box, select Internet Application, set the view engine to Razor, and check the utilization HTML5 Semantic Markup checkbox. Then click ok to continue.
For simple database access this walkthrough uses LINQ to SQL. Using LINQ to SQL requires a further project regard to System.Data.Linq. To feature the reference, right-click the References node of the DerbyNamesService project and choose Add Reference. Within the Add Reference dialog box click the .NET tab, find System.Data.Linq, and click on the Add button.
After adding the System.Data.Linq reference, you would like to make a category to access the info . To feature the info access class, find the Models folder within the Solution Explorer. Right-click the Models folder and choose Add New Item.
In the Add New Item dialog box, select the web node from the Installed Templates tree. Then select Class from the Templates, name it DerbyContext, and click on the Add button.
Using the Linux Apache MySQL PHP (LAMP) Stack
Web services are cross platform. This section shows the way to configure a web server on Linux to retrieve data from a MySQL database and leverage a technology called OData to deliver querying functionality with little work. OData may be a web platform that permits create, read, update, and delete operations over HTTP.
OData is employed to show information from systems like relational database, file systems, and traditional websites using existing web technologies like HTTP, XML, and JSON. Consider it as exposing parts of your database to the world Wide Web.
This walkthrough assumes the subsequent software is installed:
• Ubuntu 11.10
• Apache2 with URL rewrite mode
• PHP-5.4
• MySQL
• Symfony 2.0
• PHP5s XSL extension
• PHP Extension and Application Repository (PEAR)
To use OData on MySQL, first you would like an information source, meaning someplace where the information is contained. This document contains a script which will create the DerbyNames database, which consists of a leagues table and a derby names table.
To execute the script from a terminal, run the subsequent command to log into the MySQL admin console:
Mysql -u root -p
Enter the basis password when MySQL prompts for a password.
From the MySQL prompt , execute the script by entering the subsequent command:
Source DerbyNames.sql
After creating the database, subsequent task is to download the OData Producer Library for PHP. The OData Producer Library is software which will expose the MySQL database as an OData source. Download it from http://odataphpproducer.codeplex.com/.
Unzip the file contents and copy the OData Producer Library files to /var/www/OData and make sure the /var/www/OData directory has an Index.php file.
Next, PHP must know where the OData library is found . To configure PHP to seem for the OData Producer Library for PHP, create an OData.ini enter /etc/php5/conf.d$. After creating the file, type within the following line of code and save the file:
Include_path = “:/var/www/Odata:/var/www/OData/library”;
For the OData library to handle a request, Apache must hand the request to OData. By default, on the Microsoft Windows .NET stack OData services end in .svc. To keep that convention on this Apache configuration, modify /var/etc/apache2/httpd.conf by adding these lines:
<Directory “/var/www”>
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule (\.svc.*) OData/Index.php
</IfModule>
</Directory>
The OData Connector for MySQL will examine a MySQL database and produce all the PHP code files necessary for read-only OData operations except one the OData connector for MySQL doesn't create the code for IDataServiceStreamProvider. IDataServiceStreamProvider is employed to deliver binary data, for instance a picture or a video, through the OData Producer Library.
The OData Connector for MySQL requires a selected piece of software called Doctrine Object Relational Mapper. This software is an Object Relational Mapper (ORM). For those unfamiliar it, an ORM represents database tables as programing language objects.
Using the PEAR package manager, the Doctrine Object Relational Mapper are often installed using the subsequent commands:
Sudo pear channel-discover pear.doctrine-project.org
Sudo pear install doctrine/DoctrineORM
With the prerequisite ORM installed, it's time to download the OData Connector for the MySQL library. The OData Connector library is made to get PHP code files to perform OData operations against a MySQL source. You’ll download the package from http://odatamysqlphpconnect.codeplex.com. The subsequent steps are for V 1.0.
Navigate to the directory the package downloaded to and unzip it. Open a terminal and navigate to the unzipped package directory.
To generate the code files, execute the subsequent command:
Php MySQLConnector.php /db=DerbyService /srvc=DerbyService /u=webUser /pw=webuser /h=localhost
Running the MySQLConnector.php script states:
EDMX file is successfully generated within the output folder. Does one want to switch the EDMX file-/home/smithd98/Downloads/MySQLConnectorV1.0 /ODataConnectorForMySQL/OutputFiles/Northwind/NorthwindEDMX.xml(y/n):
Press N and therefore the return to indicate no.
The terminal will print the subsequent success messages:
MetadataProvider class has generated Successfully.
QueryProvider class has generated Successfully.
DataServiceProvider class has generated Successfully.
DSExpressionProvider class has generated Successfully.
Service.config file has generated Successfully.
Copy the generated fi les into the /var/www/OData/services/DerbyNames directory with the subsequent two commands:
Sudo mkdir /var/www/OData/services/DerbyNames
Sudo cp ~/Downloads/MySQLConnectorV1.0/ODataConnectorForMySQL /OutputFiles/DerbyNames/* /var/www/OData/services/DerbyNames/
One of the fi les generated by the MySQLConnector script is service.config.xml. This fi le specifies the configuration information to properly activate the service. Unfortunately, the service.config.xml fi le generated doesn’t work correctly on Linux. To figure on Linux it must be modified slightly.
The contents of the /var/www/OData/services/DerbyNames/service.config.xml file generated by the library are:
<?xml version=”1.0”?>
<configuration>
<services>
<Service Name=”DerbyNames.svc”>
<path>Services\DerbyNames\DerbyNamesDataService.php</path>
<classname>DerbyNamesDataService</classname>
<baseURL>/DerbyNames.svc</baseURL>
</Service>
</services>
</configuration>
The contents of the /var/OData/services/DerbyNames/service.config.xml Service element need to be copied into the /var/www/OData/services/service.config.xml services element as a child element.
After copying it in there, you need to make some slight changes:
1. Change the Service node to lowercase.
2. Replace the backslash (\) in the path node with a forward slash (/) so the paths are valid on Linux.
3. Change Services to lowercase in the path node.
After making those changes, the file should look like this:
<?xml version=”1.0”?>
<configuration>
<services>
<service Name=”DerbyNames.svc”>
<path>services/DerbyNames/DerbyNamesDataService.php</path>
<classname>DerbyNamesDataService</classname>
<baseURL>/DerbyNames.svc</baseURL>
</service>
</services>
</configuration>
Use an internet browser to navigate to http://localhost/DerbyNames.svc/DerbyNames. Firefox will display an XML document.
If the browser displays an error like this:
Warning: Cannot modify header information - headers already sent by (output started at /var/www/OData/services/DerbyNames/ DerbyNamesQueryProvider.php:390 in /var/www/OData/Dispatcher.php on line 205
Edit the file /var/www/OData/services/DerbyNames/DerbyNamesQueryProvider.php by removing line 326. Within the version I even have there's a bug putting an empty line at the end of the fi le (after the ?>).
Save the file then reload http://localhost/DerbyNames.svc/DerbyNames within the browser.
With everything working correctly it's time to require advantage of OData features! First, use JSON rather than XML to scale back the dimensions of the information returned by the OData service calls. To change the format to JSON, use the subsequent URL:
Http://localhost/DerbyNames.svc/DerbyNames?$format=json
This time the browser displays the raw JSON.
Another feature of OData is that it enables querying data over HTTP. To question the service for all the players within the Lansing Derby Vixens league, enter the subsequent URL within the Firefox web browser:
Http://localhost/DerbyNames.svc/DerbyNames?$filter=Leagues eq ‘Lansing Derby Vixens’&$format=json
Firefox displays the only two players within the database from the Lansing Derby Vixens League.
OData enables developers to quickly expose read, write, update, and delete operations through web services. The querying capabilities would take many hours of development time to get an equivalent functionality OData provides. These querying capabilities make the service flexible, which speeds up development because the service doesn’t got to be constantly modified to satisfy new requirements.
Despite your best intentions, all developers are not perfect and the web service you create will not work exactly correct the first time you try to test it.
A. Tools
Understanding why an internet service isn't working correctly are often difficult because most of the code running is standard software and not code written by you or your team. Most of the code delivering web services consists of the libraries being leveraged, the platform the code is running on, the web server code running, and therefore the OS code.
Fiddler
When debugging web services, it's important to have the potential to see the raw requests and responses. Fiddler may be a free Windows tool that does just that. Find installation instructions and therefore the download at http://www.fiddler2.com.
Fiddler shows the raw HTTP traffic for the Windows system on which it's running. This suggests the tool will show the raw HTTP service request and HTTP response if the system running Fiddler is that the one making the request. Unfortunately, when developing mobile applications, Fiddler won't be ready to show the HTTP traffic because it's coming from an external device. Fiddler has another feature called Composer that permits the creation and execution of a raw HTTP request.
The Composer feature enables testing and debugging of services. Getting the request and response to behave needless to say is often the primary place I start when debugging a misbehaving web service. I configure the Fiddler request builder to travel against my localhost, which also enables me to set breakpoints in my code. After the request and response are working correctly, I ensure my code is passing data that matches what I’ve produced in Fiddler.
The two most important features of using Fiddler to debug web services successfully are the filters and Composer. When Fiddler is running it captures all the HTTP traffic on the machine on which it's running. This is often typically an excessive amount of data, which obscures the web calls that are important. Fiddler has the concept of filters, which enable a user to cover HTTP traffic that's not of interest.
The other feature is use all the time is Composer. Composer enables producing the precise HTTP request to have executed. This is often useful for understanding why a web service call isn’t working, especially requests that use HTTP accept headers, because those requests can't be executed by a default browser .
Fiddler may be a must-have tool for debugging on the Windows platform.
Wireshark and MAC HTTP Client
When developing services on the Macintosh platform i use the Mac HTTP client to check web service requests. Unfortunately, it doesn't capture traffic like Fiddler. When got to capture traffic on Macintosh or Linux platforms I address Wireshark, a free, open source debugging tool that's far more advanced than Fiddler or the Mac HTTP client.
Wireshark is a complicated packet analysis tool used for HTTP traffic analysis also as the other network traffic, like debugging IP phones. For my simple needs of just debugging HTTP web calls, the extra features and complexity of Wireshark make it harder on behalf of me to use. For those not developing web services on the Windows platform, Wireshark are going to be an important tool.
B. Advanced Web Service Techniques
There are two advanced web service techniques: Web Sockets and Web Service Callbacks. These techniques are not required for consumable web services, but can help services run efficiently.
Web Sockets
The HTTP protocol is meant for servers to reply to client requests. The client asks for a resource and therefore the server delivers that resource. a problem arises if the server wants to deliver a resource to the client. For instance , a stock viewing site like http://www.google.com/finance?q=p would be more valuable if it were ready to update data on the client when the stock data changes. Today the foremost supported way to do that is by having the client continually ask the server “Do you've got any new data for me?” this is often wasteful because oftentimes the solution is not any .
That method is understood as polling. Using Web Sockets a web server is in a position to deliver new data to the client without the client having to invite the new information. As of this writing Web Sockets are an emerging technology that not all browsers support. As support becomes more mainstream, web applications for things like e-mail, weather, traffic information, then on will enjoy the power for servers to notify clients when there's more current information.
Web Service Callbacks
Sometimes a web service must call another one after it's finished. For instance , if a web service is exposed that delivers faxes, the fax will take an extended time to send. When submitting the fax request, the calling service should make the request then disconnect rather than expecting the result. However, the calling service eventually must know the results of the fax. To enable this web service, call-backs are used. Consider the subsequent POST request:
POST http://faxservice.com/fax/000123456 HTTP/1.1
Host: faxservice.com
Content-type: application/json
Content-Length: 107
{
“faxId”: “9839384”,
“OnComplete”: “http://www.gravityworksdesign.com/faxresultreceiver”, “MessageBody”:”sending a fax”
}
The requester submits that HTTP POST request to tell the fax service to form a fax to 000123456. After the fax service executes that request and gets a result, it calls the OnComplete service at http://www.EXAMPLE.com/faxresult receiver passing the result and therefore the fax Id. This permits the first requester to match that faxId and result with the request it initiated.
People are using their mobile browsers more and more a day to find information about businesses, make product decisions and purchases, and even determine the quality of a business supported what they will find online. Recently, you needed to call a business to change a meeting. You looked for the company in my mobile Safari browser, only to find the location wouldn't load because it had been built entirely in Flash.
Creating a mobile website depends on the functionality of your current website, the platform and development standards with which it had been created, and therefore the purpose that users have for visiting the web site.
A. Choosing a Mobile Web Option
If your organization is itching to be mobile, but doesn’t have a focused purpose or resources to develop a mobile app, a mobile website are often an excellent place to start out . You'll approach a mobile website project in several ways, which are discussed thorough afterward . Adaptive mobile websites automatically adjust your current website when viewed on mobile screen sizes, modifying the layout, sizing, and spacing to form it more mobile-friendly.
Dedicated mobile websites require a totally separate mobile website, and mobile web apps employ HTML5 functionality and specific UI elements to make an app-like experience on the online . You would like to research some things about your organization and its current website before choosing a mobilization strategy.
Why Do People Use Your Website on Mobile Devices?
For restaurants and local retail stores, this question are often pretty easy to answer. People are already out and about, and that they got to know your location, your telephone number , or more information about what they're going to find at your store. A mobile website that creates it extremely easy to access information is critical in these situations, and may potentially cost sales if people can’t find what they're trying to find .
Some websites are less likely to be needed by people browsing on their mobile devices, like a commercial construction company: it’s unlikely that a customer will make a choice to work with a construction company supported mobile website experience. But there’s no reason that less critical mobile websites shouldn't provide a smooth mobile experience.
What Can Your Current Website Accommodate?
Different mobile website techniques use existing desktop websites quite others. It’s important to understand how the present website was built and what the platform capabilities are when choosing a mobile development technique. For instance , if the desktop website is made entirely in Flash, you'll need to develop a separate, dedicated website for mobile devices to accommodate non-Flash mobile browsers, like iPhones.
Desktop websites built using clean, modern development standards external style sheets and semantic, div-based HTML can work well because the base for an adaptive website design, because existing elements are easily manipulated through CSS.
If your website is made on a content management system (CMS), you'll check for any mobile options available on the platform. More CMS platforms are that specialize in facilitating great mobile sites. As a start, most include some kind of template system for the location designs. Templates make it easier to use sitewide mobile modifications because changes made to a theme fi le instantly apply to the whole site, which suggests less time updating individual pages. Global style sheets create a default place for mobile CSS changes to be added for the whole site.
Most theme-based CMS systems are beginning to introduce mobile-friendly themes that you simply can use and modify to supply your site with both a desktop and mobile optimized experience. Some CMS systems provide other tools to assist with things like mobile browser testing, mobile detection and redirection, and mobile menu modifications.
The following are some CMS system mobile functionality examples.
WordPress
Some specific WordPress themes automatically apply a special mobile theme to their blog sites when viewed on mobile devices. Many of the available WordPress themes are considered mobileready, and are available with mobile versions. The default WordPress theme automatically applies an alternate mobile theme plus a View Full Site link is included to get back to the complete desktop website.
Drupal
Drupal has many themes and modules that you simply can piece together to make a mobile website version. The WURFL, Mobile Plugin, and Mobile Tools modules can assist with mobile detection, redirection, theme-switching, and image scaling.
DotNetNuke
The latest DotNetNuke versions include built-in tools for mobile detection, redirection, and a mobile template that gives a couple of layout changes for phone and tablet browsers. It also features a nice, built-in emulator for mobile browser testing.
Lots of tools are available that are making dynamic mobile sites easier. Basic HTML and CSS websites also can be modified with mobile CSS. If you've got an older website, or a lot of customdeveloped functions or complicated features, it'd be difficult to adapt your current website, and a dedicated site could also be the thanks to go.
How Much does one Want to supply for Mobile Users?
If you would like mobile users to access basically an equivalent information as they might on a desktop browser, a mobile website is that the direction to travel . That technique allows you to cover some elements and rearrange the bulk of your site for a far better mobile UI. Content is identical and updated through an equivalent editing process.
If you recognize that mobile users won’t got to access an outsized amount of your website content, a fanatical mobile website would be an honest solution. Design a mobile-specific website from the ground up, addressing specific organizational requirements and therefore the needs of on-the-go customers. a dedicated mobile website will enjoy a radical mobile marketing strategy, and may use modified content targeting mobile users in an optimal UI.
A mobile web app would be appropriate with a focused feature for mobile users, provided through a web browser rather than a downloadable app. Offer robust functionality on multiple platforms, and avoid the restrictions of app stores with a mobile web app.
The following table lists the pros and cons of the varied mobile web development options.
B. Adaptive Mobile Websites
An adaptive mobile website may be a great first project for mobile, and it allows steps to be taken incrementally toward an optimal mobile UI. Adaptive mobile websites use CSS media queries to serve different style sheets supported the dimensions or kind of browser or device detected viewing the location .
With CSS, content and presentation layers are kept separate; media queries change website layout and appearance without content modification. No browser detection or site redirection is needed; the optimal website layout appears automatically when media query parameters are met. As already mentioned, the key to a smooth, responsive mobile website project may be a well-coded existing website to control .
Get Your Queries in Place
Media queries are the core of adaptive mobile websites. Here we explains the way to choose what media type or feature to focus on , then explains alternative ways to feature your media query to your site.
Choose Your Target
To apply a media query to a website, first determine in what situations you'll target a browser to use your mobile changes. a method to focus on browsers is by media type. Media types are within the W3C’s specifications for several years, and more types still be added. The subsequent may be a list of all the media types now available. Some you likely recognize, but others are more obscure.
- All: Covers all device types.
- Braille: Used for braille tactile feedback devices.
- Embossed: Intended for paged braille printers.
- Handheld: Targets devices which are considered mobile, with smaller screens and limited bandwidth.
- Print: Used for paged material and documents viewed on-screen in print preview mode, or output to an actual printer.
- Projection: Intended for large-scale, projected presentations.
- Screen: Targets common-sized desktop computers with color screens.
- Speech: Intended for speech synthesizers.
- Tty: Intended for media using a fixed-pitch character grid like teletypes, terminals, or portable devices with limited display capabilities.
- Tv: Targets television-type devices with low resolution, color, limited-scrollability screens, sound available.
The other way to target a browser for mobile styling is by media feature. Consider following media features are:
- Aspect-ratio: It is based on the ratio of the value of the width media feature to the value of the height media feature. Accepts min/max prefixes.
- Color: It is based on the number of bits per color component of the output device. Accepts min/max prefixes.
- Color-index: Targets based on the number of entries in the color lookup table of the output device. Accepts min/max prefixes.
- Device-aspect-ratio: Targets based on the ratio of the value of the device-width media feature to the value of the device-height media feature. Accepts min/max prefixes.
- Device-height: Targets based on the height of the rendering surface of the output device. Accepts min/max prefixes.
- Device-width: Targets based on the width of the rendering surface of the output device. Accepts min/max prefixes.
- Grid: Targets with a query for whether the output device is grid or bitmap.
- Height: Targets based on the height of the display area of the output device. Accepts min/ max prefixes.
- Monochrome: Targets based on the number of bits per pixel in a monochrome frame buffer.
- Width: Targets based on the width of the display area of the output device. Accepts min/ max prefixes.
- Orientation: Targets by portrait or landscape orientation.
- Resolution: Targets based on the resolution of the output device, that is, the density of the pixels (dots per inch, or dpi). Accepts min/max prefixes.
- Scan: Targets the scanning process of “tv” output devices.
Media features quite double the number of the way to focus on browsers, and provides more fine control with the power to combine targeted features and properties. And, not, and only are often included for combinations of requests.
So how does one decide the simplest way to target for mobile? Recommend targeting all media types, and using the width media feature to use your styles once a browser is smaller than a set width. For example:
@media all and (max-width: 480px) {… }
This means whenever a browser is a smaller amount than 480 pixels wide, any CSS properties defined inside this media query will then apply.
You can also target small desktop monitors or tablets with a combination of widths:
@media all and (min-width:480px) and (max-width: 800px) {… }
Or widescreen monitors:
@media all and (min-width:1400px) {… }
This targeting method gives finer control over when styles will apply, as against the hand-held media type, and this system also makes testing easier by enabling you to check during a desktop browser. Also, some newer mobile devices have excluded themselves from the hand-held distinction so as to serve full-feature websites, because modern mobile devices have this capacity.
Link to Your Media Queries
Once you determine how to target mobile website then many ways to add your media query to the site. We recommend including your mobile CSS directly inside your global style sheet:
@media handheld
{ /* Mobile styles go here*/ }
You can also link to a separate mobile style sheet in your HTML file:
<link rel=”stylesheet” href=”mobile.css”, type=”text/css” media=”handheld” />
Or, import your mobile CSS from a global CSS fi le:
@import url(“mobile.css”) handheld;
The first option is easiest to start out with because the styles will apply instantly if the other styles therein style sheet are working correctly. There’s no got to add any files; simply add your mobile styles into an existing CSS file. This system is additionally best for performance, because just one style sheet are going to be loaded. Additionally, the @import technique isn’t well supported in older versions of Internet Explorer, so that’s one more reason it should be avoided.
Remember the Viewport
Another important detail is required to make sure mobile browsers render a site correctly. A viewport meta data tag ensures that mobile browsers on different devices zoom properly to the proper size of your site. Otherwise, if you've got a 300px-wide mobile site, the browser might still render it on a 1000px-wide canvas if a viewport isn't defined. To feature the viewport, simply add this property to the <head> tag of all pages:
<meta name=”viewport” content=”width=device-width, initial-scale=1.0,
Maximum-scale=2.0”/>
Inside the content property, several things are happening, and a number of other options are defined. The width property is about to render the site at the width of the device, with the web site scaled to its normal size on load. The maximum scale is about so touchscreen mobile users can zoom the site to 2 times its normal size.
(a) (b)
Figure 1.8 (I)(a)Mobile web page example with viewport properly set (b)Mobile web page example with viewport not set
The Inevitable Internet Explorer Fix
Media queries are a part of the CSS3 W3C specification, and are well supported across platforms. At the time of writing, that they had support a minimum of three versions back in Firefox (since 3.6), Chrome (since 17), Safari (since 5), Safari iOS (since 3.2), Opera (since 11.6), Opera Mobile (since 10), and therefore the Android browser (since 2.1). Unsurprisingly, the gap is seen in Internet Explorer, which has supported the feature only since Internet Explorer 9.
Though global usage of Internet Explorer 8 or below is a minimum of 30 percent , if you're using media queries just for mobile sites, the most worry is Windows Phone 7, which comes with an online Explorer 7 equivalent browser. Version 7.5 comes with Internet Explorer 9, so going forward it’s within the clear. With a mobile market share of around 2 percent, Windows Phone isn't a drastic concern, but there's a JavaScript workaround to get media queries rendering in older mobile Internet Explorer browsers:
<!--[if lt IE 9]> <script src=”http://css3-mediaqueries-js.googlecode.com/
Svn/trunk/css3-mediaqueries.js”></script> <![endif]-->
The script parses your CSS and applies the media query styles, and can be tested in real time on Internet Explorer, including when you resize the window.
C. Add Mobile Styles
Once the media query is in place, it’s time to make a decision the way to change the web site for mobile browsers. It's a good idea to make mock-ups of how you'd like your website to seem on mobile, but it’s important to understand the restrictions of this system , and it's going to be helpful to check out some changes within the code first.
Adding Your Changes to @Media
The basic process for changing your website for mobile browsers is to put CSS styles for the mobile site inside your @media tag. These styles will apply to your site when the defined media type or feature properties are met. You'll reduce the number of columns, modify the width of content areas, increase the size of buttons and links, and hide items not needed for mobile.
In the following example, you'll see that the regular site header features a width of 960px. But when the site is viewed on alittle , mobile screen, the media query applies a new width of 320px, which can override the first width. For the logo, an alternate mobile logo image is loaded as a CSS background image, and therefore the size of the div is additionally reduced.
Here’s an example of some regular website CSS, defining a header that's 960px wide and 105px tall, with a background image. The site logo is 312px by 102px, and also loaded as a background image in CSS:
#header {
Float:left;
Width:960px;
Height:105px;
Background:url(images/header-bg.jpg) no-repeat;
}
h1#logo, a#logo {
Width:312px;
Height:102px;
Background:url(images/logo.png) no-repeat;
Float:left;
Padding:0;
}
Here’s an example of the mobile website CSS, applied to an equivalent elements when a browser width is under 480px wide. Now the header is about to 320px wide and 65px tall. An equivalent float and background properties will still apply on the mobile version, but the height and width set within the media query section will override the regular CSS.
@media all and (max-width: 480px) {
#header {
Width:320px;
Height:65px;
}
h1#logo, a#logo {
Width:160px;
Height:100px;
Background:url(images/mobile-logo.png) no-repeat!important;
Margin:8px 0 0 0;
}
}
This is the method followed throughout the adaptive mobile site code: simply change the CSS for every element to suit into the mobile screen size and modify the location styles. You'll add @media styles for one set of properties or multiple properties to optimally change the site appearance for several devices:
@media all and (max-width: 480px) {
/*phone styles go here*/
}
@media all and (min-width:480px) and (max-width: 800px) {
/* tablet styles go here */
}
Change Your Width
The first thing you’ll want to try and do is set a smaller width for the whole website. If you're wont to designing fixed-width websites, you'll also design mobile fixed-width sites. Set the width of any containing divs on your site to smaller width, like 320px. With the proper viewport, a mobile site with a fixed width automatically scales to suit wider or narrower screens with everything scaled proportionally. If you switch your phone to landscape mode, everything gets slightly bigger to fi t the width.
Alternatively, you'll set div widths to 100% for the mobile website. This suggests that rather than the whole site scaling up or down for various screen sizes, the content areas simply become wider or narrower. Font sizes remain an equivalent , and content areas have different lengths supported what proportion content fits on each line.
Choosing a fixed or fluid mobile website width depends on your preference for user experience on different devices and screen sizes, also as your preference for development techniques. Fluid mobile layouts are more flexible and supply a far better use of space on varying screen sizes, but you've got more variables and factors to check through development than with one , fixed mobile site version.
With either width setting, confirm that each one divs are set to widths but your determined fixed width, or are ready to a percent for fluid widths. Confirm no desktop site div widths, like 500px or 800px, persist on the mobile website, because they're going to break outside of the set mobile site width and make horizontal scrolling.
Flow Your Columns
Once you've got set the width for the whole site, you’ll want confirm all of the contained divs flow into one continuous column because the available width is so small on a mobile . If your divs are already flated, this part should be easy. If two divs were floated next to every other within the desktop website, the second div will automatically position itself after the primary div once the containing div not has enough room to fi t both side by side. This is often why table-based websites don’t work well with this technique: all columns will still be positioned next to every other regardless of how small the containing div is.
The order of mobile website content is controlled by the HTML content order. This will be seen together of the restrictions of a dynamic mobile website. If a desktop website contains two columns, all content within the left column must appear before any content within the right column on the mobile website. There's no way to switch the order of HTML content using CSS.
Knowing this, one thing to take into consideration is that the placement of any side menus. If you've got a menu placed during a left-hand column for all inside pages, this menu would seem before any of the page content from the proper column. If you're willing to measure with this type of restriction, flowing all of your content into one, usable website column may be a pretty easy process.
The left menu appears before the most content. The small advertisement has been hidden below the menu, otherwise that also would have appeared before the main content.
Hide Content
Another thing to do while planning your mobile website is determining content areas that aren't needed on the mobile site. For items that you simply want to hide for mobile, it’s as easy as adding display:none to the CSS for a category or ID that surrounds only that content.
Some things that are best to hide on mobile include image rotators, any Flash, and any images that are simply supplemental to the planning and don’t add to the understanding of the page content.
You can also prefer to hide entire sections of content that aren’t important for mobile website users. For instance , you'll hide supplemental content during a side column or footer blocks, or hide testimonials, social media links, or a persistent contact form for pages on which users wouldn’t need them. Especially if content is repeated on every page, believe whether it’s actually important, or simply supplemental column filler. You'll even plan to hide a side menu if the most navigation is sufficient for getting round the site.
Simplify Your Header
Wise use of website real estate that's “above the fold” is even more important on a mobile website than a desktop version. Mobile browser bars may allow users to ascertain only an area as little as 200px in height before having to scroll. One among the foremost important things to do is design and simplify your website header to only get the most pertinent information across. Use a smaller logo. Remove contact information unless it’s critical for your mobile users. Hide slogans, links that are useful only on a desktop, and even search bars.
Make sure that the header tells users what site they're on, then confirm they will quickly get to the data they actually need.
Modify Menus
Determining the way to position the mobile website’s main menu is one among the trickiest and most important elements to address. If a horizontal main menu contains only a couple of things , it's going to be possible to go away the links listed horizontally in one or two rows. Confirm the links are large enough, with enough spacing, that they will be easily hit on a touchscreen: no quite four or five items during a row, and no quite two rows.
Or a menu created as an unordered list might be restyled in order that each item goes on its own line, becoming a vertical menu.
This would do the trick:
Ul li
{
Display:block; width:100%;
}
A third option is to use completely different HTML code for a menu on desktop and mobile. You'll change a menu rendered inside an unordered list on desktop to a drop-down list on mobile. A drop-down list needs only a touch little bit of
Space, and mobile devices have developed very user-friendly ways of handling them. It’s possible to display different menu code on mobile. In your desktop CSS code, set your for your <select> elements. Inside the mobile media query
Styles, do the opposite: set <ul> to display:none and include any desired styling and display:inline for your <select> element.
/* Desktop Menu CSS */
Nav select {display: none; }
Nav ul li {float: left; list-style: none; }
Nav ul a {color: #fff; display: block; }
/* Mobile Menu CSS */
@media all and (max-width: 480px) {
Nav select {display: inline; }
Nav ul {display: none; }
}
Of course, adding duplicate code for mobile can increase the size of your site and requires maintaining two menus, so it is not ideal. Using JavaScript, you can automatically convert the type of list displayed between a <ul> and <select> element. The following example uses the jQuery framework, which allows you to select and append HTML elements without a great deal of logic.
Start with the menu code set as an unordered list:
<nav>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</nav>
Add this JavaScript to the <head> of your HTML fi le to specify the two separate menu types, and when to use them:
<script type=”text/javascript”>
// Create the dropdown base
$(“nav a”).addClass(“mm-add”);
$(“<select />”).appendTo(“nav”);
// Create default option “Go to...”
$(“<option />”, {
“selected”: “selected”,
“value”
: “”,
“text”
: “Go to...”
}).appendTo(“nav select”);
// Populate dropdown with menu items
$(“nav a.mm-add”).each(function() {
Var el = $(this);
$(“<option />”, {
“value”
: el.attr(“href”),
“text”
: el.text()
}).appendTo(“nav select”);
});
// Make sure it all works
$(“nav select”).change(function() {
Window.location = $(this).find(“option:selected”).val();
});
</script>
This technique is a great option for creating a space-saving mobile menu. Thanks to Chris Coyier of CSS-tricks.com for creating this technique.
Review Your Content
Once the essential template of your mobile site is set up header, footer, site width, and columns review the content and confirm everything is where it should be. Text-heavy pages shouldn't have many issues. Custom website features, like an events calendar or a contact form, may have a bit of caressing.
Scale Media
A common element which will break out of mobile site constraints is images. If you've got a containing div set to 300px, and a picture that's , or has dimensions set to, 400px wide, the image will extend outside of the div to take care of its full size. Luckily, there's a quick fix to use to all or any of the pictures on your site:
Img { max-width: 100%; }
This little little bit of CSS ensures that no images break outside of any surrounding div, and every one modern browsers will scale down content proportionally that have a max-width set. The max-width: 100% CSS property also can be applied to other media like video, object, and embed to constrain the size at which they're displayed.
Once again, scaling a picture using CSS doesn't change the dimensions of the media that has got to be loaded by the browser. A 600x400, 200k image shown at 300x200 on mobile remains a 200k element loading on the web site . Some tools have emerged lately which will help improve bandwidth by changing the particular size of media files on mobile devices.
Adaptive Images
Adaptive Images from Matt Wilcox is a superb , drop-in JavaScript and PHP script solution that automatically resizes actual image fi le sizes to the specific dimensions at which they're viewed. This creates the perfect scenario: lightweight, easy to implement, and does all the work for you on the fly. Combining adaptive images with max-width: 100%; should cover all the bases display and load images at the optimal size. Just follow these steps and you’re done:
1. Download the newest version of Adaptive Images from http://adaptive-images.com/ download.htm.
2. Add the included .htaccess and adaptive-images.php fi les to the server document-root folder.
3. Add one line of JavaScript into the <head> of your site: <script>document.cookie=’resolution=’+Math.max(screen.width,screen.height)+’; path=/’;</script>.
4. Add your CSS Media Query values into $resolutions within the PHP file.
5. Add images as you normally would, at their desktop website size.
This solution works only on websites using Apache 2 and PHP 5.x, but others have adapted the technique in other languages, including .NET and ColdFusion. View the download page for an up-to-date listing of Adaptive Images ports and plugins.
This technique was built off an earlier option created by the Filament Group called Responsive Images. This system requires you to make and upload images at multiple sizes to your website, add a query to all or any images’ src elements, then add JavaScript to check screen width and load the right image. This system also requires Apache and PHP. Obviously, creating and uploading duplicate images and changing all image fi les’ URLs is cumbersome and time-consuming.
One of the most reasons to use the adaptive mobile website technique is that it's easy to use to a whole site with just CSS changes. I personally wouldn't want to require the time necessary to use this system to an existing website with many images, but it’s important to understand your options and understand how techniques are progressing.
Testing Made Easy
Testing adaptive mobile websites is extremely easy, especially if you're targeting your media queries for all devices with max-width criteria as discussed earlier:
@media all and (max-width: 480px)
This means you'll simply resize your browser to but 480px wide, and you’ll instantly see your website with the mobile CSS styles applied on your desktop screen. It’s convenient to do a majority of testing right your desktop as you code. Some mobile emulators are available to boost testing from your desktop. Screenfly uses a proxy server to mimic devices as you view a web site.
Enter a web site address and preview the web site on variety of various device screen sizes and resolutions. Screenfly’s proxy server mimics the user agent string of a specific device, but doesn't emulate device behaviour like zoom. There's also a Firefox plug-in called User Agent Switcher that does just what it says: it allows Firefox to emulate the user agents of other browsers, like iPhone or Internet Explorer.
Testing on a desktop browser or emulator is convenient, but there's no comparison to native mobile browsers for understanding all the kinks and little details. For instance , desktop browsers won't accurately portray the left and right margin space that appears during a mobile browser.
Using a regular desktop browser might always show some space on all sides , but once you check on your phone, text might run right up to every edge if specific margins or padding weren't added within the CSS. Don’t wait until the eleventh hour to check your website on a spread of smartphones. And if you don’t have a slew of mobile devices for your own testing purposes, make certain to seek out a couple of friends who are willing to poke round the website for you.
Break Out of Mobile (or Not?)
Depending on how far you accompany your adaptive mobile website, you'll or might not prefer to include a link back to your “regular” website. If you retain the bulk of website content and just modify the display for mobile users, a link to the standard desktop website shouldn’t be necessary. Believe all the changes you've got made for the mobile website, and confirm there's nothing that somebody might search out and be unable to find on the mobile website.
If your mobile website version is well tested, easy to navigate, and still contains most of your desktop website content, people should haven't any reason to modify back to a desktop version. If you’ve chosen to hide a lot of content or entire pages in your adaptive mobile site, linking to the desktop website could also be useful. To do this, you would like to use a separate style sheet for your mobile device styles, and a bit of Javascript to “break out” of the mobile styles and consider the regular webpage. The subsequent example uses a JavaScript fi le named breakout.js that performs this functionality.
<script type=”text/javascript”
Src=”http://www.website.com/js/breakout.js”></script>
<span id=”FullSite”>View Full Website</span>
<span id=”MobileSite”>View Mobile Website</span>
Include spans with ids which will be called within the JavaScript, one to look at the complete website, and one to look at the mobile website. Inside your media query CSS, use display:none on the span ids to set them to be visible only viewing the mobile or full site versions, to link to the other .
The following JavaScript code assumes that the jQuery framework has already been loaded. After the HTML page has been loaded, the jQuery document ready function is named , and our logic checks to check if the user has “broken” out of mobile. This is often performed within the shouldWeBreakOutOfMobile function, which simply checks to see if a particular cookie exists:
$(document).ready(function () {
If (shouldWeBreakOutOfMobile() == true) {
BreakOutOfMobile(document.URL, false);
}
Else {
$(‘head’).append(‘<meta name=”viewport” content=”width=device-width, initial-
Scale=1.0, maximum-scale=2.0” />’);
ApplyMobileStyle();
}
Taking It Further: Complete Responsive Websites
Now that you’ve seen the way to use media queries to develop an adaptive mobile-specific website, you'll expand upon a number of these techniques to make a totally responsive website. Rather than modifying the fixed-width desktop website to make a fixed-width mobile website, a totally responsive website utilizes percentage-based widths and margins for a flexible grid layout.
This is very almost like the “liquid layouts” from years past, long despised by designers for his or her unpredictable appearances and lack of layout control. But combined with media queries and other new discoveries, designers are embracing responsive websites because the way forward for web design meeting the requirements of all different screen and device types while giving designers the fine control over details they need .
Some web designers have even started advocating designing for mobile first. Start with the small screen, strip your site right down to the essentials, and build from there. This concept might sound a bit scary, but judging by the proliferation of smartphones and tablets, it’s really not very extreme.
Because creating a totally responsive website would generally require a full site redevelopment, and introduces a lot of detailed coding techniques.
D. Dedicated Mobile Websites
With a fanatical mobile website, most of the concepts discussed for a dynamic mobile site still hold true. You would like to make a decision how you would like to vary , rearrange, or remove content from your website for the mobile version.
The difference is that you simply are going to be building the dedicated mobile website from the ground up, so you've got only a few restrictions and it's easier to concentrate to the details that make the optimal mobile browsing experience. This is often also a good opportunity to undertake a totally responsive site design, to hide the range of phone and tablet device differences.
When planning a fresh mobile website, designing ahead may be a must. A designer doesn't got to believe restrictions just like the flow of columns: there's far more freedom to design a mobile site as perfectly as possible. Start with a modifying your sitemap to incorporate only the pages that people will need when browsing your mobile site. You'll select only alittle number of key pages on the mobile site. This might allow the menu to suit horizontally across the mobile site, when the desktop version may have had too many links to do so.
Because a dedicated website won't mirror desktop content, it's also an honest idea to cater site content to mobile users. Rewrite mobile content to be shorter, and appeal to any mobile-specific user needs.
Some guidelines to follow when planning and building your dedicated mobile website are outlined within the following sections.
Keep Files Sizes Small
Avoid using 32-bit PNG images, as these have the most important fi le size of image types used on the web. Use JPG and GIF fi les, and if you would like transparency use 8-bit PNG files. 8-bit fi les support alpha transparency and render fine in modern mobile browsers.
Increase the Size of Elements in the User Interface
Optimize size and spacing of buttons and links; a good rule of thumb is, quite fittingly, to form sure users can hit buttons easily with their thumbs when testing the site. Confirm buttons and links have large hotspots that are the particular link area, and increase font sizes and line spacing for the mobile version.
Leverage CSS3
Many new CSS3 properties that reduce the necessity for design element images are well-supported by modern mobile browsers and may speed up development. Make certain to use them to the fullest extent when designing your mobile website. Here are a couple of examples:
• Gradients: background: linear-gradient(top, #000000 0%,#ffffff 100%);
• Border Radius (rounded corners): border-radius: 15px;
• Box Shadow: box-shadow: 10px 10px 5px #888;
• Text Shadow: text-shadow: 2px 2px 2px #000;
Retina Images
With iPhone 4’s retina display added to the combination, the simplest way to create images for mobile websites has now changed. Gone are the times of the 72dpi standard web image. Because the retina display doubles the potential resolution users can see, simply double the size of your source fi les to serve retina resolution images. To display an icon at 32x32 pixels, create the fi le at 64x64 pixels, and set the image size properties to 32x32:
<img src=”/my-icon.png” width=”32px” height=”32px” />
It is important to note that this will serve double the amount of data than what can be used on non-retina displays. You can also use media queries to target iPhone 4’s retina display and serve only the double resolution images to applicable devices:
<link rel=”stylesheet” type=”text/css” href=”/retina.css” media=”all and
(-webkit-min-device-pixel-ratio: 2)” />
Then, in the retina-specific CSS, you can load a background image that is 64x64 pixels, and specify its dimensions as 32x32 using the background-size CSS property.
Detection and Redirection
To redirect users to the mobile website, you can use a basic JavaScript option based on screen size,similar to using media queries:
<script type=”text/javascript”>
<!--
If (screen.width <= 500) {
Document.location = “mobile.html”;
)
//-->
</script>
This redirects users to your mobile website homepage when their screen widths are below the set dimensions. During this example, mobile.html is that the mobile homepage file, which can be displayed when the web site is viewed from any screen but 500px wide whether tablet or phone.
Users also can be redirected through JavaScript that detects the user agent. Several scripts are available to use, depending on the language with which your website is made. Http://detectmobilebrowsers.com features a collection of downloadable scripts for fifteen different languages.
Link Back to the Desktop Site
Generally, content is greatly reduced on an obsessive mobile website compared to the desktop website, so it's important to supply a link back to the regular website version. Because a dedicated mobile website features a unique URL, it’s easy to feature links between the 2 versions. Use a media query and display:none to make sure the link to the desktop version appears only someone is viewing the site from a mobile device.
Testing
Most of an equivalent testing methods apply for a dedicated mobile website as they are doing for a responsive one. You'll review the initial work on a scaled-down desktop browser, and use emulators like Screenfly. Native mobile devices should definitely be used for testing the web site interface and usefulness . it's also important to check the detection and redirection to the mobile website using several major mobile device platforms.
Adobe Shadow may be a great tool to help with on-device website testing. With it you'll pair native iOS and Android devices together with your computer wirelessly. Then once you refresh your site on your desktop while using the Shadow extension for Google Chrome, the native mobile browsers will automatically sync and refresh also . You'll also remotely inspect your site as rendered on the mobile browsers through your desktop browser.
E. Mobile Web Apps with Html5
Mobile web apps can provide useful alternatives to native mobile apps. With a plethora of latest tools harnessing the HTML5 and JavaScript capabilities of recent mobile browsers, dynamic web applications can get up to any native app. It can take much less time for an experienced web developer to make a mobile web app that works across platforms than to develop an equivalent app natively for an equivalent kind of device platforms.
What Exactly Is HTML5?
HTML5 is basically just HTML, and therefore the evolving of the language for easier creation of web applications. Although some features and specifications are new, it's not meant to make a worldwide shift to a “new” language. The goal of HTML5 is to make standards that are compatible across browsers and supply ways to develop web features using open source methods that previously required proprietary technologies. It aims to take care of backward compatibility, and not break current HTML sites .
Whereas previous iterations of HTML and XHTML kept adding more strict syntax and fewer room for error, HTML5 scales back requirements, creating a more open environment for creating sites . Starting with the doctype, HTML5 is overtly simple:
<!DOCTYPE html>
That’s it. All you've got to do to technically be using HTML5 is use this doctype , and it isn’t likely to vary anytime soon. Though HTML5 seems like a version number, the compatibility factors guiding HTML5 mean that things just like the doctype should become standard, and one less thing web developers need to worry about when ensuring their websites and applications work for everybody .
HTML5 introduces many features that you simply can utilize in your mobile web apps to make a more native mobile web experience. At its core, HTML5 introduces new structural elements with more semantic meaning than <div> s:
- <header> : For a group of introductory aides. This is defined by content, not position, so you can have a <header> for your entire site and also a header within a blog post.
- <nav> : For major site navigation. Again, could be used multiple times on a page.
- <hgroup> : To aid with document outlining, can be used to wrap multiple, subsequent headers.
- <section> : Used to group semantically related content.
- <article> : For self-contained related content. (A rule of thumb: Think “Could this be an RSS item?”)
- <footer> : Information about the footer ’s containing element (copyright, author). Like <header> , <footer> can be used for an entire site, or multiple elements within it.
- <aside> : A sidebar related to adjacent content.
These new structural elements create the base of any modern, semantically rich website or web application.
And What Exactly Is a Mobile Web App?
Whereas a mobile website exists to enhance the mobile functionality of an existing website, a mobile web app exists to perform a selected mobile function. A mobile web app should be more like a native app than to an internet site . a web app cannot handle some functions, or won't have the potential to access the device to perform them. a number of the situations that might require a native application development include:
• Resource and graphic-intensive games
• Accessing the device camera, microphone, address book, or media library
• Apps to be sold through app markets for payment
• Sending push notifications
• Running as a background service
If the app doesn’t got to do any of those things, creating the app on the web may be a great option. Once you plan to create a mobile web app, at its core you’ll still be developing a mobile website. You'll use many of the already-discussed techniques like adaptive images and media queries.
Like a dedicated mobile website, a mobile web app will most likely be designed just for mobile phones and possibly tablets. You’ll still be creating all of your HTML pages and may use media queries to focus on different orientations and screen sizes. Then, using HTML5 and JavaScript, you'll add advanced functionality that more closely relates to a native app.
How Do You Use HTML5 in a Mobile Web App?
If you’re not looking for any of the mentioned capabilities in your mobile app, then HTML, CSS, and JavaScript might provide all the necessary tools to create a well-designed, full-fledged mobile web app.
New Form Input Types
These HTML5 specifications are easy to understand, quick to implement, and a no-brainer to use right away. Instead of the basic <input type=”text”> , new input types provide a streamlined experience in modern mobile browsers, and can also aid in form validation:
- <input type=”email”> : This markup define that they should accept the field entry only if a valid e-mail address format is followed. On iPhone, the device keyboard that is with this field includes the at (@) and dot (.) symbols on the main screen, making it easier to quickly enter the correct data. The keyboard on Android will not be modified.
- <input type=”url”> : This tells browsers to check for a valid web address format. A special keyboard with a “.com” button appears on iPhone; Android’s keyboard are the same.
- <input type=”tel”> : Although varying telephone number formats mean there’s no validation added, this brings up a number keyboard screen on some mobile devices, including iPhone and Android.
- <input type=”number”> : It allows only numbers to be input, and shows numeric keyboards and number spinner controls on some devices and browsers.
- <input type=”date”> : The goal here is for browsers to provide native date pickers to replace JavaScript widgets, and standardize valid input formats.
- <input type=”time”> : Validates a 24-hour time input format.
- <input type=”datetime”> : Validates a precise date and time.
- <input type=”range”> : Renders a slider in some browsers.
- <input type=”search”> : Expects a search to be performed, and renders with a specific style in some browsers, like Safari.
- <input type=”color”> : Can provide a native browser color picker, although not well-supported by browsers yet.
Backward compatibility is in full effect with these elements, therefore you don’t have to worry about forms breaking in older browsers. If a browser doesn’t recognize an input type, it just falls back to a regular text input field. There’s no reason not to use these input types in a mobile web app to provide a better user experience.
New form attributes are introduced to help replace common JavaScript widgets:
- Required: Can be placed on and most input fields in that browsers won’t allow the form to be submitted if the field is empty.
- Placeholder: Puts default text in the input box that automatically clears once the user’s focus is on that field.
- Min and max: Constrains the range of values that can be entered in a field like a number or date range.
- Multiple: When used on an input type like e-mail it allows multiple addresses to be inserted in a comma-separated format.
- Step: When used on a spinner it control the increment of options that are shown.
Offline Storage
HTML5 offline storage provides how to save lots of data on the client side even when there's no Internet connection. Once data has been downloaded to the device, a manifest fi le are often wont to cache files locally, like options and actions the user made. When the net connection is restored the information can synchronize back to the server.
Data can't be downloaded from the server if the net connection is lost, but many aspects of a mobile web app experience can continue unchanged with offline storage. This is often a crucial element for behaving more sort of a native mobile app, because many apps don’t require a web connection to completely function.
The Cache Manifest
A manifest tells the browser what it must store on its local cache. Once the browser has stored the fi les in its cache, the web app can still use the files when the user is offline. The manifest also can specify files that should not be cached, and supply fallbacks when assets are missing.
To get started, simply add the manifest attribute to the element, and point it to the file containing your application manifest:
<html lang=”en” manifest=“/webapp.manifest”>
Your manifest file must begin with a declaration of CACHE MANIFEST, which tells your browser that what follows is the source to a manifest file. Next, the files are listed within categories, also known as namespaces.
CACHE MANIFEST
CACHE:
Index.html
Myscripts.js
Mystyles.css
FALLBACK:
/ offline.html
NETWORK:
Liveinfo.html
# version 1
CACHE , quite obviously, tells the browser all of the fi les that should be cached.
FALLBACK tells the browser the way to handle files that aren't cached. If anything matches the URL on the left, and isn't within the manifest, and can’t be accessed because of lack of connection, it'll get replaced with the fi le on the proper . During this case, if any URL is specified besides index.html , then show offline.html . This will be wont to prevent users from accessing specific parts of the mobile web app that do require an internet connection, serving users a special page instead.
NETWORK explicitly tells the browser any files that has got to have an internet connection to be accessed. By default, anything ex-directory within the CACHE will fall during this category, and it are often specifically stated employing a wildcard asterisk ( * ).
Last, a comment is included that tells the browser to reload the contents of the manifest. To do this, something must change within the contents of the fi le to force a reload.
To serve the manifest correctly, the fi le must have the extension .manifest , and it must have the proper MIME type. You’ll got to change HTTP headers and include something like this in your mime.types file:
Text/cache-manifest manifest
Once the manifest fi le is in situ , when a browser accesses the site it parses the HTML fi le, processes the manifest file, requests the assets within the manifest file, and caches the required files. Then, if the browser reloads when the web connection is lost, and nothing within the manifest file has changed, the browser will detect that it's local cache and serve the page from the files saved locally.
Geolocation
Plenty of mobile web user scenarios can benefit from geolocation. For instance , many online retail store locators now have a “use my current location” option. This may conveniently mention the closest stores to a user’s current location in one click, rather than having to enter a city or zip code.
The JavaScript Geolocation API uses GPS or network IP information to fi nd the physical location of users. It exists inside the navigator object, is simple to work with, and allows you to boost a mobile web app in very native ways. To start, you'll quickly fi nd the present location of your user with the getCurrentPosition JavaScript method. Or, watchPosition checks at regular intervals to check if the user’s position has changed.
It’s important to notice when using geolocation during a web app that browsers prompt users to form sure they accept the app’s use of their position information. If users refuse, an error handler is returned, so confirm that your app addresses that scenario appropriately.
The success handler that's returned if the user accepts the app’s use of getCurrentPosition or watchPosition includes a position object containing two properties: timestamp and coords . Using the coordinate data, you'll easily map user position on a graphical interface, like Google Maps. The subsequent JavaScript added to your HTML fi le will get the coordinates for the user’s
Current location for displaying on a map:
<script>
Function getLocation() {
If (navigator.geolocation) {
Navigator.geolocation.getCurrentPosition(functon(position) {
Var coords = position.coords;
ShowMap(coords.latitude, coords.longitude, coords.accuracy);
});
}
}
</script>
Canvas
The Canvas API provides 2-D drawing capabilities for a large range of mobile web applications: drawing tools, games, emulators, and more. It uses HTML and JavaScript to bring dynamic, native drawing and animation, with none need for Flash. The HTML5 Canvas Cookbook by Eric Rowell is a wonderful resource, from getting started with paths and drawings to advanced animation and game development.
Make Your Mobile Web App Even More Native
Because your mobile web app remains running during a browser, you’ll have things just like the browser navigation bar taking over screen real estate, and forcing certain options to be available to users, where a native app may need a specialized navigation bar instead.
Add to Home Screen
On iPhone and iPad, the mobile WebKit browser includes a simple way to bookmark a web site, adding it as an icon on the device home screen. This is often another detail which will make a mobile web app seem more sort of a native app, with a one-touch access icon, a bit like the other app on the house screen. Any website are often added to the iOS device home screen; the matter is that the bulk of users don’t skills to feature these shortcuts to their devices.
Matteo Spinelli created a JavaScript project that prompts users to feature a site to their home screen, with a bubble intuitively positioned next to the native browser button where users must perform this function. It mimics YouTube’s initial use of such a feature, with options including the message text to display, bubble appearance frequency, and bubble animation effects. It also includes a method sheet so designers can easily customize button appearance.
The following two lines simply got to be added to the <head> of the mobile web app’s HTML. The script checks the user’s device, OS and version, and displays the bubble only in appropriate configurations:
<link rel=”stylesheet” href=”path/to/add2home.css”>
<script type=”application/javascript” src=”path/to/add2home.js”></script>
Figure 1.9(I) The Add to Home pop-up on a mobile web app
More iOS Tips and Tricks
IPhone and iPad have provided several other proprietary properties their browsers will recognize that help create a more native mobile web app experience:
<meta name=”apple-mobile-web-app-capable” content=”yes” />
<meta name=”apple-mobile-web-app-status-bar-style” content=”black” />
<link rel=”apple-touch-icon” href=”iphon_tetris_icon.png”/>
<link rel=”apple-touch-startup-image” href=”startup.png” />
To explain each of these:
• apple-mobile-web-app-capable : A cue to the webkit browser that this website is behaving as a mobile, potentially offline, web app.
• apple-mobile-web-app-status-bar-style : Hides the browser status bar by scrolling the screen right down to the beginning of the web page on page load. The status bar will still appear when a user scrolls all the high . This also hides the navigation bar when the app is offline.
• apple-touch-icon : Points to the mobile web app icon image to seem on the device home screen.
• apple-touch-startup-image : Points to the mobile web app startup image.
JQuery Mobile
JQuery Mobile is another tool that helps make great mobile web UIs. JQuery Mobile provides an HTML5-based, touchscreen-optimized user interface framework for cross-platform mobile devices. Based on the established jQuery and jQuery UI foundations, it’s lightweight and easily themeable.
To get started, simply link to the jQuery and jQuery mobile scripts and the default style sheet:
<link rel=”stylesheet” href=”http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css” />
<script type=”text/javascript” src=”http://code.jquery.com/jquery-1.6.4.min.js”>
</script>
<script type=”text/javascript” src=”http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js”></script>
Instead of making the jQuery Mobile interface appear as if the iPhone or Android interfaces, jQuery Mobile has an independent UI style that appears good and functions nicely on all mobile browsers. JQuery also provides a Themeroller tool, where designers select desired colors and designs and a method sheet is generated automatically.
Besides slick mobile styling, jQuery Mobile provides rich form controls, layouts for lists and overlays, and UI widgets like toggles, sliders, and tabs. Inspect the fast Start Guide for step-by-step instructions.
Android Inc. Was initially started in 2003, out of a frustration with the smartphone market because it existed at the time. It had been acquired by Google in 2005. The hardware side of Android is supported by the Open Handset Alliance (OHA), which may be a conglomeration of the many handset manufacturers, and therefore the software is maintained by the Android Open Source Project, which is led by Google. Android had its first major release in late 2008; the primary major phone company to support it had been T-Mobile, and therefore the original handset was the HTC Dream (G1).
The Android OS was built on a modified Linux kernel and applications are written in Java. By using Java because the development framework for the applications, Android enables you to develop your application on all major platforms. By leveraging the Eclipse IDE, Android affords the user almost the precise same user experience for development on all major OS platforms. Additionally, when researching Android you'll come upon the name Dalvik. It's the virtual machine that runs on the Android device, and your applications run within it.
A. Why Target Android?
Among the various reasons to focus on the Android platform is cost. On the average you'll get an Android smartphone for a fraction of the value of an iPhone. They'll not have commensurate features, but thrift may be a major component for new smartphone buyers.
Next is flexibility. More sorts of Android devices are available, so if your application fits a specific market, there's probably a tool that might support your needs already in production. At the time of writing, there are effectively two iOS devices; four if you include the retina display versions, versus roughly 15 form factors to develop for.
If you're already a Java developer, adding Android to your repertoire may be a snap. What Java is to Android, Cocoa is to CocoaTouch and C# is to Silverlight. All of the frameworks that mobile developers use are a mixture of subsets and supersets of the functionality of a given technology.
Identifying an application that exists on another platform but doesn't yet exist on Android is another perfectly good reason to focus on Android. That being said, you ought to do some research, because if a developer has targeted iOS or BlackBerry because the primary platform, you've got to assume that Android is potentially on the horizon.
B. Who Supports Android?
HTC, LG, Motorola, and Samsung are the main players within the Android smartphone market. Archos, Dell, Samsung, and Toshiba hold the most important pieces of the Android tablet market. You ought to note that Amazon’s Kindle Fire and Nook Color are up-and-comers and use a customized version of the Android tablet OS on their devices.
C. Android as Competition to Itself
Because Android was designed to be run on many various sorts of devices, created by many various manufacturers, it's left itself open to the desire of said manufacturers. Due to the open nature of the Android OS, it's commonplace for manufacturers to make vendor-specific builds of Android, and when this happens you're beholden to them for OS updates.
Additionally in these custom builds, vendor-specific limitations have arisen like the vendor-specific market. You then have another hurdle to cross when releasing your application for sale to the general public because some devices might not be ready to purchase it due to these limitations.
Another issue that has cropped up is that the lack of over-the-air (OTA) distribution of OS updates by cellular carriers. Often your device is perfectly capable of running a later version of the Android software, but carriers are often slow to distribute that to their customers.
Multiple Markets and Market Locks
Depending on your version of Android, and depending on the manufacturer of a given device, you'll find yourself locked into employing a vendor-specific Android marketplace. Additionally, application vendors can list their application not only on Google Play or vendor-specific marketplaces, but also on the Amazon App Store.
You often find on cheap and imported Android devices a version of Google Play that's maintained by the manufacturer. They pick and choose what applications are available from the entire set within the marketplace. You ought to develop as you expect to be available to all or any Android devices; just note when purchasing large quantities for an enterprise deployment that you will need to be careful for these inconsistencies.
The version of the Android SDK that you simply got to support depends on what devices you would like to support. If you would like to focus on most phones available immediately , you should support Android 2.2 or 2.3. “Gingerbread” (2.3) is that the last widely available version for those devices. The Android 3.x versions are for tablets, like the Samsung Galaxy Tab. The Android 4.x versions are the most recent , and are a mixture of the Android 2.x and Android 3.x functionality meant to pull back on the version splintering seen in devices, but not many devices currently in release support it.
Once you've got selected a version to deploy your application against, you would like to line up your development environment. Within the next section you'll learn all about configuring your IDE, Java and Android SDKs, and building emulators.
D. Getting the Tools You Need
This section paraphrases the installation instructions from the Android Developer section, and we added some personal notes from our experiences.
Downloading and Installing JDK
The first thing that you simply got to do to develop Android applications is to visit http://www.oracle.com/technetwork/java/javase/downloads/index.html and make sure that you've got the Java JDK installed. Because numerous different acronyms and versions appear on the Java download website, Figure points you within the direction you would like to urge past all of the potential distractions thereon site.
The JDK is that the Java Development Kit. You would like this package to try to to any Java development on your machine, Android or otherwise. Make certain to seem for the Java Platform, Standard Edition JDK.
Downloading and Installing Eclipse
After you've got successfully installed the JDK, you'll need a development environment. The open source IDE Eclipse is suggested by Android directly in its documentation. You're not limited only to Eclipse, but the tooling has been honed over time to be the simplest solution to urge up and running. Figure shows the Eclipse download page ( www.eclipse.org/downloads ). Download the version of Eclipse Classic that's appropriate for your OS .
Downloading and Installing the Android SDK
After you have installed the Eclipse IDE, you need to install the Android Software Developer Kit. This contains all the tools necessary to build Android apps, because the SDK is not built directly into Eclipse.
Downloading and Configuring the Eclipse ADT Plug-in
After you've got installed the Android SDK you would like the ADT plug-in. What this does is add the features necessary to make Android Projects, because they're not bundled with the bottom Eclipse install. Additionally, the plug-in adds debugging tools to Eclipse to assist during the Android development process. Figure shows the interface for installing the ADT plug-in. You'll also use this interface when upgrading ADT. The tooling generally gets a revision when a replacement version of the Android OS is released.
Use the Update Manager feature of your Eclipse installation to put in the newest revision of ADT on your development computer. Follow these steps:
1. Start Eclipse and choose Help ➪ Install New Software.
2. Click Add within the top-right corner.
3. Within the Add Repository dialog box that appears, enter ADT plug-in for the name and therefore the following URL for the location: https://dl-ssl.google.com/android/eclipse/.
4. Click OK. If you've got trouble acquiring the plug-in, try using “http” within the Location URL rather than “https”.
5. Within the Available Software dialog box, select the checkbox next to Developer Tools and click on Next.
6.The next window shows an inventory of the tools to be downloaded. Click Next.
7. Read and accept the license agreements then click Finish. If you get a security warning saying that the authenticity or validity of the software can’t be established, click OK.
8. When the installation completes, restart Eclipse.
Once you've got downloaded the ADT plug-in you would like to line it up to speak to the Android SDK that you simply downloaded earlier. This enables Eclipse to create , run, and debug Android applications without having to open a terminal or command shell.
After you’ve successfully downloaded the ADT, subsequent step is to modify your ADT preferences in Eclipse to point to the Android SDK directory:
1. Select Window ➪ Preferences to open the Preferences panel. In Mac OS X, click Eclipse ➪Preferences.
2. Select Android from the left panel.
3. You'll see a dialog box asking whether you would like to send usage statistics to Google. If so, make your choice and click on Proceed. You can't continue with this procedure until you click Proceed.
4. For the SDK Location within the main panel, click Browse and locate your downloaded SDK directory.
5. Click Apply then click OK.
Installing Additional SDK Components
The last step in preparing your development environment for Android is to download additional Android OS packages. This permits you to create applications that focus on that OS, and also gives you the tools you would like to emulate a tool running that OS on which to check all of your applications, whether or not they need been targeted thereto OS version.
Correctly configuring and using this tool will make sure that you've got all the newest SDKs and utilities afforded to you. Note that you simply won't necessarily need all of the versions of the SDKs listed this was merely for instance the complete breadth of your options. Loading the Android SDK Manager in Eclipse takes only a couple of steps:
1.Open Eclipse.
2. Select Window ➪ Android SDK and AVD Manager.
3. Select Available Packages in the left panel. This reveals all of the components that are currently available for download from the SDK repository.
4.Select the component(s) you’d like to install and click Install Selected.
5. Verify and accept the components you want and click Install. The components will now be installed into your existing Android SDK directories.
Development
The following sections contains the application layout and Android app development.
Creating a New Project
First belongings you need to create a new Android project. The line highlighted in Figure is that the sort of project you would like .
First you would like to name your application and add it to a workspace. Consider a workspace because the folder during which your application resides. Figure illustrates what the New Android Project screen seems like . After you've got named your application you'll got to provides it a package name, set the minimum SDK required to run your application, and name the initial Activity which will run when your application runs. If you would like to feature a test project to your workspace, you'll do so at this time.
An important note at this point: confirm that your package name is exclusive . The quality format for package names is com.companyName.applicationName . This must be unique because that's how it's known on the Android device and within the Android Market. Once you make updates you'll make them only within your package name. If you modify your package name there'll be no upgrade path between versions.
The minimum SDK required is usually set once you are leveraging a permission or piece of functionality that didn't exist when the core Android version was released, or if you would like to focus on a specific kind of device. The main jumps are between 1.6 and 2.1, 2.3 and 3.x, and 3.x and 4.x.
This step is additionally important when building your application. The minimum SDK version you set specifies rock bottom possible version of the SDK during which your application will run, and it's the first version during which your application will run. Android 1.5 is that the lowest version of the SDK still supported, and Android 4.0.3 is that the highest.
Project Structure
The major are the src and res folders and therefore the AndroidManifest .xml file. It shows the project layout for the application.
All of your code lives within your src folder, under your Package Namespace. The res folder holds layouts and resources for various hardware specs. HDPI, LDPI, and MDPI are the resolutions that you'll create images. The layout subfolder holds all of your XML layouts. These are how your application gets rendered. The code are going to be the way to populate these layouts. All of your XML layouts are stored within the layout subfolder of res , and your code are going to be linked under the namespace in your src folder of the project view.
The Android Manifest is that the heart of your application. It holds the whole configuration of your app the permissions you request, the application attributes, and links to instrumentation to be attached to your app. You'll edit this in Eclipse’s Manifest Editor or in XML because that's how it's saved.
The Manifest Editor is where the initial information of your application is stored once you create it. This interface also has links to export your application. Exporting is important when submitting your app to Google Play. In Eclipse there's a selected menu option and wizard that expedites the submission process.
The spartan view is that the Permissions Editor. Here you'll add permission requests to your application. The foremost common one is android.permission.INTERNET , which allows the application to use the device Internet connectivity. This, along side GPS and accelerometer, are the permissions you'll increase the Derby Names application.
As you create changes within the other tabs they're reflected here. If you are feeling easier editing the XML by hand you'll use this interface to add, update, and take away properties as you see fit.
Android Basics
You have two options for starting your application. You'll build the layout you'd wish to populate, otherwise you can build the code which will populate the layout. Either is acceptable; it just depends on what you are feeling most comfortable with.
Creating User Interfaces This section describes the common widgets that come with Android, and shows samples of the various layout elements you'll use to coordinate the flow of your application’s activities.
Basic Android UI Elements
All of the basic elements in Android are stored in the android.widgets namespace in the SDK.
The most commonly used elements include:
- Button: This is a standard button element.
The following XML specifies the layout of the Button widget:
<Button
Android:layout_height=”wrap_content”
Android:layout_width=”wrap_content”
Android:id=”@+id/button”
Android:text=”Click Me”
Android:onClick=”btnClick” />
Code: This code is necessary to handle the Click event noted in the XML layout.
Public void btnClick (View view)
{
//Do Something.
}
- TextView: once I see this i would like to think text box, but it isn’t a text box. TextView is effectively an equivalent as a label in other languages. It's just an area to display text.
- EditText: this is often the text box widget. You'll edit the contents of the text box and save those values in code.
- CheckBox: this is often a typical checkbox element.
- RadioButton: this is often a typical radio button element. To actually get the foremost bang for your buck, though, you would like a RadioGroup .
- ListView: this is often the element you use if you would like to point out lists of knowledge . You'll overload its display and put many elements in each row, otherwise you can just bind a text item and a worth to every . The trick is using an ArrayAdapter where T is that the sort of object that you simply want bound. Additionally, creating a layout XML for a way you would like each item displayed may be a good strategy.
Basic Android Layouts and Views
- FrameLayout: this is often very simplistic and may really contain only one UI element. You can, in fact, have multiple elements but they overlap one another by default.
- TableLayout: Think tables in HTML and this is often the kind of organization you get with this layout. TableLayout s contain rows and columns, representing a grid, and you'll put other UI elements into it. The subsequent code leads to a table with two rows, each with two cells.
- RelativeLayout: this is often the foremost complex layout of the four mentioned during this section. You specify relationships between UI elements to get out your interface.
Creating an Android Virtual Device
You need to create an Android Virtual Device (AVD) in order to debug your application in the emulator, because this “device” is what the emulator runs. Creating an AVD is quite easy. Eclipse includes a tool called AVD Manager. You need to name your AVD instance, choose its OS version (Target), pick a skin and resolution, and specify the hardware details for the device. Once you have configured it to your specifications, click Create AVD and you are all set.
For most purposes, the stock AVD skins are fi ne for debugging, rendered but if you would like to emulate a specific device (tablet or handset) either for demonstration purposes or because you want it to feel like the device you are developing for, you can use a custom skin. Although you can always set the hardware properties to mirror those of the device you are using, there is an online community dedicated to making custom skins for use with the AVD.
Using your favourite search engine, type the model and make of the Android device you want to emulate, and most likely you will find a custom skin out there for it. Creating a new AVD with the appropriate specs and then selecting this skin gives you an emulator that looks just like the device you are testing for.
Debugging
Debugging in Eclipse is straightforward. Rather than running your application, you click Debug As and you're off and running. Set breakpoints in your code by selecting them by the gutter next to the road numbers, and as your code progresses it'll break in the least your steps. Additionally to breakpoint-based debugging, you furthermore may have access to the Dalvik Debug Monitor Server (DDMS) perspective in Eclipse.
You can use DDMS to look at the heap usage for a given process, track memory allocation of objects inside an app, interact with the file system of the device running the app, view running threads for an application, profile methods using tracing, read log messages using LogCat, and emulate phone and sensor data.
E.Connecting To the Google Play
There Amazon Android Marketplace, which has other requirements. But it may be more of a marketing choice than a development choice, we decided to go with the explanation of the basic Google Play distribution process.
Getting an Android Developer Account
Signup is a snap for a dev account. Just make sure you have a Google account (Gmail, or Google Apps), $25 (one-time registration fee), head to https://play.google.com/apps/publish/signup , and you are all set.
Signing Your Application
Signing your application with Eclipse is a simple process:
1.Right-click your project in the Package Explorer and select File ➪ Export.
2.Select Export Android Application.
3.Complete the steps and you will have a keystore, and a signed release build of your app ready for the market.
When you have created your keystore, ensure to guard it safely. It is the file you will use to sign your application every time you update, and if you lose it you cannot upgrade your application in Google Play.
F.Android Development Practices
Android Fundamentals
When developing an Android app you need to account for which of the four basic components like Activities, Services, Content Providers, and Broadcast Receivers of apps you need to include.
Activities
Activities are the individual screens in your application. All of the functionality that is exposed in the UI for that screen lives in the scope of that Activity.
Services
Services are components that run during a background thread. Common usages for services are to carry long-running processes, or for functions which will happen in parallel with the application. Remember that once you have an application running within the background it can take processing power from the device, though contrary to popular thought it doesn't affect your battery life.
Content Providers
Content providers are interfaces to the offline storage that you simply have within your app. If you create a set of applications you'll want to have one point for holding all of your data. You'll also leverage the Content Providers built into the Android OS. The quality set of providers within the OS allows you to get content from the Calendar, Contacts, Media Store, Messaging, and Voice Mail applications.
Broadcast Receivers
Broadcast receivers are components that answer system messages. You'd use a Broadcast Receiver to catch events just like the screen turning off, or the battery reaching a critical level. a standard use for a Broadcast Receiver is for querying the status of the network (Wi-Fi or cellular) in order that you'll display the acceptable messaging to the user.
Fragments as UI Elements
Starting in Android 3.x, there has been a shift in design elements to account for the significant differences between the screen sizes of tablets versus handsets.Whereas normally UI design for mobile devices is extremely rigid, Fragments add A level of flexibility. Fragments themselves live as a sub activity that you simply can reference in multiple places in your application. Fragments live within the scope of their parent activity, but are often utilized in multiple activities.
Ask for Permission
The users of your application must approve of what functionality you would like to leverage on their device. To prompt the user for what you would like, then that your device will behave as designed, you would like to feature permission requests in your application’s manifest. Visit http://developer.android .com/reference/android/Manifest.permission.html for a list the varied permissions you'll request when developing.
Depending on what version of the OS you're targeting you're afforded additional permissions. One among the most recent permissions available is READ_SOCIAL_STREAM , which enables you to access the user’s social stream. One among the oldest permissions is your ability to set the given zone , using, you guessed, it SET_TIME_ZONE .
If you are trying to run a piece of code within the emulator and it should be responding to firing events or taking note of hardware, and it isn’t, confirm you've got requested permission in your app.
Additionally, don't request every possible permission. Applications that do that are often considered malware or a minimum of not trustworthy by the layperson.
Mind the rear Stack
Unlike iOS-based devices, all Android devices have a hardware back button. What this suggests is that there's something physical on the device that interrupts the UI and takes the user to the previous action. This is often known within the back stack. It are often likened to a browser history or a copy/ paste clipboard. How this differs from those, though, is that it must be stateful.
You must understand that you simply got to persist the state of the View when returning thereto from the rear stack. Additionally, if the present view affects the state of the previous view, you want to update it accordingly without requiring the user to click a UI element; it must be ready to be updated when the user backs up the stack.
G. Building the Derby App in Android
The needs are to list the roster from the Lansing Derby Vixens roller derby team as the primary function, and then list all the roller derby teams in the world with the ability to see their team rosters.
Common Interactions
The main ways to get your users around your app, and to let them know when events happen or issues arise is by using well-managed UI navigation, and timely use of notifications.
UI Navigation and Using Back Stack
Because Android devices are equipped with a dedicated hardware back button, you required to make certain considerations as you pass from activity to activity in your application. The states of activities are stored in a back stack that persists and allows users to walk back through the navigation one button click at a time. Extras are stateful objects held within Intents that are the primary way that you communicate between activities. Considered “the glue between activities”. Intents provide a simple storage mechanism that can be retrieved and set, and are passed between two activities.
Use the GetExtra command to retrieve simple and complex objects from one activity to another using an Intent.
You can select the extras you want to refer to individually from the Intent. For example:
String id = getIntent().getStringExtra(“id”);
String name = getIntent().getStringExtra(“name”);
Or you can get all of the objects you passed along as a Bundle :
Bundle extras = getIntent().getExtras();
String userName;
String id;
If (extras != null) {
UserName = extras.getString(“name”);
Id = extras.getString(“id”);
}
Use the PutExtra command to put the object you want to pass between activities. You can pass simple or complex objects. You need to use Extras only when you want to pass data between activities. It is not necessary to set a complex state transfer process if you don’t need that data.
String username = “DerbyUser”;
String id = “derbyuser42”;
Intent newIdea = new Intent(this, newIdea.class);
NewIdea.putExtra(“username”, username);
NewIdea.putExtra(“id”, id);
StartActivity(newIdea);
Notifications
You have lots of ways to display content to your users: either in your Base UI or through different types of notifications. What follows is an explanation of toasts and alerts.
Toasts
A toast is a quick notification that displays (by default) in a gray translucent box over your UI.
Context context = getApplicationContext(); //Find the application you are currently running
CharSequence text = “Greetings from the App!”; //This is the message you want to share.
Int duration = Toast.LENGTH_SHORT; //This is a constant in the SDK for a quick
Notification
Toast toast = Toast.makeText(context, text, duration); //Create the toast object
Toast.show(); //Display it for the duration now.
Alerts
Simpler even than toasts, alerts are very similar to JavaScript alerts in that they pop a modal form with which you have very little ability to interact. You can set a button to represent affirmation, declination, and cancellation alerts. The following snippet of code shows how to do that:
//Create a new AlertDialog using its builder respective to the current context.
New AlertDialog.Builder(this)
.setTitle(“Alert Title”) //Set Title for the Alert
.setMessage(“Is this the message you expected?”) //Set Message for the alert
.setNegativeButton(“No”, null) //Set the Declination Button (Optional)
.setPositiveButton(“Yes”, null) //Set the Affirmation Button (Optional)
.setNeutralButton(“Who Cares”, null) //Set the Cancellation Button (Optional)
.show(); //Display the alert now.
Like all things in Android, you can customize notifications. You can find more information on customizing them at http://developer.android.com/guide/topics/ui/notifiers/index.html .
Offline Storage
Even though the bulk of Android devices are smartphones which afford users an always-on, always-connected experience many reasons exist to store data on the device versus querying the a service remotely. For simple or small pieces of data you can use Shared Preferences; for larger data sets that may include complex objects, you can use SQLite.
SQLite
SQLite is a flat-file database that runs inside the Android framework. You can use it to store large object graphs or significant amounts of data so that you aren’t constantly connecting to a remote source.
SharedPreferences
SharedPreferences may be a set of key-value pairs saved on your device that's helpful for storing instance-specific data because it pertains to the app. The most concern is that the level of privacy that you simply impose upon it. If you create it world-readable its value are often accessed by any application should another application query against your key. This function is an example of leveraging
SharedPreferences to store application preference for the user:
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Public void savePreferenceToSharedPreferences(String key, String value){
Editor.putString(key, value);
Editor.commit();
}
Public String loadPreferenceFromSharedPreferences(String key)
{
String tmpRtn = sharedPreferences.getString(key, “”);
Return tmpRtn;
}
Web Service
This section goes over what you need to do to consume this information. In this example you write out the data to the log:
Public class DerbyDataActivity extends Activity {
/** Called when the activity is first created. */
@Override
Public void onCreate(Bundle savedInstanceState) {
Super.onCreate(savedInstanceState);
SetContentView(R.layout.main);
GetLansingDerbyVixens();
}
Long-Running Tasks over the Web
Please remember that if you're getting to be downloading a lot of information over any web request, or if you're during a high-latency situation, you would possibly want to seem into using the AsyncTask for handling long-running tasks on a background thread. If your main thread hangs for roughly five seconds, you'll receive a message.
GPS
The following function connects to your device’s GPS and displays a toast of your latitude and longitude when you go past its set threshold:
Public class SensorsGPS extends Activity {
/** Called when the activity is first created. */
@Override
Public void onCreate(Bundle savedInstanceState) {
Super.onCreate(savedInstanceState);
SetContentView(R.layout.main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager locManager = (LocationManager) getSystemService(Context.
LOCATION_SERVICE);
LocationListener locListener = new MyLocationListener();
LocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
LocListener);
}
/* Class My Location Listener */
Public class MyLocationListener implements LocationListener
{
@Override
Public void onLocationChanged(Location loc) {
Loc.getLatitude();
Loc.getLongitude();
String Text = “My current location is: “ + “\nLatitude = “ + loc.getLatitude()
+ “\nLongitude = “ + loc.getLongitude();
Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}
@Override
Public void onProviderDisabled(String provider)
{
Toast.makeText(getApplicationContext(), “GPS Disabled”, Toast.LENGTH_SHORT).
Show();
}
@Override
Public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), “GPS Enabled”, Toast.LENGTH_SHORT).
Show();
}
@Override
Public void onStatusChanged(String provider, int status, Bundle extras) {}
}
Accelerometer
In order to trace motion and position of the Android device you'll leverage the device’s built-in accelerometer because it monitors the x, y, and z axes of the device.
Reference Text Book
1. Jeff McWherter, Scott Gowell, Professional Mobile Application Development, John Wiley & Sons, Ref: www.it-ebooks.org
2. Maximiliano Firtman, Programming the mobile Web, Oreilly, 2nd Edition, 2013, ISBN: 978-1-449-33497-0