Android基于腾讯的x5WebView的浏览页面,长按保存图片
/**
* 响应长按点击事件
* @param
*/
private void setWebImageLongClickListener() {
WebView.HitTestResult result = mX5WebView.getHitTestResult();
if (result != null) {
int type = result.getType();
if (type == WebView.HitTestResult.IMAGE_TYPE || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
String longClickUrl = result.getExtra();
showDialog(longClickUrl);
}
}
}
/**
* 长按 WebView 图片弹出 Dialog
* @param url
*/
private void showDialog(final String url) {
new ActionSheetDialog(BaseWebViewActivity.this)
.builder()
.setCancelable(true)
.setCanceledOnTouchOutside(true)
.addSheetItem(
"保存到相册",
ActionSheetDialog.SheetItemColor.Blue,
new ActionSheetDialog.OnSheetItemClickListener() {
@Override
public void onClick(int which) {
String fileName = System.currentTimeMillis() + ".jpg";
savePicture(fileName,url);
}
}).show();
}
//Glide保存图片
public void savePicture(final String fileName, String url){
Glide.with(BaseWebViewActivity.this).load(url).asBitmap().toBytes().into(new SimpleTarget<byte[]>() {
@Override
public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
try {
savaFileToSD(fileName,bytes);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//往SD卡写入文件的方法
public void savaFileToSD(String filename, byte[] bytes) throws Exception {
//如果手机已插入sd卡,且app具有读写sd卡的权限
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String filePath = Environment.getExternalStorageDirectory().getCanonicalPath()+"/Test";
File dir1 = new File(filePath);
if (!dir1.exists()){
dir1.mkdirs();
}
String filename1 = filePath+ "/" + filename;
//这里就不要用openFileOutput了,那个是往手机内存中写数据的
FileOutputStream output = new FileOutputStream(filename1);
output.write(bytes);
//将bytes写入到输出流中
output.close();
//关闭输出流
Toast.makeText(BaseWebViewActivity.this, "图片已成功保存到"+filePath, Toast.LENGTH_SHORT).show();
// 其次把文件插入到系统图库
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(this.getContentResolver(),
filename1, filename, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 最后通知图库更新
this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(new File(filename1))));
} else Toast.makeText(BaseWebViewActivity.this, "SD卡不存在或者不可读写", Toast.LENGTH_SHORT).show();
}
网友评论