在做行動應用的單點登入時,常需要在瀏覽器裡點擊一個連結來啟動 APP,並把參數傳到 APP 內的介面處理。以下把 Android 與 iOS 的實作方式整理出來,方便日後查閱。
1)修改 AndroidManifest.xml,在需要被打開的 activity 下加入 intent-filter:
2)在 HTML 中加入 ssotest 連結,點擊即可打開 APP。
3)其它 APP 也可透過以下方式打開它:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("ssotest://")));4)若要傳遞參數,直接在 URL 後追加即可,例如:ssotest://?key=value。
5)在接收的 Activity 中解析參數:
this.getIntent().getScheme(); // 獲得 Scheme 名稱 this.getIntent().getDataString(); // 獲得完整 Uri,自行解析字串即可
1)修改 plist 檔,註冊對外的 URL Scheme:
A. 找到工程的 info.plist;B. 點擊 Information Property List 後面的加號,選擇 URL types;C. 展開 URL types,再展開 Item 0,把 URL identifier 修改為 URL Scheme;D. 展開 URL Scheme,把 Item 0 的內容改為 ssotest(可自行定義)。
2)同樣在 HTML 中加入 ssotest 連結,點擊即可打開 APP。
3)若要在啟動的 APP 中接收此 URL 並做特殊處理,可修改 AppDelegate.m,重寫 openURL 方法:
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
// 可透過 [url scheme] 獲得定義的 Scheme 名稱
// 可透過 [url absoluteString] 獲得完整 URL,藉此解析傳入的資料
return YES;
}透過自定义 URL Scheme,瀏覽器與原生應用之間就打通了一條通道,是實作單點登入、頁面跳轉與參數傳遞的常用手法。