標籤:
先說實現步驟再說原理:
使用步驟
一,首先要給你要開啟的應用中的activity設定過濾器(在資訊清單檔裡設定)
以JumpActivity為例
如下面的: <intent-filter> 中就是所需過濾器
<activity android:name=".JumpActivity" > <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可以接收和處理類似於 "sharetest://data/XXX"的連結--> <data android:host="data" android:scheme="sharetest" /> </intent-filter> </activity>
二,在JumpActivity中做開啟後的處理,用來接收外部的跳轉
public class JumpActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); Intent intent = getIntent();//在這個Activity裡,我們可以通過getIntent(),來擷取外部跳轉傳過來的資訊。 String data = intent.getDataString();//接收到網頁傳過來的資料:sharetest://data/http://www.huxiu.com/ String[] split = data.split("data/");//以data/切割data字串 url = split[1]; //就得到:http://www.huxiu.com/(這就是我們需要網頁傳給我們的資料)。。。然後我們再通過網頁開啟app的同時就可以用獲得的url資料做一些我們需要做的處理比如你在裡瀏覽網頁時開啟自己的安卓app應用的同時,載入一個app內的網頁 } }
三,我們需要找到html前端,讓他們在網頁中加入:
<iframe src="" style="display:none"></iframe>
如下:index.html
<!DOCTYPE html> <html> <body> <iframe src="sharetest://data/http://www.huxiu.com/" style="display:none"></iframe> </body> </html>
將index.html放到Assets目錄下,在代碼裡調用Webview載入該Html檔案,代碼如下:
/*網頁開啟app*/
public class H5ToAppActivity extends Activity { private String url; private WebView webview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_h5_app); webview = (WebView) findViewById(R.id.webviewh5); url = "file:///android_asset/index.html"; WebSettings wSet = webview.getSettings(); wSet.setJavaScriptEnabled(true); webview.loadUrl(url); }}
這樣執行以上代碼時就可以開啟對應的app了。
比如我的2048是一個網頁,開啟網頁的時候可以同時開啟另外一個應用
下面是兩個應用你可以下載下來看下效果:(兩個應用一起下)
2048網頁示範apk:http://download.csdn.net/detail/qiushi_1990/9514778
網頁開啟的應用apk:http://download.csdn.net/detail/qiushi_1990/9514779
這樣在開啟2048時會出現下面效果
然後會跳轉到下面應用
實現原理
最近,在使用QQ和等SDK來實現分享網頁的時候,發現,SDK已經為頁面跳回應用提供了基本的資料支援。我們只需在應用裡和被分享的網頁進行簡單的設定,即可實現此功能。
那麼我們先來看下網頁跳回應用的實現原理。
就Android平台而言,URI主要分三個部分:scheme, authority and path。其中authority又分為host和port。格式如下:
scheme://host:port/path
舉個實際的例子:
content://com.example.project:200/folder/subfolder/etc
\---------/ \---------------------------/ \---/ \--------------------------/
scheme host port path
\--------------------------------/
authority
現在大家應該知道data flag中那些屬性的含義了吧,看下data flag
<data android:host="string"
android:mimeType="string"
android:path="string"
android:pathPattern="string"
android:pathPrefix="string"
android:port="string"
android:scheme="string" />
點擊和QQ分享跳轉到程式內部的原理與此一致。
Android 從網頁中跳轉到APP