原生與H5互動介紹
阿新 • • 發佈:2019-02-02
步驟如下:
1、允許webView載入JS
2、編寫js介面類
3、webView新增js介面
程式碼如下:
佈局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <WebView android:id="@+id/web_view" android:layout_width="match_parent" android:layout_height="300dp"/> <TextView android:id="@+id/tv_reload" android:layout_marginTop="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#fbd22430" android:textSize="20sp" android:text="測試"/> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/edit_text" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="傳送至H5"/> <Button android:id="@+id/btn_send3" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="呼叫H5有參方法"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimaryDark"> <Button android:id="@+id/btn_send2" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="呼叫H5無參方法"/> <Button android:id="@+id/btn_send4" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="5加5,返回到安卓"/> </LinearLayout> </LinearLayout>
Main
package com.example.leixiansheng.webviewh5; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.webkit.ValueCallback; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private WebView mWebView; private TextView mTvReload; private EditText mEditText; private Button mButton; private Button mButton2; private Button mButton3; private Button mButton4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EventBus.getDefault().register(this); initWidgets(); //初始化 initEvent(); } private void initEvent() { /** * 安卓端向H5傳送資料 *WebView.loadUrl("javascript:xxxxx") */ mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String str = mEditText.getText().toString(); //如果H5 remote()方法存在,呼叫H5 remote()方法 mWebView.loadUrl("javascript:if(window.remote){window.remote('" + str + "')}"); //呼叫H5有參無返回方法,沒有進行方法是否存在的判斷 // mWebView.loadUrl("javascript:remote(\"" + str + "\")"); //用\" ....\" 轉義傳送字元 // mWebView.loadUrl("javascript:remote('哈哈')"); //用‘str’ 傳送字元 } }); mButton3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String str = mEditText.getText().toString(); // 如果H5 remote()方法存在,呼叫H5 remote()方法 mWebView.loadUrl("javascript:if(window.remote){window.remote('" + str + "')}"); //呼叫H5有參無返回方法,沒有進行方法是否存在的判斷 // mWebView.loadUrl("javascript:remote(\"" + str + "\")"); //用\" ....\" 轉義傳送字元 // mWebView.loadUrl("javascript:remote('哈哈')"); //用‘str’ 傳送字元 } }); mButton2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //呼叫H5無參無返回方法 mWebView.loadUrl("javascript:show()"); } }); mButton4.setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onClick(final View v) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //Android呼叫有返回值js方法,安卓4.4以上才能用這個方法 mWebView.evaluateJavascript("sum(5,5)", new ValueCallback<String>() { @Override public void onReceiveValue(String value) { Log.i(TAG, "js返回資料" + value); mTvReload.setText(value); } }); } else { //安卓4.4以下用這個方法 mWebView.loadUrl("javascript:sumBefore(10,10)"); } } }); } private void initWidgets() { mWebView = findViewById(R.id.web_view); mTvReload = findViewById(R.id.tv_reload); mEditText = findViewById(R.id.edit_text); mButton = findViewById(R.id.btn_send); mButton2 = findViewById(R.id.btn_send2); mButton3 = findViewById(R.id.btn_send3); mButton4 = findViewById(R.id.btn_send4); //設定WebView屬性,能夠執行Javascript介面 mWebView.getSettings().setJavaScriptEnabled(true); //給webView新增Javascript介面 mWebView.addJavascriptInterface(new ActivityJsInterface(),"webTest"); //其他 // WebView 載入assets目錄下的html檔案,一般是載入H5給的url mWebView.loadUrl("file:///android_asset/test.html"); } /** * H5 呼叫 安卓端:H5向安卓傳遞資料,然後安卓端更新資料 * @param event */ @Subscribe public void onEvent(final TestEvent event) { runOnUiThread(new Runnable() { @Override public void run() { mTvReload.setText(event.str); } }); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } }
JsBridge
package com.example.leixiansheng.webviewh5; import android.util.Log; import android.webkit.JavascriptInterface; import org.greenrobot.eventbus.EventBus; /** * Created by Leixiansheng on 2018/5/14. */ public class ActivityJsInterface { private static final String TAG = "ActivityJsInterface"; /** * 這裡所有方法不在主執行緒執行 * @param str */ @JavascriptInterface public void setValue(String str) { EventBus.getDefault().post(new TestEvent(str)); } }
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebView</title>
<style type="text/css">
body{
background: #cbcc1a
}
</style>
</head>
<body>
<h2>WebView</h2>
<div class="o">
<span>請輸入:</span>
<input type="text" placeholder="輸入文字" id="textVal">
<button id="onClickbtn" onclick="clickFun()">點擊發送</button>
</div>
<style>
</style>
<script type="text/javascript">
function clickFun() {
var value =document.getElementById('textVal').value
window.webTest.setValue(value)
}
function remote(str) {
document.getElementById('textVal').value=str;
}
function show() {
document.getElementById('textVal').value="hello world";
}
function sum(a, b) {
return a + b;
}
function sumBefore(m,n){
var value = m+n;
window.webTest.setValue(value);
}
</script>
</body>
</html>
/**
* 登陸成功返回資料到H5
*/
private void loginCallback(Platform platform) {
if (platform != null) {
try {
final JSONObject jsonObject = new JSONObject();
jsonObject.put("openid", platform.getDb().getUserId());
jsonObject.put("nickname", platform.getDb().getUserName());
jsonObject.put("headimgurl", platform.getDb().getUserIcon());
jsonObject.put("sex", platform.getDb().getUserGender());
Log.d("MainActivity", jsonObject.toString());
runOnUiThread(new Runnable() {
@Override
public void run() {
mWebView.loadUrl("javascript:App_ThrLoginCallback(" + jsonObject + ")");
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}