Optimizing web applications for Android

Một phần của tài liệu Manning android in action 3rd (Trang 471 - 478)

We start this discussion by considering how to code web applications so they’re view- able both by desktop clients and by mobile platforms such as Android. Developing web applications for Android can be viewed as a continuum of options. On one end is a site created for universal access, meaning that it’ll be visited by both desktop and mobile users. On the other end of the spectrum is a website designed specifically for mobile users. Between these two extremes are a couple of techniques for improving the user experience. We’ll use the term mobile in mind—this refers to a website that’s not exclusively written for mobile users but expects them as part of the regular visitor list. Let’s begin with a discussion of designing your site with mobile in mind.

16.2.1 Designing with mobile in mind

There are millions of websites, but only a small percentage were created with mobile devices in mind—in fact, many sites were launched prior to the availability of a mobile browser. Fortunately, the browser in Android is capable of rendering complex web content—even more powerful than any of the early desktop browsers for which those early sites were designed.

When designing a universal website—a site that’s to be consumed by desktop and mobile users alike—the key concept is to frequently check your boundary conditions.

For example, are you considering fly-out menus that rely on hovering with a mouse?

That approach is a nonstarter for an Android user; there’s no mouse with which to hover. And unless you’re a giant search engine provider, you want to avoid coding

your site to the least common denominator approach of a single field per page. That might get you by for a while on a mobile browser, but your desktop users will be both confused and annoyed. You need to meet the needs of both sets of users concurrently.

You may be starting from a position that creating two sites—one for desktop and one for mobile—is out of your reach from a budgetary perspective. We’ll come back to the multiple-site approach later, but for now let’s design with mobile in mind.

To meet that objective, we examine two approaches to improve the visual appear- ance and usability of a mobile-in-mind website. Start with a simple HTML page, shown in the following listing.

<html>

<head>

</head>

<body>

<h1>Unlocking Android Second Edition</h1>

<h2>Chapter 16 -- Android Web Development</h2>

<hr />

<div style="width:200px;border:solid 5px red;">

<p>For questions or support you may visit the book's companion <a

href="http://manning.com/ableson2">website</a> or contact the author via

<a href="mailto:fableson@msiservices.com">email</a>.</p>

</div>

<img src="http://manning.com/ableson2/ableson2_cover150.jpg" /></body>

</html>

When this HTML page is rendered in the browser, the content is “zoomed out” such that it all fits onto the page. Go ahead; try it yourself by pointing your Android browser to http://android16.msi-wireless .com/index.php. Figure 16.1 shows the content ren- dered in the standalone browser on an Android device.

The text is too small to easily be read on the phone.

The user can of course pinch, zoom, and scroll the content to make it more easily consumed. But if you know that the site visitor is viewing your site on a mobile device, wouldn’t it be a good idea to put out the welcome mat for them, keeping their pinching and zooming to a minimum? Fortunately, there’s a simple means of modifying the visual appearance of your site so that when visitors arrive at your site via their Android device, you can make them feel like you were expecting them. To accomplish this simple but impor- tant task, you use the viewport meta tag.

Listing 16.1 Sample HTML page

Figure 16.1 Simple web page

16.2.2 Adding the viewport tag

The lowest-cost and least-obtrusive solution to the default view being too small to see is the use of a special meta tag. Meta tags have long been the domain of the search engine optimization (SEO) gurus.2 A meta tag is placed within the <head></head> tags of a web page to specify such things as the page keywords and description—which are used by search engines to help index the site.

In this case, the meta tag of interest is the viewport. A viewport tag tells the client browser how to craft a virtual window, or viewport, through which to view the website.

The viewport tag supports a handful of directives that govern the way in which the browser renders the page and interacts with the user.

To provide a more appealing rendering of our sample HTML page, you’ll add a viewport tag between the head tags. Listing 16.2 shows the same web page, but it now includes the viewport meta tag. If you want to view the page on your own Android device, you can do so at http://android16.msi-wireless.com/index_view.php.

<html>

<head>

<meta name="viewport" content="width=device-width" />

</head>

<body>

// omitted html text

</body>

</html>

This web page has been made more mobile friendly by the addition of the viewport meta tag B. The content attribute of the tag conveys directives to govern how the viewport should behave. In this case, the browser is instructed to create a viewport with a logical width equal to the screen width of the device.

Figure 16.2 demonstrates the impact this one line of code has on the visual appearance of the web page.

Note how the text of the page is larger and more acces- sible. To be fair, this is an ultrasimple example, but the point is that you can provide a readable page right from the start, and the user can easily scroll down verti- cally to view the remainder of the site without needing to zoom in or out just to make out what the page says.

You can specify the width in pixels rather than requesting the width to be equal to the device-width. This approach can be useful if you want to display a graphic in a certain manner or if your site can

2 See http://searchenginewatch.com for everything SEO related.

Listing 16.2 Adding the viewport meta tag

Viewport meta tag

B

Figure 16.2 The viewport tag modifies the appearance of the web page.

