編輯:中階開發
接續上篇,本文說明 iPhone 版本的四個進階能力,並完整介紹 Android 版本的實作方式。
為了讓使用者能左右滑動瀏覽產品,我們自訂了一個檢視控制器 ProductScrollViewController。它的檢視包含一個 UIScrollView(內部並排擺放各產品的詳情頁)與一個 UIPageControl(頁面指示器)。
當使用者點擊子類別畫面上的產品時,WebViewController 攔下 URL 請求,但這次推到堆疊上的不是普通的 WebViewController,而是 ProductScrollViewController。
圖 11. 可翻頁的產品詳情畫面

檢視載入完成後,控制器先載入當前產品以及前後各一個產品的檢視,作為 UIScrollView 的子檢視。使用者滑動時,再動態補上新產品的檢視。這種「當前加前後各一」的策略能在記憶體與流暢度之間取得平衡。
- (void)viewDidLoad {
[super viewDidLoad];
pageControl.numberOfPages = [urls count];
pageControl.currentPage = currentPage;
scrollView.pagingEnabled = YES;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width
* pageControl.numberOfPages,
scrollView.frame.size.height);
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.delegate = self;
[scrollView setContentOffset:
CGPointMake(scrollView.frame.size.width * currentPage, 0)];
[scrollView setBackgroundColor:[UIColor blackColor]];
[self loadScrollViewWithPage:pageControl.currentPage - 1];
[self loadScrollViewWithPage:pageControl.currentPage];
[self loadScrollViewWithPage:pageControl.currentPage + 1];
}
- (void)loadScrollViewWithPage:(int)page {
if (page < 0 || page >= pageControl.numberOfPages) {
return;
}
WebViewController *controller = [viewControllers objectAtIndex:page];
if (controller == [NSNull null]) {
controller = [[WebViewController alloc]
initWithNibName:@"WebViewController" bundle:[NSBundle mainBundle]];
controller.navigationController =
(UINavigationController *)self.parentViewController;
controller.request = [NSURLRequest requestWithURL:
[urls objectAtIndex:page]];
[viewControllers replaceObjectAtIndex:page withObject:controller];
[controller release];
}
if (nil == controller.view.superview) {
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
[scrollView addSubview:controller.view];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
if (pageControlUsed) {
// 這次滾動是由頁碼控制項觸發的,不是使用者拖曳
return;
}
// 當前一頁或下一頁露出超過 50% 時切換指示器
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlUsed = NO;
}
- (IBAction)changePage:(id)sender {
int page = pageControl.currentPage;
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
// 標記這次滾動由頁碼控制項觸發
pageControlUsed = YES;
}
我們沿用前面那座雙向橋,讓 Madisons Mobile 的「Email 加入關注清單」頁面能讀取 iPhone 通訊錄中的電子郵件地址。做法是在頁面上放一個特殊 URL 的連結,例如 testuishell:///emailpicker#callbackHandler。自訂的 testuishell:// 配置用來把它與一般 HTTP 請求區分開,而片段 callbackHandler 則是動作結束後要呼叫的 JavaScript 回呼函式名稱。
嚴格來說,除了語法要正確、且能與 HTTP 請求區分之外,這個特殊 URL 的格式並無其他限制。
圖 12. 整合 iPhone 通訊錄

使用者點下連結後,WebViewController 攔到請求,建立一個 ABPeoplePickerNavigationController 並以模態方式顯示通訊錄。使用者選完郵件地址後,WebViewController(被設為通訊錄控制器的代理)收到回呼,便以該地址為參數呼叫 JavaScript 函式 callbackHandler(),由頁面上的 JavaScript 把值填進收件者欄位。
- (BOOL)webView:(UIWebView *)aWebView
shouldStartLoadWithRequest:(NSURLRequest *)aRequest
navigationType:(UIWebViewNavigationType)navigationType {
if (webView.request == nil || [activityIndicatorView isAnimating]) {
return YES;
} else if ([aRequest.URL.scheme isEqualToString:@"testuishell"]) {
if ([aRequest.URL.path isEqualToString:@"/emailpicker"]) {
// 記下請求路徑與 JavaScript 回呼函式名稱
self.api = aRequest.URL.path;
self.callbackHandler = aRequest.URL.fragment;
ABPeoplePickerNavigationController *picker =
[[ABPeoplePickerNavigationController alloc] init];
picker.displayedProperties = [NSArray arrayWithObject:
[NSNumber numberWithInt:kABPersonEmailProperty]];
picker.peoplePickerDelegate = self;
[self presentModalViewController:picker animated:YES];
[picker release];
} else if (...) {
// 處理實體地址的選擇
}
} else if (...) {
// 攔截其他 URL 請求
} else {
// 攔截一般 URL 請求(見前一篇清單 7)
}
return NO;
}
- (void)peoplePickerNavigationControllerDidCancel:
(ABPeoplePickerNavigationController *)peoplePicker {
[self dismissModalViewControllerAnimated:YES];
}
- (BOOL)peoplePickerNavigationController:
(ABPeoplePickerNavigationController *)peoplePicker
shouldContinueAfterSelectingPerson:(ABRecordRef)person {
if ([api isEqualToString:@"/emailpicker"]) {
// 還沒選到郵件地址,繼續顯示通訊錄
return YES;
} else if (...) {
// 處理實體地址的選擇
}
return NO;
}
- (BOOL)peoplePickerNavigationController:
(ABPeoplePickerNavigationController *)peoplePicker
shouldContinueAfterSelectingPerson:(ABRecordRef)person
property:(ABPropertyID)property
identifier:(ABMultiValueIdentifier)identifier {
if ([api isEqualToString:@"/emailpicker"]) {
// 已選到郵件地址,從通訊錄取出該值
ABMultiValueRef emails = ABRecordCopyValue(person, property);
CFIndex index = ABMultiValueGetIndexForIdentifier(emails, identifier);
CFStringRef email = ABMultiValueCopyValueAtIndex(emails, index);
// 組出 JavaScript 回呼(函式名 + 引數)
NSString *callback = [NSString stringWithFormat:@"%@('%@')",
callbackHandler, email];
[webView stringByEvaluatingJavaScriptFromString:callback];
CFRelease(email);
CFRelease(emails);
[self dismissModalViewControllerAnimated:YES];
}
return NO;
}
相對地,JSP 端只需要一個觸發連結與一個回呼函式,並用 _iPhoneNativeApp 這個旗標限定只在混合 App 環境中顯示:
<c:if test="${_iPhoneNativeApp == true}">
<a class="button" href="testuishell:///emailpicker#emailPickerCallbackHandler">
Address Book
</a>
<script type="text/javascript">
function emailPickerCallbackHandler(email) {
document.getElementById("recipient").value = email;
}
</script>
</c:if>
同样的 URL 攔截技巧也能用來「用原生檢視取代 Web 內容」。Madisons Mobile 的店舖定位器原本提供一個連到 Google Maps 的地圖連結。在 Mobile Safari 中,這種請求會被導向系統的地圖應用程式——對嵌入的 Web 內容而言,這會導致跳出 App。為避免這種情況,我們攔下請求,改用 MKMapView 搭配自訂的 MapViewController 在應用程式內顯示地圖。
圖 13. 內嵌的地圖檢視

- (BOOL)webView:(UIWebView *)aWebView
shouldStartLoadWithRequest:(NSURLRequest *)aRequest
navigationType:(UIWebViewNavigationType)navigationType {
if (webView.request == nil || [activityIndicatorView isAnimating]) {
return YES;
} else if (...) {
// 攔截其他 URL 請求
} else if ([aRequest.URL.host isEqualToString:@"maps.google.com"]) {
// 從 query string 中取出 ll(經緯度)與 q(地址)
NSString *ll = nil;
NSString *q = nil;
NSString *query = aRequest.URL.query;
NSArray *parameters = [query componentsSeparatedByString:@"&"];
for (NSString *parameter in parameters) {
if ([parameter hasPrefix:@"ll="]) {
ll = [[[parameter substringFromIndex:3]
stringByReplacingOccurrencesOfString:@"+" withString:@" "]
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
if ([parameter hasPrefix:@"q="]) {
q = [[[parameter substringFromIndex:2]
stringByReplacingOccurrencesOfString:@"+" withString:@" "]
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
}
NSArray *latitudeAndLongitude = [ll componentsSeparatedByString:@","];
NSArray *addressAndName = [q componentsSeparatedByString:@" ("];
// 建立地圖檢視控制器與標記大頭針
MapViewController *mapViewController = [[MapViewController alloc]
initWithNibName:@"MapViewController" bundle:[NSBundle mainBundle]];
MyAnnotation *annotation = [[MyAnnotation alloc] init];
CLLocationCoordinate2D coordinate;
coordinate.latitude = [[latitudeAndLongitude objectAtIndex:0] doubleValue];
coordinate.longitude = [[latitudeAndLongitude objectAtIndex:1] doubleValue];
annotation.coordinate = coordinate;
annotation.title = [addressAndName objectAtIndex:1];
annotation.title = [annotation.title substringToIndex:
annotation.title.length - 1];
annotation.subtitle = [addressAndName objectAtIndex:0];
mapViewController.annotation = annotation;
[annotation release];
UINavigationController *nav = (UINavigationController *)
self.parentViewController;
if (nav == nil) {
nav = self.navigationController;
}
[nav pushViewController:mapViewController animated:YES];
[mapViewController release];
return NO;
} else if (...) {
// 攔截其他 URL 請求
} else {
// 攔截一般 URL 請求
}
return NO;
}
從 iPhone OS 3 起,Mobile Safari 與 UIWebView 都支援 HTML5 的地理定位 API。因此這裡不必寫任何原生程式碼,直接用 JavaScript 就能取得座標。
圖 14. 地理定位支援

function captureCurrentLocation() {
// 只接受 10 分鐘以內的位置資料。600000 毫秒 = 10 分鐘
navigator.geolocation.getCurrentPosition(showLocation, showError,
{enableHighAccuracy:true, maximumAge:600000});
}
function showLocation(position) {
var fromForm = document.getElementById("store_locator_gps_form");
var geoCodeLatitude = fromForm.geoCodeLatitude;
var geoCodeLongitude = fromForm.geoCodeLongitude;
geoCodeLatitude.value = position.coords.latitude;
geoCodeLongitude.value = position.coords.longitude;
fromForm.action = "mStoreLocatorResultView";
fromForm.submit();
}
同一套混合模型也適用於 iPad,技術完全一樣。雖然 iPhone App 可以在 iPad 上原樣執行,但更好的做法是提供專屬版本(例如「Madisons HD」),或讓同一支 App 同時支援兩者。要注意 iPad 有自己的人工介面指南,與 iPhone 差異不小——例如 iPad HIG 強調減少全螢幕轉場,改用分割畫面與彈出視窗。這時可以沿用前面的裝置偵測機制來區分來自 iPhone 與 iPad 的請求。
Android 是一個開放的軟體堆疊,由 Open Handset Alliance 主導並針對行動裝置最佳化。它以 Linux 核心為基礎,開發語言是 Java,瀏覽器採開源 WebKit 引擎,並在應用程式中提供嵌入的 Web 檢視——這一點與 iPhone 相同。
Android 應用程式通常由一或多個「活動」(Activity)組成,每個活動對應一個視窗或對話框;畫面配置可以由 Java 動態建立,也可以用 XML 靜態描述。架構上的關鍵概念包括:「意圖」(Intent,一種系統訊息,應用程式可註冊接收或主動發出)、「內容提供者」(Content Provider,用於存取裝置上的資料),以及「服務」(Service,通常在背景執行以監控或處理事件)。整個模型鼓勵應用程式、內容提供者與服務形成鬆散的聯盟,讓一個應用程式能輕易利用裝置上其他應用程式、內容與服務。
這裡的混合做法是用 Java 寫一個獨立應用程式,但使用者看到的大部分內容其實是 Web 檢視,由經過最小改造的 WebSphere Commerce 伺服器提供。在需要存取裝置特殊功能的場景(例如 GPS),伺服器提供的頁面裡會包含呼叫原生 Java 函式庫的 JavaScript 函式,由那些函式庫去取得並回傳資料。這意味著需要一或多個「橋梁函式庫」。如果這些 Android 專用函式庫被設計成與 iPhone 版本相同的 API 介面,那麼伺服器端程式碼幾乎不必修改就能同時服務兩個平台。
目前行動裝置上的畫面絕大部分由 WebView 掌管,而 WebView 本質上就是原生框架中嵌入的網頁。iPhone 上的多數注意事項同樣適用於 Android,因為兩者都是觸控操作:按鈕與連結必須夠大以便手指點選,文字必須夠大以便閱讀。這些多由 WebSphere Commerce 提供的頁面中嵌入的樣式表控制。
一個差異是螢幕尺寸。iPhone 目前只有兩種(iPhone/iPod Touch 與 iPad),Android 裝置的尺寸範圍則複雜得多,這會影響圖片尺寸、字級與按鈕大小的選擇。
應用程式選單是純 Web 應用程式難以整合的典型 Android 元素,多數裝置透過實體硬體鍵喚起,因此這部分只能交給原生框架。Android 預設最多顯示六個選單項,超出部分會收進一個標示為「More」的項目,點下去展開子選單。
圖 15. Madisons Android 應用程式-應用程式選單

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="https://schemas.android.com/apk/res/android">
<item android:id="@+id/locator" android:title="@string/StoreLocator"
android:icon="@drawable/ic_menu_compass" />
<item android:id="@+id/wishlist" android:title="@string/WishList"
android:icon="@drawable/ic_menu_save" />
<item android:id="@+id/cart" android:title="@string/ShoppingCart"
android:icon="@drawable/ic_menu_cart" />
<item android:id="@+id/home" android:title="@string/Home"
android:icon="@drawable/ic_menu_home" />
<item android:id="@+id/scan" android:title="@string/Scan"
android:icon="@drawable/ic_menu_scan" />
<item android:id="@+id/account" android:title="@string/MyAccount"
android:icon="@drawable/ic_menu_account" />
<item android:id="@+id/contact" android:title="@string/Contact" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication()).inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
String message = "No option selected";
if (item.getItemId() == R.id.home) {
mWebView.loadUrl(homePage);
return (true);
} else if (item.getItemId() == R.id.cart) {
mWebView.loadUrl(cartURL);
return true;
} else ... // 其他處理器從略
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
return (super.onOptionsItemSelected(item));
}
做法與 iPhone 版本相同。實際的 JavaScript 在 Android 案例中不同,但兩個原型之間的通訊錄介面保持一致,這樣 WebSphere Commerce 提供的頁面才能在兩邊通用。
條碼掃描是 Android 上一個很典型的應用程式協作設計。此例中「Scan」選單項呼叫 zxing(Zebra Crossing)的 IntentIntegrator,啟動 Barcode Scanner 應用程式、開啟相機、拍攝條碼(此處是二維 QR 碼)、在裝置上解碼,再把結果回傳。應用程式把結果解讀為一個產品頁面的 URL,載入 WebView 顯示。若使用者裝置未安裝 Barcode Scanner,這個做法還會詢問是否現在下載安裝。
import com.google.zxing.integration.android.IntentIntegrator;
// 條碼掃描
private void barcodeScan() {
IntentIntegrator.initiateScan(MyActivity.this);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case IntentIntegrator.REQUEST_CODE: {
if (resultCode == RESULT_OK) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(
requestCode, resultCode, data);
if (scanResult != null) {
String qrCode = scanResult.getContents();
// 處理回傳的字串
mWebView.loadUrl(qrCode);
}
}
break;
}
}
}
圖 16. QR 條碼與對應的產品頁面

與 iPhone 版本相同,讓使用者找到相對於目前位置的店舖是很實用的功能。Android 上的瀏覽器同樣基於開源 WebKit 引擎,目前版本也支援 HTML5 地理定位,因此一樣不需要原生程式碼。
隨著行動裝置、智慧型手機銷售與高速網路持續快速成長,行動商務對消費者的重要性只會越來越高。在這樣的環境下,能否為行動消費者提供良好體驗,將是零售商的關鍵競爭優勢。混合式應用程式模型提供了一條務實的路徑:重用既有 Web 資產、只在真正需要時才動用原生能力,讓同一套伺服器端程式碼服務多個平台。
Linux BFS 調度器解析:設計理念、效能爭議與實作原理
摘要:BFS 是一款專為 Linux 桌面環境設計的核心調度器,基於 Staircase Deadline 與 EEVDF 演算法,支援 Linux 2.6.31 之後的
Android 3.x 平板相容性設計:讓 1.5~2.3 的 App 跑在 Honeycomb 上
Android 3.x(Honeycomb)是為平板而生的一代,螢幕尺寸與解析度都遠高於早期手機,因此舊有應用要在平板上正確顯示,需要做一些資源與版面配置上的調整。以下說
Action Bar 使用方法 - Android 活動欄(一)
在 Android 3.0 中,除了我們重點講解的 Fragment 之外,Action Bar 同樣是一項重要內容。Action Bar 主要用來取代傳統的標題欄,對於
自訂 HorizontalScrollView 實作 QQ 風格側滑菜單
本篇要示範如何自訂一個 HorizontalScrollView,做出類似 QQ 那種可以左右滑動、拉出側邊選單的互動效果。 版面配置 主布局的結構是這樣的:最外層放一個