1.这个三方库用例也很多,使用方式也很简单,先看一下git网址
git传送门:https://github.com/lzyzsd/JsBridge
2.使用方式,直接依赖
compile 'com.github.lzyzsd:jsbridge:1.0.4'
3.直接在自己的webview中写吧,我先把代码放过来
private void initView() {
webView = (BridgeWebView) findViewById(R.id.webview);
back = (LinearLayout) findViewById(R.id.back);
title = (TextView) findViewById(R.id.title);
rightBtn_click = (RelativeLayout) findViewById(R.id.rightBtn_click);
rightBtn = (ImageView) findViewById(R.id.rightBtn);
rightBtn_click.setVisibility(View.VISIBLE);
rightBtn.setImageResource(R.mipmap.share);
//返回
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
WebViewActivity.this.setResult(RESULT_OK);
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
}
});
//分享
rightBtn_click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!TextUtils.isEmpty(shareurl)) {
//分享标题
sharename = title.getText().toString();
if (TextUtils.isEmpty(sharename)) {
sharename = getResources().getString(R.string.app_name);
}
ShareDialog shareDialog = new ShareDialog(WebViewActivity.this);
shareDialog.share(shareurl, sharename, sharesrc, sharedes, null, true);
shareDialog.show();
} else {
ToastUtils.showToast(WebViewActivity.this, getString(R.string.data_err));
}
}
});
progressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
}
private void initEvent() {
WebSettings websettings = webView.getSettings();
websettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
websettings.setLoadsImagesAutomatically(true);
websettings.setJavaScriptEnabled(true);
websettings.setUseWideViewPort(true);
websettings.setSupportZoom(true);
websettings.setSupportMultipleWindows(true);
websettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
websettings.setBuiltInZoomControls(true);
websettings.setSupportZoom(true);
websettings.setJavaScriptCanOpenWindowsAutomatically(true);
websettings.setAppCacheEnabled(true);
webView.setDefaultHandler(new DefaultHandler());
webView.setWebViewClient(new MyWebViewClient(webView));
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
progressBar.setVisibility(View.GONE);
} else {
if (progressBar.getVisibility() != View.VISIBLE) {
progressBar.setVisibility(View.VISIBLE);
}
progressBar.setProgress(newProgress);
}
super.onProgressChanged(view, newProgress);
}
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback uploadMsg, String AcceptType, String capture) {
this.openFileChooser(uploadMsg);
}
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback uploadMsg, String AcceptType) {
this.openFileChooser(uploadMsg);
}
public void openFileChooser(ValueCallback uploadMsg) {
mUploadMessage = uploadMsg;
initPermission();
}
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {
mUploadMessageArray = filePathCallback;
initPermission();
return true;
}
});
webView.loadUrl(url);
webView.registerHandler("save", new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
Log.e(TAG, "handler = ImagesFromWeb, data from web = " + data);
if (!TextUtils.isEmpty(data)) {
if (data.endsWith(".png") || data.endsWith(".jpg") || data.endsWith("jpeg")) {
DownLoadManager.downLoadImage(context, data);
} else {
ToastUtils.showToast(WebViewActivity.this, getResources().getString(R.string.okgofail));
}
}
function.onCallBack("ImagesFromWeb exe, response data 中文 from Java");
}
});
webView.registerHandler("goLogin", new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
Log.e(TAG, "handler = ImagesFromWeb, data from web = " + data);
if (!TextUtils.isEmpty(data)) {
CommonUtils.toLogin(WebViewActivity.this);
}
function.onCallBack("ImagesFromWeb exe, response data 中文 from Java");
}
});
webView.registerHandler("toBookDetail", new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
Log.e(TAG, "handler = ImagesFromWeb, data from web = " + data);
if (!TextUtils.isEmpty(data)) {
WebViewBean webViewBean = new Gson().fromJson(data, new TypeToken() {
}.getType());
if (!TextUtils.isEmpty(webViewBean.getBookId())) {
Intent intent = new Intent(WebViewActivity.this, BookDetailActivity.class);
intent.putExtra(SPUtils.K_BOOKID, webViewBean.getBookId());
intent.putExtra(SPUtils.K_TITLE, "");
startActivity(intent);
} else {
showToast(getResources().getString(R.string.okgofail));
}
}
function.onCallBack("ImagesFromWeb exe, response data 中文 from Java");
}
});
}
private class MyWebViewClient extends BridgeWebViewClient {
public MyWebViewClient(BridgeWebView webView) {
super(webView);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//获取HTML的title
String titles = view.getTitle();
if (!TextUtils.isEmpty(titles)) {
title.setText(titles);
sharename = titles;
}
if (TextUtils.isEmpty(sharedes)) {
sharedes = getResources().getString(R.string.app_name);
}
//加载结束后去掉加载框
dismissLoading();
if (!WebViewActivity.this.isDestroyed() || !WebViewActivity.this.isFinishing()) {
webView.callHandler("checkAPP", "android", new CallBackFunction() {
@Override
public void onCallBack(String data) {
Log.i(TAG, "回传结果:" + data);
}
});
}
}
}
/**
* Back键控制网页后退
*
* @param
* @param
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
WebViewActivity.this.setResult(RESULT_OK);
return super.onKeyDown(keyCode, event);
}
/**
* 在 Activity 销毁( WebView )的时候,先让 WebView 加载null内容,然后移除 WebView,再销毁 WebView,最后置空。
*
* @param
* @param
*/
@Override
protected void onDestroy() {
if (webView != null) {
webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
webView.clearHistory();
((ViewGroup) webView.getParent()).removeView(webView);
webView.destroy();
webView = null;
}
super.onDestroy();
}
private void initPermission() {
// 申请权限。
PermissionUtils.permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE).callBack(new PermissionUtils.PermissionCallBack() {
@Override
public void onGranted(PermissionUtils permissionUtils) {
PictureSelector.create(WebViewActivity.this)
.openGallery(PictureMimeType.ofImage())
.maxSelectNum(Integer.MAX_VALUE)// 最大图片选择数量 int
.isCamera(true)// 是否显示拍照按钮
.isZoomAnim(true)// 图片列表点击 缩放效果 默认true
// .enableCrop(true)// 是否裁剪
.compress(true)// 是否压缩
.synOrAsy(true)//同步true或异步false 压缩 默认同步
// .withAspectRatio(3, 2)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
.glideOverride(160, 160)// glide 加载宽高,越小图片列表越流畅,但会影响列表图片浏览的清晰度
.hideBottomControls(true)// 是否显示uCrop工具栏,默认不显示
.isGif(false)// 是否显示gif图片
// .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
// .circleDimmedLayer(true)// 是否圆形裁剪
// .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
// .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
// .selectionMedia(selectList)// 是否传入已选图片
.forResult(PictureConfig.CHOOSE_REQUEST);
}
@Override
public void onDenied(PermissionUtils permissionUtils) {
ToastTintUtils.error("请打开您的相机和存储权限");
}
}).request();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PictureConfig.CHOOSE_REQUEST:
// 图片选择结果回调
selectList = PictureSelector.obtainMultipleResult(data);
// 例如 LocalMedia 里面返回三种path
// 1.media.getPath(); 为原图path
// 2.media.getCutPath();为裁剪后path,需判断media.isCut();是否为true
// 3.media.getCompressPath();为压缩后path,需判断media.isCompressed();是否为true
// 如果裁剪并压缩了,已取压缩路径为准,因为是先裁剪后压缩的
List list = new ArrayList<>();
for (LocalMedia media : selectList) {
Log.i("图片-----》", media.getPath());
iconPath = media.getPath();
list.add(Uri.fromFile(new File(iconPath)));
}
if (list != null && list.size() > 0) {
if (mUploadMessageArray != null) {
// Uri[] uris = new Uri[]{Uri.fromFile(new File(iconPath))};
Uri[] uris = new Uri[list.size()];
for (int i = 0; i < list.size(); i++) {
uris[i] = list.get(i);
}
Logger.e("ttt" + uris.toString());
mUploadMessageArray.onReceiveValue(uris);
mUploadMessageArray = null;
} else if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(Uri.fromFile(new File(iconPath)));
mUploadMessage = null;
} else {
Toast.makeText(context, "获取图片失败,请稍后重试", Toast.LENGTH_LONG).show();
}
} else {
cancelFilePathCallback();
}
break;
}
}
/**
* 取消mFilePathCallback回调
*/
private void cancelFilePathCallback() {
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(null);
mUploadMessage = null;
} else if (mUploadMessageArray != null) {
mUploadMessageArray.onReceiveValue(null);
mUploadMessageArray = null;
}
}
4.这份代码是基本的生命webview在布局中要写的
这个代码有选择相册的功能,还有写的句柄,来回调用用的,先说访问相册,这个跟iOS没法比,我们要自己写调起相册的功能,使用的是一个三方库,选择照片后回调,这里说一下,避免选择后不能再次选择问题,所以有了一个取消mFilePathCallback回调
其次句柄:
HTML调用我的方法,首先我注册一个方法,等他触发
webView.registerHandler("save", new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
Log.e(TAG, "handler = ImagesFromWeb, data from web = " + data);
if (!TextUtils.isEmpty(data)) {
if (data.endsWith(".png") || data.endsWith(".jpg") || data.endsWith("jpeg")) {
DownLoadManager.downLoadImage(context, data);
} else {
ToastUtils.showToast(WebViewActivity.this, getResources().getString(R.string.okgofail));
}
}
function.onCallBack("ImagesFromWeb exe, response data 中文 from Java");
}
});
然后是HTML注册方法,APP调用
webView.callHandler("checkAPP", "android", new CallBackFunction() {
@Override
public void onCallBack(String data) {
Log.i(TAG, "回传结果:" + data);
}
});
基本用法就这样,记得访问相册的时候判断一下权限