remember a user’s preferences and by default set up the logical dimensions accord- ing to the user’s liking. Table 16.1 describes the ways in which you can customize the viewport.

Adding a viewport meta tag to a web page is safe, because any meta tags that aren’t supported by a client browser are ignored, with no impact on the page. This one tag provides a simple yet useful enhancement to an existing website. Although this isn’t a magic bullet to solve every challenge associated with viewing a website on an Android phone, it does aid in the first impression, which is important.

Before moving on, we have one additional feature of the viewport tag to demonstrate: scaling. Figure 16.3 shows the same web page scaled to 1.3 times the origi- nal size. This approach can be used to scale a page up or down, within the constraints defined by the mini- mum-scale and maximum-scale directives as described in table 16.1.

This scaled-up web page may or may not provide your desired effect. The good news is that you can adjust the initial-scale value to your liking. In prac- tice you’ll likely set the value to somewhere between 0.7 and 1.3.

The viewport tag is almost a freebie: add the tag, and if the browser recognizes it, the page’s rendering will be modified and likely improved. You can take a bit more control than this by selectively loading con- tent or style sheets based on the type of browser visit- ing your site. That’s what we explore next.

Table 16.1 Viewport meta tag options

Directive or attribute Comment

width Used to specify the width of the logical viewport. Recommended value:

device-width.

height Used to specify the height of the logical viewport. Recommended value:

device-height.

initial-scale Multiplier used to scale the content up (or down) when the page is initially rendered.

user-scalable Specifies whether the user is permitted to scale the screen via the pinch zoom gesture. Value: yes or no.

maximum-scale Upper limit on how far a page may be scaled manually by the user. Maximum value is 10.0.

minimum-scale Lower limit of how far a page may be scaled manually by the user. Minimum value is 0.5.

Figure 16.3 Scaled-up web page

16.2.3 Selectively loading content

Assuming your budget doesn’t provide for creating and managing entirely parallel websites to meet the needs of your desktop and mobile visitors, you need a strategy for adequately delivering quality content to both types of users. To go beyond the func- tionality of the viewport tag, you want to have a more predictable experience for your mobile visitors. To accomplish this, you’re going to selectively load CSS based on the type of visitor to your site.

Browser detection approaches have matured over time. Next we explore two basic methods to accomplish this task, keeping in mind that your site is meant to be univer- sal and expecting browsers of different shapes, sizes, and capabilities.

16.2.4 Interrogating the user agent

The first approach involves the examination of the user agent string. Every time a browser connects to a web server, one of the pieces of information it provides in the HTTP request is the browser’s user agent. The user agent is a string value representing the name of the browser, the platform, the version number, and other characteristics of the browser. For example, the user agent of a Nexus One running Android 2.2 looks like this:

Mozilla/5.0 (Linux; U; Android 2.2; en-us;Nexus One Build/FRF91) AppleWebKit/

533.1 KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

The contents of this string may be examined and subsequently used to decide which content and or CSS files to load into the browser. The following listing demonstrates the use of the user agent string to selectively choose a CSS file.

<html>

<head>

<meta name="viewport" content="width=device-width" />

<link rel="stylesheet" href="corestuff.css" type="text/css" />

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

