Android與H5交互
app開發(fā)過程中,利用原生+h5模式來開發(fā)是比較常見的
下面案例演示的是:原生調(diào)起一個(gè)H5頁面,然后H5點(diǎn)擊跳轉(zhuǎn)到原生
WebViewActivity頁面 調(diào)用H5 ,點(diǎn)擊H5鏈接 跳轉(zhuǎn)到原生MainActivity頁面
注意 別忘了 <!-- 添加網(wǎng)絡(luò)權(quán)限 -->
<uses-permission android:name="android.permission.INTERNET" />
一、清單文件,增加的配置
-
data的數(shù)據(jù)就是H5 A標(biāo)簽 href=“#”填寫的鏈接地址: android://h5/open
二、在你需要跳轉(zhuǎn)的頁面,清單文件中加入如下配置:
<activity android:name=".MainActivity" android:exported="true">
<!-- h5跳轉(zhuǎn)app -->
<!-- 需要添加下面的intent-filter配置 -->
<intent-filter>
<!-- 通過一個(gè)應(yīng)用來顯示數(shù)據(jù) -->
<action android:name="android.intent.action.VIEW" />
<!-- 默認(rèn)值,沒有該默認(rèn)值則無法響應(yīng)隱式意圖 -->
<category android:name="android.intent.category.DEFAULT" />
<!-- 該組件可以通過瀏覽器打開 -->
<category android:name="android.intent.category.BROWSABLE" />
<!-- android:scheme="android" 用來辨別啟動(dòng)的app -->
<!-- android:host="h5" 可以當(dāng)成是一個(gè)域名,這邊建議使用應(yīng)用的包名 -->
<!-- android:pathPrefix="/open" 參數(shù)路徑前綴 -->
<data
android:host="h5"
android:pathPrefix="/open"
android:scheme="android" /><!-- android://h5/open -->
</intent-filter>
</activity>
三、整體結(jié)構(gòu)布局如下 :

