最近在公司做web App項(xiàng)目宾抓,需要在webApp中打開原生App
如果本地有安裝原生App,那就直接去打開原生App對應(yīng)的頁面,如果本地沒有安裝原生App,那就直接去下載這個(gè)原生App.
先看網(wǎng)頁端的代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button onclick="doCheck()">測試設(shè)備Main2</button></br>
</body>
<script type="text/javascript">
function doCheck() {
var ua = navigator.userAgent;
//判斷瀏覽器的當(dāng)前設(shè)備,是iPhone,還是Android
if(ua.indexOf('iPhone') > 0) {
alert('iPhone設(shè)備');
} else if(ua.indexOf('Android') > 0) {
//alert('Android設(shè)備');
checkAndroid();
} else {
alert('暫不支持你所用的系統(tǒng)对雪,請使用Android或iOS系統(tǒng)')
}
}
//
function checkAndroid() {
//"banggu://是網(wǎng)頁與App約定的協(xié)議坏怪,這個(gè)是自由的不需要限制"
//com.example.liuzenglong.newapp.Main2Activity 這個(gè)是我準(zhǔn)備打開對應(yīng)App的一個(gè)類
//?id=10000&userId ='liuzenglong'&password='123456'" //提供傳遞的參數(shù)給App
window.location.href = "banggu://com.example.liuzenglong.newapp.Main2Activity/get/info?id=10000&userId ='liuzenglong'&password='123456'"; /***打開app的協(xié)議舱馅,有安卓同事提供***/
window.setTimeout(function() {//這里500ms打不開App就會去下載頁下載App
window.location.; /***打開app的下載頁***/
}, 500);
}
</script>
</html>
至此網(wǎng)頁端的工作已經(jīng)做完了硅确,現(xiàn)在可以看App端铛楣,由于本人是做Android開發(fā)近迁,這里只提供Android的實(shí)現(xiàn)方式.
Android需要做的事情
1.先在AndroidManifest的配置文件配置一下打開頁面的數(shù)據(jù)
<activity android:name=".OpenFromWebActivity">
<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="banggu" />//這個(gè)是我們對應(yīng)的協(xié)議,與網(wǎng)頁里面需要保持一致蛉艾,
</intent-filter>
</activity>
2. 在Activity里處理網(wǎng)頁傳遞來的數(shù)據(jù)**
/**
* 獲取Uri
*
* @return
*/
private String getUri() {
// 嘗試獲取WebApp頁面上過來的URL
Uri uri = getIntent().getData();
if (uri != null) {
StringBuffer sb = new StringBuffer();
// 完整的url信息
sb.append("url: " + uri.toString());
// scheme部分
sb.append("\nscheme: " + uri.getScheme());
// host部分 用來對應(yīng)對包名钳踊,
sb.append("\nhost: " + uri.getHost());
enterActivity(uri.getHost());
// 訪問路勁
sb.append("\npath: "); //用來對應(yīng)模塊,
List<String> pathSegments = uri.getPathSegments();
for (int i = 0; pathSegments != null && i < pathSegments.size(); i++) {
sb.append("/" + pathSegments.get(i));
}
// Query部分 //用來對應(yīng)模塊需要的參數(shù)
sb.append("\nquery: ?" + uri.getQuery());
return sb.toString();
}
return null;
}
/**
* 進(jìn)入對應(yīng)的Activity
* @param activityName
*/
private void enterActivity(String activityName) {
try {
Class currentClass = Class.forName(activityName);
Toast.makeText(this, "---"+currentClass.getName(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, currentClass);
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
這樣基本工作就已經(jīng)做完了勿侯,具體頁面拓瞪,具體操作。