編輯2014分之5,因爲這似乎是一個流行的問題,我已經添加了很多細節答案:
安卓:
對於Android,請參閱Intent Filter to Launch My Activity when custom URI is clicked。
您可以使用一個意圖過濾器:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" />
</intent-filter>
,這是附加到你想要啓動的活動。例如:
<activity android:name="com.MyCompany.MyApp.MainActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" android:host="com.MyCompany.MyApp" />
</intent-filter>
</activity>
然後,在您的活動中,如果沒有運行,活動將通過Intent中傳遞的URI啓動。
Intent intent = getIntent();
Uri openUri = intent.getData();
如果已經運行,onNewIntent()將在您的活動中再次與意圖中的URI一起被調用。
最後,如果你不是想處理的自定義協議的UIWebView的本機應用中託管,您可以使用:
myWebView.setWebViewClient(new WebViewClient()
{
public Boolean shouldOverrideUrlLoading(WebView view, String url)
{
// inspect the url for your protocol
}
});
的iOS:
對於iOS,請參閱Lauching App with URL (via UIApplicationDelegate's handleOpenURL) working under iOS 4, but not under iOS 3.2。
通過信息定義您的URL方案。plist中鍵類似於:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.yourcompany.myapp</string>
</dict>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>myapp</string>
</array>
</dict>
</array>
然後定義一個處理函數被調用的應用程序委託
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
// parse and validate the URL
}
如果你想處理在UIWebViews中自定義協議的本機應用程序中託管,你可以使用UIWebViewDelegate方法:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *urlPath = [request URL];
if (navigationType == UIWebViewNavigationTypeLinkClicked)
{
// inspect the [URL scheme], validate
if ([[urlPath scheme] hasPrefix:@"myapp"])
{
...
}
}
}
}
對於WKWebView程序(iOS 8 +),你可以改用WKNavigationDelegate這種方法:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
NSURL *urlPath = navigationAction.request.URL;
if (navigationAction.navigationType == WKNavigationTypeLinkActivated)
{
// inspect the [URL scheme], validate
if ([[urlPath scheme] hasPrefix:@"myapp"])
{
// ... handle the request
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
}
//Pass back to the decision handler
decisionHandler(WKNavigationActionPolicyAllow);
}
接受的答案應該能夠解決整個問題。你的回答沒有提到Android。這個問題有一個粗體的「和」。 – ToothlessRebel 2013-01-13 19:24:30
這個問題真的應該分成兩個問題 - 沒有任何一種方法可以在兩個平臺上處理自定義URI。 – 2014-01-30 06:22:24