1. 长按事件
public boolean onLongClick(View v) {
final HitTestResult htr = webview.getHitTestResult();
if (htr.getType() == WebView.HitTestResult.IMAGE_TYPE) {
new AlertDialog.Builder(this)
.setTitle(htr.getExtra())
.setItems(R.array.image_long_click_event,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
if (which == 0) {
// view image
webview.loadUrl(htr.getExtra());
} else if (which == 1) {
// save image
downloadImage(htr.getExtra());
} else if (which == 2) {
// set wallpaper
setWallpaper(htr.getExtra());
}
}
}).show();
}
return false;
}
其中
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="image_long_click_event">
<item>View Image</item>
<item> Save Image</item>
<item>Save as Wallpaper</item>
</string-array>
</resources>
protected void downloadImage(String extra) {
DownloadManager downloadManager = ((DownloadManager) getSystemService(Activity.DOWNLOAD_SERVICE));
Request request = new Request(Uri.parse(extra));
request.setShowRunningNotification(true);
request.setVisibleInDownloadsUi(true);
request.setDescription(extra);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "allenSample.png");
downloadManager.enqueue(request);
}
protected void setWallpaper(String extra) {
try {
Bitmap bitmap = loadImageFromUrl(extra);
setWallpaper(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Bitmap loadImageFromUrl(String url) {
InputStream inputStream;
Bitmap b;
try {
inputStream = (InputStream) new URL(url).getContent();
BitmapFactory.Options bpo = new BitmapFactory.Options();
bpo.inSampleSize = 2;
b = BitmapFactory.decodeStream(inputStream, null, bpo);
return b;
} catch (IOException e) {
throw new RuntimeException(e);
}
}