本文是用的URL Scheme
實現的
h5頁面代碼:
<!DOCTYPE html>
<html>
<body>
<iframe src="share://jianshu.com/news/content?sourceSid=${article.sid}" style="display:none"/>
</body>
</html>
URI主要分三個部分:scheme、host、pathPrefix。
scheme="share"
host="jianshu.com"
pathPrefix="/news/content"
組成的鏈接
share://jianshu.com/news/content
用?key=value&key=value
方式進行傳遞數據
即sourceSid=${article.sid} 則是攜帶過來的數據
Android
可通過Activity的onCreate()方法來獲取攜帶的值
// app跳轉與h5跳轉,取sourceSid
String sourceSid = getIntent().getStringExtra(sourceSid);
if (TextUtils.isEmpty(sourceSid)) {
// 通過h5網頁調起app
Intent mgetvalue = getIntent();
String maction = mgetvalue.getAction();
if (Intent.ACTION_VIEW.equals(maction)) {
Uri uri = mgetvalue.getData();
if (uri != null) {
// 通過URL獲取value
sourceSid = uri.getQueryParameter("sourceSid");
}
}
} else {
// app內部跳轉過來
}
AndroidManifest設置濾器
<activity
android:name=".NewsActivity"
android:configChanges="orientation|keyboardHidden|screenSize|screenLayout"
android:launchMode="singleTask"
android:theme="@style/AppTheme.ShareStyle">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!--下面所設置的值需要和html端一致(不要出現大寫字母)-->
<!--在data里設置了 scheme和host,則該Activity可以接收和處理類似于 "share://jianshu.com/news/content"的鏈接-->
<data
android:host="jianshu.com"
android:pathPrefix="/news/content"
android:scheme="share" />
</intent-filter>
</activity>
當App未啟動時,點擊H5跳轉App時會出現白色頁面(是否是白色和設置的主題有關,Application-onCreate()...)然后再進入詳情頁面,會給人一種延遲卡頓感。
設置theme 在延遲的這段時間內展示歡迎圖片,可以設置為單獨的Activity也可以設置為全局
<style name="AppTheme.ShareStyle" parent="AppTheme.NoActionBar">
<item name="android:windowBackground">@mipmap/welcome</item>
</style>
后記:
一般都是用App分享鏈接到微信、QQ的。
而微信、QQ的瀏覽器屏蔽了iframe,所以不能點擊分享的鏈接直接打開App了。
H5可通過給button設置鏈接方式:
< a href="share://jianshu.com/news/content?sourceSid=${article.sid}">App內打開</ a>
然而微信屏蔽了URL Scheme,通過判斷是微信瀏覽器則顯示給用戶提示:讓其用瀏覽器的方式進行打開,然后再通過在瀏覽器跳轉App。