Step1:webview添加长按点击事件,获取到图片的url
webView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
final WebView.HitTestResult hitTestResult = webView.getHitTestResult();
if (hitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
hitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("提示");
builder.setMessage("保存图片到本地");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
picUrl = hitTestResult.getExtra();
new Thread(new Runnable() {
@Override
public void run() {
url2bitmap(picUrl);
}
}).start();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
return true;
}
return false;
}
});
Step2:把url转换为bitmap对象(要在子线程操作)
public void url2bitmap(String url) {
Bitmap bm = null;
try {
URL iconUrl = new URL(url);
URLConnection conn = iconUrl.openConnection();
HttpURLConnection http = (HttpURLConnection) conn;
int length = http.getContentLength();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, length);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
if (bm != null) {
save2Album(bm);
}
} catch (Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
}
});
e.printStackTrace();
}
}
Step3:保存照片到相册,并通知系统更新相册
private void save2Album(Bitmap bitmap) {
File appDir = new File(Environment.getExternalStorageDirectory(), "相册名称");
if (!appDir.exists()) appDir.mkdir();
String[] str = picUrl.split("/");
String fileName = str[str.length - 1];
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
onSaveSuccess(file);
} catch (IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
}
});
e.printStackTrace();
}
}
private void onSaveSuccess(final File file) {
runOnUiThread(new Runnable() {
@Override
public void run() {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
}
});
}
PS:webview的单击事件的监听默认是不会响应的,如果响应的话,h5的点击就没用了。