if (navigator.userAgent.indexOf('Android') != -1) {

document.write('<link rel="stylesheet" href="android.css"

type="text/css" />');

} else {

document.write('<link rel="stylesheet" href="desktop.css"

type="text/css" />');

}

</script>

</head>

<body>

...

</body>

</html>

Listing 16.3 Interrogating the user agent

B

Load core CSS

Look for Android userAgent

C

This HTML snippet includes a viewport meta tag, specifying that the viewport’s width should match the width of the device. A CSS file is included named corestuff.css B. Regardless of the platform, this file contains required classes and styles related to the application. Using this approach, the web application includes a style sheet aimed at more than one target platform. This enables us to have a more deterministic impact on the behavior on a particular device, leaving less to chance. Our primary content hasn’t changed—remember, we’re still targeting a universal website but keeping mobile users in mind. Clearly, more work is being done here, as various stylistic ele- ments have been extracted into platform-specific files. As such, we’re taking a mea- sured step down the continuum toward a made-for-mobile site. If the user agent string contains the word “Android” C, the code loads the user-supplied android.css style sheet. If the user agent isn’t from an Android device, the code loads a style sheet named desktop.css. Additional conditional statements may be included here for other mobile platforms, such as the iPhone or BlackBerry.

User agent strings contain a considerable amount of information, though just how much of it is useful and trustworthy is a topic of debate. For example, it’s not uncom- mon for a hacker to write code to programmatically bombard a target website and in the process craft a user agent that masquerades as a particular kind of browser. Some versions of websites are more secure than others. A user agent value is easy to forge, and although the security implications aren’t expressly of concern to us in this discus- sion, it’s something to keep in mind.

The user string has so much data that you have to do a bit of homework to inter- pret it properly. Some JavaScript libraries can aid in this process, but ultimately it may not be the best approach. There’s another way: the media query.

16.2.5 The media query

Early web styling included inline markup such as font and bold tags. The best practice in web design today is to separate styling information from the content itself. This involves adding class attributes to elements of content and relying on a style sheet to dictate the specific colors, sizes, font face, and so on. Providing multiple CSS files for a given page enables flexible management of the numerous styles needed to deliver a crisp, clean web page. This approach also permits flexibility in terms of which styles are used for a particular device.

Professional content sites have leveraged this approach through the use of multi- ple, targeted style sheets along with extensive use of the link statement’s media attri- bute. The media attribute acts as a filter for determining which style sheets should be loaded. For example, consider the familiar scenario where you purchase something online and you’re shown your receipt. The page may have fancy graphics and multiple elements organized in a creative manner. But when the page is printed, the output is relatively benign and thankfully easy to read. This is accomplished through the use of the media attribute applying a print-oriented style sheet. You can leverage this same approach to build mobile-in-mind web pages.

The following listing presents a snippet from a web page with support for many style sheets, including two for mobile-specific use.

<link href="//sitename/css/all.css" media="all"

rel="stylesheet" type="text/css" />

<link href="//sitename/css/screen.css"

media="screen,projection"

rel="stylesheet" type="text/css" />

<link href="//sitename/css/screenfonts.css"

media="screen,projection" rel="stylesheet"

type="text/css" />

<link href="//sitename/css/print.css"

media="print" rel="stylesheet" type="text/css" />

<link href="//sitename/css/handheld.css"

media="handheld" rel="stylesheet" type="text/css" />

<link href="//sitename/css/handheld-small.css"

media="only screen and (max-device-width:320px)"

rel="stylesheet" type="text/css" />

The media query of allB indicates that the associated style sheet (all.css) is appro- priate for all devices. The screen.css file C is filtered for screen or projectors only. An additional screen- or projector-targeted style sheet named screenfonts.css D is

included to organize all font-related styles. For hard-copy output, the media value of print is used E. The media value of handheld F is intended for handheld devices, though when the media query specifications were first drafted, the capabilities of mobile browsers were quite limited—certainly much less feature rich than the Android browser is today. Therefore, a better approach is to use a media query related to specific attributes such as screen dimensions. For example, if you’re targeting a par- ticularly small device, you can use a specific attribute-oriented media query. The hand- held-small.css file G will be used when you have a screen width of no more than 320 pixels.

As with all things browser related, your mileage may vary over time with different releases. There’s no substitute for regression testing.

The actual technique of employing CSS within your code is beyond our scope and interest here; you can find many good references on the topic. The takeaway from this discussion is to be prepared to employ the appropriate CSS for each visitor to the site based on their respective web browser capabilities. The media query is a powerful tool in your arsenal.

Of course, no matter the amount of effort you put into making your universal web- site mobile friendly, there are times when a site should simply be designed from the ground up for mobile users.

16.2.6 Considering a made-for-mobile application

Here we are, finally at the other end of the spectrum where we look at web applica- tions that are designed explicitly for mobile devices. After all, the best mobile web

Listing 16.4 Sample link statements

all.css

B

Screen filter

C

Fonts only

D

Print

E only Handheld device CSS

F

Media query based on screen size

G

applications are designed to be mobile applications from the start and aren’t simply the full application versions crammed onto a smaller screen, relying on the browser to render them. The Android browser will display the pages, but the full-blown websites are often too heavy and busy for the typical mobile user. The reason is simple: using a mobile device is a different experience than sitting at your desk with a mouse and full keyboard.

More often than not, the Android user is on the move and has little time or patience for dealing with data entry-intensive UIs or sifting through large result sets. Mobile transactions need to be thought out and targeted to the mobile user profile. Pretend you’re standing on a train looking at a piece of content or making a status update to a service ticket. If you have to select multiple menus or enter too many fields to per- form your work, it likely won’t get done.

Consider two axioms for made-for-mobile applications.

The first is to simplify, reduce, and eliminate. Simplify the UI. Reduce the data entry required. Eliminate anything that’s not needed. Seriously; pull out the scalpel and cut out things that don’t matter to someone in the field. Consider figure 16.4, which shows the mobile version of the Facebook application. There’s no nonsense here, just two fields: Email or Phone and Password, and a button to log in. Three links round out the page.

The second axiom is to provide a link to the full site and make sure that you don’t reroute the user to the mobile version if they’ve explicitly requested to go to the main page. Note the Full Site link in the lower-right corner of figure 16.4. Sometimes peo- ple have the time and need to dig deeper than the mobile version permits. When this occurs, let the user go to the main page and do whatever you can through the view- port tag and the media queries to make the site as palatable as possible, but with the full features.

It’s time to move beyond the browser-only visual aspects of web application devel- opment to consider more advanced techniques that Android developers have at their disposal. We look next at browser database management technology, which has the promise to take web applications, mobile and desktop, to unprecedented levels of functionality and utility.

Một phần của tài liệu Manning android in action 3rd (Trang 471 - 478)

Tải bản đầy đủ (PDF)

(662 trang)