android webview中js交互、第三方分享
程序员文章站
2022-03-14 08:23:48
由于要用到js与android交互,先写一下交互的心得:
效果图如下:
1.android调用js中的callJS()方法。
方法一:mWebView.lo...
由于要用到js与android交互,先写一下交互的心得:
效果图如下:
1.android调用js中的callJS()方法。
方法一:mWebView.loadUrl("javascript:callJS()");//效率低
方法二:mWebView.evaluateJavascript("javascript:callJS()", new ValueCallback() { @Override public void onReceiveValue(String value) { //此处为 js 返回的结果 } });//效率高,仅4.4以上可用。
2.js调用android中的方法。
1. 通过WebView的addJavascriptInterface()进行对象映射 2. 通过 WebViewClient 的shouldOverrideUrlLoading ()方法回调拦截 url 3. 通过 WebChromeClient 的onJsAlert()、onJsConfirm()、onJsPrompt()方法回调拦截JS对话框alert()、confirm()、prompt() 消息
3.调用android中的方法。我采用的是第一种方法:addJavascriptInterface()
定义JSJavaSprict对象,传递JsInterface(接口中将以后要回调的方法定义好,用的时候实现对应的方法)
(回调就是把方法的定义和功能导入实现分开的一种机制,目的是为了解耦他的本质是基于观察者设计模式,即观察者设计模式的的简化版)
// 通过addJavascriptInterface()将Java对象映射到JS对象 //参数1:Javascript对象名 //参数2:Java对象名
mWebView.addJavascriptInterface(new JSJavaSprict(new JsInterface() {
@Override public void starShare(final String shareUrl, final String title, final String thumb, final String disgest) { ShareDialog shareDialog = new ShareDialog(PolicyDetailsActivity.this, new ShareDialog.ShareClickListen() { @Override public void WXFriend() { runOnUiThread(new Runnable() { @Override public void run() { shareWeixin(0, shareUrl, title, disgest); } }); } @Override public void WXContacts() { runOnUiThread(new Runnable() { @Override public void run() { shareWeixin(1, shareUrl, title, disgest); } }); } @Override public void QQQzone() { runOnUiThread(new Runnable() { @Override public void run() { shareToQzone(title, disgest, thumb, shareUrl); } }); } @Override public void QQContacts() { runOnUiThread(new Runnable() { @Override public void run() { sendQQ(title, disgest, shareUrl, thumb); } }); } @Override public void WB() { runOnUiThread(new Runnable() { @Override public void run() { sendMultiMessage(title, shareUrl, disgest); } }); } @Override public void copy() { //复制链接 ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); // 将文本内容放到系统剪贴板里。 cm.setText(shareUrl); ToastUtils.showShortToast("复制成功!"); } }); shareDialog.show(); } @Override public void setTitle(String title) { } @Override public void toActivity() { } @Override public void finish() { // PolicyDetailsActivity.this.finish(); } @Override public void download(String url) { if (SDCardUtils.isSDCardEnable()) { String[] split = url.split("/"); //文件名字 String fileName = split[split.length - 1]; RequestParams entity = new RequestParams(url); // 设置断点续传 entity.setAutoResume(true); entity.setSaveFilePath(Contasts.DIR_FILE + "/" + fileName); x.http().get( entity, new Callback.ProgressCallback() { @Override public void onSuccess(File result) { ToastUtils.showShortToast("下载成功"); loadingProgress.dismissDialog(); try { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(result), getMIMEType(result)); startActivity(intent); } catch (Exception e) { ToastUtils.showShortToast("请安装相关插件"); } } @Override public void onError(Throwable ex, boolean isOnCallback) { } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } @Override public void onWaiting() { loadingProgress = new LoadingProgress(PolicyDetailsActivity.this); loadingProgress.showDialog("正在下载中..."); } @Override public void onStarted() { } @Override public void onLoading(long total, long current, boolean isDownloading) { } }); } else { ToastUtils.showShortToast("SD卡不可用"); } } }), "android");4、JSJavaSprict和JsInterface写法
import android.webkit.JavascriptInterface; public class JSJavaSprict { private JsInterface jsInterface; public JSJavaSprict(JsInterface jsInterface) { this.jsInterface = jsInterface; } //windows.android.startShare('1223') // 被JS调用的方法必须加入@JavascriptInterface注解 @JavascriptInterface public void startShare(String shareUrl, String title, String thumb, String disgest) { jsInterface.starShare(shareUrl, title, thumb, disgest); } //windows.android.setTitle('1223') @JavascriptInterface public void setTitle(String msg) { jsInterface.setTitle(msg); } @JavascriptInterface public void startSign(String type) { // LogUtils.d(type); if ("2".equals(type)) { jsInterface.toActivity(); } else { jsInterface.finish(); } } /** * 下载文件 * * @param url */ @JavascriptInterface public void startdownload(String url) { jsInterface.download(url); } }
public interface JsInterface { /** * 地址 标题 缩略图 摘要 * * @param shareUrl * @param title * @param thumb * @param disgest */ void starShare(String shareUrl, String title, String thumb, String disgest); void setTitle(String title); void toActivity(); void finish(); void download(String url); }
弹出分享框。
public class ShareDialog extends Dialog { private GridView gvItem; private TextView tvCancel; private Context mContext; private List mlist; private ShareClickListen shareClickListen; public ShareDialog(@NonNull Context context, ShareClickListen shareClickListen) { super(context); this.mContext = context; this.shareClickListen = shareClickListen; mlist = new ArrayList<>(); for (int i = 0; i < 6; i++) { mlist.add(i); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setBackgroundDrawableResource(R.drawable.loc_background); getWindow().setWindowAnimations(R.style.dialogstyle); getWindow().getDecorView().setPadding(0, 0, 0, 0); WindowManager.LayoutParams params = getWindow().getAttributes(); params.width = WindowManager.LayoutParams.FILL_PARENT; params.height = WindowManager.LayoutParams.WRAP_CONTENT; getWindow().setAttributes(params); getWindow().setGravity(Gravity.BOTTOM); setContentView(R.layout.dialog_share); gvItem = findViewById(R.id.gv_item); tvCancel = findViewById(R.id.tv_cancel); gvItem.setAdapter(new CommonAdapter(mContext, mlist, R.layout.item_dialog_share) { @Override public void convert(ViewHolder helper, Integer item) { ImageView ivIcon = helper.getView(R.id.iv_icon); TextView tvIcon = helper.getView(R.id.tv_icon); switch (item) { case 0: ivIcon.setImageResource(R.drawable.btn_friends); tvIcon.setText("朋友圈"); break; case 1: ivIcon.setImageResource(R.drawable.btn_wx); tvIcon.setText("微信好友"); break; case 2: ivIcon.setImageResource(R.drawable.btn_space); tvIcon.setText("QQ空间"); break; case 3: ivIcon.setImageResource(R.drawable.btn_qq); tvIcon.setText("QQ好友"); break; case 4: ivIcon.setImageResource(R.drawable.btn_wb); tvIcon.setText("微博"); break; case 5: ivIcon.setImageResource(R.drawable.btn_link); tvIcon.setText("复制链接"); break; } } }); gvItem.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { switch (position) { case 0: shareClickListen.WXFriend(); break; case 1: shareClickListen.WXContacts(); break; case 2: shareClickListen.QQQzone(); break; case 3: shareClickListen.QQContacts(); break; case 4: shareClickListen.WB(); break; case 5: shareClickListen.copy(); break; } // sendMultiMessage(); } }); tvCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); } public interface ShareClickListen { void WXFriend(); void WXContacts(); void QQQzone(); void QQContacts(); void WB(); void copy(); } }
4.当我们点击js中分享按钮时,调用startShare()方法。
点击下载时,调用download()方法。
5.第三方分享。
初始化微博、腾讯、微信方法。将平台申请的key值替换。
AuthInfo mAuthInfo = new AuthInfo(this, Contasts.APP_KEY, Contasts.REDIRECT_URL, Contasts.SCOPE);//微博 WbSdk.install(this, mAuthInfo);
WbShareHandler wbShareHandler = new WbShareHandler((Activity) this);wbShareHandler.registerApp(); wbShareHandler.setProgressColor(0xff33b5e5);
IWXAPI iwxapi = WXAPIFactory.createWXAPI(this, Contasts.WX_APP_KEY, true);//微信 iwxapi.registerApp(Contasts.WX_APP_KEY); // Tencent类是SDK的主要实现类,开发者可通过Tencent类访问腾讯开放的OpenAPI。 // 其中APP_ID是分配给第三方应用的appid,类型为String。
Tencent mTencent = Tencent.createInstance(Contasts.QQ_APP_ID, this.getApplicationContext());//腾讯StatConfig.setDebugEnable(true);
①微信分享
public void shareWeixin(int type, String shareUrl, String title, String disgest) { WXWebpageObject wxWebpageObject = new WXWebpageObject(); wxWebpageObject.webpageUrl = shareUrl; WXMediaMessage msg = new WXMediaMessage(); msg.title = title; msg.description = disgest; msg.mediaObject = wxWebpageObject; // Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_touxiang); // Bitmap thumbBmp = Bitmap.createScaledBitmap(thumb, THUMB_SIZE, THUMB_SIZE, true); // thumb.recycle(); // msg.thumbData = Utils.bmpToByteArray(thumb, true); SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = "windomZZ"; req.message = msg; if (type == 0) { req.scene = SendMessageToWX.Req.WXSceneTimeline; } else { req.scene = SendMessageToWX.Req.WXSceneSession; } iwxapi.sendReq(req); }
②微博分享
/** * 第三方应用发送请求消息到微博,唤起微博分享界面。 * * @param title * @param shareUrl * @param disgest */ private void sendMultiMessage(String title, String shareUrl, String disgest) { WeiboMultiMessage weiboMessage = new WeiboMultiMessage(); WebpageObject mediaObject = new WebpageObject(); mediaObject.identify = Utility.generateGUID(); mediaObject.title = title; mediaObject.description = disgest; Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); // 设置 Bitmap 类型的图片到视频对象里 设置缩略图。 注意:最终压缩过的缩略图大小不得超过 32kb。 mediaObject.setThumbImage(bitmap); mediaObject.actionUrl = shareUrl; mediaObject.defaultText = title; weiboMessage.mediaObject = mediaObject; wbShareHandler.shareMessage(weiboMessage, false); }
在分享的界面实现WbShareCallback
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); wbShareHandler.doResultIntent(intent, this); } @Override public void onWbShareSuccess() { ToastUtils.showShortToast("分享成功"); } @Override public void onWbShareCancel() { ToastUtils.showShortToast("分享取消"); } @Override public void onWbShareFail() { }
③QQ好友及QQ空间分享
private void sendQQ(String title, String digest, String shareUrl, String thumb) { final Bundle params = new Bundle(); params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT); params.putString(QQShare.SHARE_TO_QQ_TITLE, title); params.putString(QQShare.SHARE_TO_QQ_SUMMARY, digest); params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareUrl); params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, thumb); params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "智汇郑州"); // params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, 1); mTencent.shareToQQ(PolicyDetailsActivity.this, params, this); } private void shareToQzone(String title, String digest, String thumb, String shareUrl) { //分享类型 final Bundle params = new Bundle(); params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT); params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);//必填 params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, thumb);//选填 params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, shareUrl);//必填 ArrayList mlist = new ArrayList<>(); mlist.add(thumb); params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, mlist); mTencent.shareToQzone(PolicyDetailsActivity.this, params, this); }
当前activity实现IUiListener接口
@Override public void onComplete(Object o) { ToastUtils.showShortToast("分享成功"); } @Override public void onError(UiError uiError) { switch (uiError.errorCode) { } } @Override public void onCancel() { ToastUtils.showShortToast("分享取消"); } //分享回调 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Tencent.handleResultData(data, this); }
上一篇: 计算机网络(30)——无线局域网