四、貼一下html里面的代碼吧
- ceshi.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>測(cè)試</title>
</head>
<body>
<a href="android://h5/open?type=5&id=2" style="font-size: 55px;">點(diǎn)擊事件1</a>
<br />
<br />
<a href="file:///android_asset/cs.html" style="font-size: 55px;">點(diǎn)擊事件2</a>
<br />
<br />
</body>
</html>
- cs.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>測(cè)試</title>
</head>
<body>
<br />
<a href="file:///android_asset/ceshi.html" style="font-size: 55px;" >點(diǎn)擊事件2</a>
<br />
</body>
</html>
五、具體實(shí)現(xiàn)如下:
- activity_web_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WebViewActivity">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
- WebViewActivity頁面的處理
調(diào)用的是本地H5(html)路徑
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewActivity extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
initwebView();//初始化webview
}
@SuppressLint("JavascriptInterface")
private void initwebView() {
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setDomStorageEnabled(true);
//設(shè)置WebView屬性,能夠執(zhí)行Javascript腳本
webSettings.setJavaScriptEnabled(true);
//設(shè)置可以訪問文件
webSettings.setAllowFileAccess(true);
//設(shè)置Web視圖
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//返回值是true的時(shí)候控制去WebView打開,為false調(diào)用系統(tǒng)瀏覽器或第三方瀏覽器
WebView.HitTestResult hit = view.getHitTestResult();
//hit.getExtra()為null或者h(yuǎn)it.getType() == 0都表示即將加載的URL會(huì)發(fā)生重定向,需要做攔截處理
if (TextUtils.isEmpty(hit.getExtra()) || hit.getType() == 0) {
//通過判斷開頭協(xié)議就可解決大部分重定向問題了,有另外的需求可以在此判斷下操作
Log.e("重定向", "重定向: " + hit.getType() + " && EXTRA()" + hit.getExtra() + "------");
Log.e("重定向", "GetURL: " + view.getUrl() + "\n" + "getOriginalUrl()" + view.getOriginalUrl());
Log.d("重定向", "URL: " + url);
}
if (url.startsWith("http://") || url.startsWith("https://")) { //加載的url是http/https協(xié)議地址
view.loadUrl(url);
return false; //返回false表示此url默認(rèn)由系統(tǒng)處理,url未加載完成,會(huì)繼續(xù)往下走
} else { //加載的url是自定義協(xié)議地址
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
if (intent.resolveActivity(WebViewActivity.this.getPackageManager())!=null){
startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
//開始加載網(wǎng)絡(luò)
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.e("加載中",url);
}
//網(wǎng)頁加載完成回調(diào)
@SuppressLint("NewApi")
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.e("加載完成",url);
}
});
// 調(diào)用本地H5頁面的方法
webView.loadUrl("file:///android_asset/ceshi.html");
}
}
以上是運(yùn)行跳轉(zhuǎn)成功,下面是拿到跳轉(zhuǎn)的參數(shù)
- MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
Log.d("test123",""+intent);
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action)) { //判斷是否是我們指定的 action
Uri uri = intent.getData(); //將String類型的URL轉(zhuǎn)變?yōu)閁RI
if (uri != null) {
String type = uri.getQueryParameter("type"); //獲取參數(shù)
String id = uri.getQueryParameter("id");
Log.d("uri", "" + uri);
Log.d("type", "" + type);
Log.d("id", "" + id);
}
}
}
}
- 跳轉(zhuǎn)第二個(gè)頁面后,獲取的參數(shù)打印如下:
Android webview調(diào)用JS方法
- Android寫一個(gè)觸發(fā)事件(button),調(diào)用AndroidJsCall();
resule是傳遞的參數(shù)
@SuppressLint("SetJavaScriptEnabled")
public void AndroidJsCall()
{
webView.loadUrl("javascript:toAndroidCall('"+resule+"')");
}
- h5(vue)中寫一個(gè)方法
- html如下:
function toAndroidCall(message){
console.log("Android中調(diào)用JS方法成功,做處理---------------"+message);
}
- vue如下:
mounted() {
//將要給原生調(diào)用的方法掛載到 window 上面
window.callJsFunction = this.callJsFunction
},
methods: {
callJsFunction(message) {
console.log("Android中調(diào)用JS方法成功,做處理---------------"+message);
}
}
JS中調(diào)用Android webview方法
- 1、webView進(jìn)行配置
//增加JS接口
webView.addJavascriptInterface(this,"ceshi");
- 2、Android中實(shí)現(xiàn)方法
//JS調(diào)用Android方法
@JavascriptInterface
public String jsCallAndroid(){
Toast.makeText(this,"JS調(diào)用Android方法成功",Toast.LENGTH_LONG).show();
return result;
}
如果要傳參數(shù)
//JS調(diào)用Android方法-帶參數(shù)
@JavascriptInterface
public String jsCallAndroid(int type){
Toast.makeText(this,"JS調(diào)用Android方法成功,type----"+type,Toast.LENGTH_LONG).show();
return result;
}
- 3、在JS中新增一個(gè)按鈕
<button id="button" onclick="toCallAndroid()">JS調(diào)用Android方法</button>
- 4、設(shè)置點(diǎn)擊事件
//JS中調(diào)用Android方法
function toCallAndroid()
{
ceshi.jsCallAndroid();
}
文章來源:http://www.zghlxwxcb.cn/news/detail-413060.html
安卓響應(yīng)前端選擇文件照片 input type=“file“
不響應(yīng):
H5 訪問本地文件的時(shí)候,使用的 ,WebView 出于安全性的考慮,限制了以上操作。解決實(shí)現(xiàn):
webview 中重寫方法響應(yīng) WebviewChromeClient 。文章來源地址http://www.zghlxwxcb.cn/news/detail-413060.html
- 4.1以上系統(tǒng),使用 openFileChooser() ,該方法5.0已經(jīng)被廢棄
- 5.0以上系統(tǒng),使用 onShowFileChooser()
private ValueCallback<Uri[]> uploadMessageAboveL;
private ValueCallback<Uri[]> uploadMessage;
//用于保存拍照?qǐng)D片的uri
private Uri mCameraUri;
private static final int CAMERA_REQUEST_CODE = 10010;//相機(jī)標(biāo)識(shí)符
private static final int ACTION_CHOOSE_IMAGE = 0x201;//相冊(cè)標(biāo)識(shí)符
webView.setWebChromeClient(new WebChromeClient(){
//Android >= 5.0
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
uploadMessageAboveL = filePathCallback;
//調(diào)用系統(tǒng)相機(jī)或者相冊(cè)
uploadPicture();
return true;
}
//For Android >= 4.1
public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture)
uploadMessage = filePathCallback;
//調(diào)用系統(tǒng)相機(jī)或者相冊(cè)
uploadPicture();
}
});
- 我這里是給個(gè)彈框選擇 拍照 還是 調(diào)用系統(tǒng)相冊(cè)
private static String[] items = new String[]{
"拍照",
"從相冊(cè)中選擇",
"取消",
};
private void uploadPicture() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("請(qǐng)選擇圖片");
builder.setItems(items, new DialogInterface.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
checkPermissionAndCamera();
} else if (which == 2) {
if (uploadMessageAboveL != null) {
uploadMessageAboveL.onReceiveValue(null);
uploadMessageAboveL = null;
}
if (uploadMessage != null) {
uploadMessage .onReceiveValue(null);
uploadMessage = null;
}
builder.create().dismiss();
} else {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, ACTION_CHOOSE_IMAGE);
}
return;
}
});//設(shè)置對(duì)話框 標(biāo)題
builder.create()
.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("TAG", "resultCode:==="+resultCode);
if (resultCode != RESULT_OK) {
//取消拍照或者圖片選擇時(shí),返回null,否則<input file> 再次點(diǎn)擊無效果就是沒有反應(yīng)
if (uploadMessageAboveL != null) {
uploadMessageAboveL.onReceiveValue(null);
uploadMessageAboveL = null;
}
if (uploadMessage != null) {
uploadMessage .onReceiveValue(null);
uploadMessage = null;
}
}
//相機(jī)返回
if (requestCode == CAMERA_REQUEST_CODE) {
if (uploadMessageAboveL != null) {
uploadMessageAboveL.onReceiveValue(new Uri[]{mCameraUri});
uploadMessageAboveL = null;
}
if (uploadMessage != null) {
uploadMessage.onReceiveValue(mCameraUri);
uploadMessage = null;
}
}
//相冊(cè)返回
if (requestCode == ACTION_CHOOSE_IMAGE) {
if (data == null || data.getData() == null) {
if (uploadMessageAboveL != null) {
uploadMessageAboveL.onReceiveValue(null);
uploadMessageAboveL = null;
}
if (uploadMessage != null) {
uploadMessage .onReceiveValue(null);
uploadMessage = null;
}
return;
}
if (uploadMessageAboveL != null) {
uploadMessageAboveL.onReceiveValue(new Uri[]{data.getData()});
uploadMessageAboveL = null;
}
if (uploadMessage!= null) {
uploadMessage.onReceiveValue(data.getData());
uploadMessage= null;
}
}
}
到了這里,關(guān)于Android與H5交互 -- 點(diǎn)擊H5跳轉(zhuǎn)到 Android原生 頁面 ,webview與h5(js)交互的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!