最近遇到一个需求,产品经理要求Android客户端点击“积分商城”调用H5页面的时候,Android和Js可以相互调用方法。这就涉及到HTML和Android之间的交互和通讯。作为Android实习生,虽然是第一次接触,且产品不像以前比赛项目那样,这次是面向消费者人群。于是乎,一顿猛操作…“度娘”[hhhhh~]。大概了解之后,一开始看的资料全是用内嵌的WebView。但是项目中用的是开源框架AgentWeb,且很多地方都涉及到调用相关方法。接着就开始了AgentWeb 的流浪之旅。buBBle~
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.widget.Toast;
import com.just.agentweb.AgentWeb;
import org.json.JSONObject;
//定义一个AndroidInterface类 方便调用、管理
public class AndroidInterface {
private AgentWeb agent;
private Context context;
public AndroidInterface(AgentWeb agent, Context context) {
this.agent = agent;
this.context = context;
}
private Handler deliver = new Handler(Looper.getMainLooper());
@JavascriptInterface
public void callAndroid(final String msg) {
deliver.post(new Runnable() {
@Override
public void run() {
Log.i("Info", "main Thread:" + Thread.currentThread());
Toast.makeText(context.getApplicationContext(), "" + msg, Toast.LENGTH_LONG).show();
}
});
Log.i("Info", "Thread:" + Thread.currentThread());
}
//这里是你要传的参数给Js
@JavascriptInterface
public String getJson(){
String result="";
try {
JSONObject mJSONObject=new JSONObject();
mJSONObject.put("phone_number", "12763912321");
mJSONObject.put("name", "小二");
mJSONObject.put("age","19");
result= mJSONObject.toString();
}catch (Exception e){
}
return result;
}
@JavascriptInterface
public void show(){
Log.i("Test","method");
}
}
import android.graphics.Bitmap;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.just.agentweb.AgentWeb;
import butterknife.BindView;
import butterknife.OnClick;
public class TMallActivity extends BaseActivity {
@BindView(R.id.webview)
LinearLayout mWebView;
private String message;
private String mLoadUrl;
@BindView(R.id.tv_webview_title)
TextView webTitle;
private String mTitle;
AgentWeb mAgentWeb;
@Override
protected int getContentViewId() {
return R.layout.activity_web;
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void initView() {
super.initView();
mLoadUrl = getIntent().getStringExtra("url");
mTitle = getIntent().getStringExtra("title");
//加载H5页面地址
mAgentWeb = AgentWeb.with(this)
.setAgentWebParent(mWebView, new LinearLayout.LayoutParams(-1, -1))
.useDefaultIndicator(getResources().getColor(R.color.colorPrimary))
.setWebViewClient(mWebViewClient)
.createAgentWeb()
.ready()
.go(mLoadUrl);
//初始化js交互对象
mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new AndroidInterface(mAgentWeb, this.getApplicationContext()));
mWebView = (LinearLayout) findViewById(R.id.webview);
mWebView.requestFocus();
webTitle.setText(mTitle);
KeyBoardListener.getInstance(this).init();
}
private WebViewClient mWebViewClient = new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//do you work
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
};
@OnClick(R.id.ll_back)
public void onViewClicked() {
finish();
}
@Override
protected void onPause() {
mAgentWeb.getWebLifeCycle().onPause();
super.onPause();
}
@Override
protected void onResume() {
mAgentWeb.getWebLifeCycle().onResume();
super.onResume();
}
}
//初始化js交互对象
mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new AndroidInterface(mAgentWeb, this.getApplicationContext()));
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="@dimen/dp_44"
android:background="@color/white"
android:orientation="horizontal"
>
<LinearLayout
android:id="@+id/ll_back"
android:layout_width="@dimen/dp_50"
android:focusable="true"
android:layout_height="match_parent">
<ImageView
android:padding="10dp"
android:layout_width="@dimen/dp_30"
android:layout_height="match_parent"
android:focusable="false"
android:layout_marginLeft="@dimen/dp_10"
android:src="@mipmap/ic_back"
android:layout_gravity="center_vertical"
/>
LinearLayout>
<TextView
android:gravity="center"
android:id="@+id/tv_webview_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="标题"
android:layout_gravity="center"
android:layout_marginRight="@dimen/dp_50"
android:textColor="@color/black"
android:maxLines="1"
android:ellipsize="end"
android:textSize="@dimen/dp_15"/>
LinearLayout>
<LinearLayout
android:orientation="vertical"
android:id="@+id/webview"
android:overScrollMode="never"
android:scrollbars="none"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
LinearLayout>
这样Android端的方法就定义好了。接下来是Js的工作了。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script>
window.android.callAndroid("北海有雨");
</script>
</head>
//省略。。。。
window.android.callAndroid("");
其中android是在初始化Js对象的时候约定好的,你也可以写成其他的,例如“jsandroid”…而callAndroid()是我们定义好的方法。同样,要传参数的话,你可以调用getJson()这个方法,传参,返回String类型。
这样,只要参数没传错的话,工作就完成了。
感谢查看!