Android Use webView Long Press to Save and Download Network Pictures

  • 2021-11-10 10:54:49
  • OfStack

This article example for everyone to share Android use webView long press to save download network pictures of the specific code, for your reference, the specific content is as follows

Recently, it is found that WebView. HitTestResult can be obtained from setOnLongClickListener of webView, and different treatments can be made according to Type of HitTestResult. By judging the type of Type, get the url of the click picture, then download the picture to the local, send a broadcast to inform the system gallery to update, and view the downloaded picture in the system gallery. Run Demo to make a long click on the picture in the web page to download the network picture

Directly on the code:

The download of Demo is attached below: Click the open link


package demo.sam.webview_demo; 

import android.app.Activity; 
import android.app.Dialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.Handler; 
import android.os.Message; 
import android.provider.MediaStore; 
import android.support.v7.app.AlertDialog; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.text.Editable; 
import android.util.Log; 
import android.view.KeyEvent; 
import android.view.View; 
import android.webkit.WebChromeClient; 
import android.webkit.WebResourceRequest; 
import android.webkit.WebSettings; 
import android.webkit.WebView; 
import android.webkit.WebViewClient; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ProgressBar; 
import android.widget.Toast; 

import java.io.FileNotFoundException; 

public class MainActivity extends Activity { 

 private ProgressBar progress; 
 private WebView webView; 
 private EditText editText; 
 private Button click; 
 private Context context; 


 @Override 
 protected void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.activity_main); 
  context= this; 
  initView(); 
  initData(); 
  initListener(); 



 } 

 private void initData() { 
  WebSettings settings = webView.getSettings(); 
  settings.setJavaScriptEnabled(true); 
  settings.setUseWideViewPort(true);// Set this property, which can be scaled arbitrarily  
  settings.setLoadWithOverviewMode(true); 
  //  Enable the page to support scaling  
  settings.setBuiltInZoomControls(true); 
  settings.setSupportZoom(true); 
  // Support automatic loading of pictures  
  settings.setLoadsImagesAutomatically(true); 
  settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);//  Typesetting adaptation screen  
  //  Zoom button  
  settings.setDisplayZoomControls(false); 

  webView.setWebViewClient(new WebViewClient(){ 

   //  The page jumps on the current page  
   @Override 
   public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { 
    return super.shouldOverrideUrlLoading(view, request); 
   } 

   //  End of page loading  
   @Override 
   public void onPageFinished(WebView view, String url) { 
    super.onPageFinished(view, url); 
    if(progress!=null){ 
     progress.setVisibility(View.GONE); 
    } 
   } 
  }); 

 } 

 private void initView() { 
  progress = (ProgressBar) findViewById(R.id.progress); 
  webView = (WebView) findViewById(R.id.webView); 
  editText = (EditText) findViewById(R.id.url); 
  click = (Button) findViewById(R.id.click); 
 } 

 private void initListener() { 
  //  Web page loading progress display  
  webView.setWebChromeClient(new WebChromeClient(){ 
   @Override 
   public void onProgressChanged(WebView view, int newProgress) { 
    super.onProgressChanged(view, newProgress); 
    progress.setVisibility(View.VISIBLE); 
    progress.setProgress(newProgress); 
   } 
  }); 

  click.setOnClickListener(new View.OnClickListener() { 
   @Override 
   public void onClick(View view) { 
    Log.e(" Web site entered ",editText.getText().toString().trim()); 
    webView.loadUrl(editText.getText().toString().trim()); 
   } 
  }); 

  //  Long press click event  
  webView.setOnLongClickListener(new View.OnLongClickListener() { 
   @Override 
   public boolean onLongClick(View view) { 
    final WebView.HitTestResult hitTestResult = webView.getHitTestResult(); 
    //  If it is a picture type or a type with a picture link,  
    if(hitTestResult.getType()== WebView.HitTestResult.IMAGE_TYPE|| 
      hitTestResult.getType()== WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE){ 
     //  The dialog box for saving pictures pops up  
     AlertDialog.Builder builder = new AlertDialog.Builder(context); 
     builder.setTitle(" Prompt "); 
     builder.setMessage(" Save pictures locally "); 
     builder.setPositiveButton(" Confirm ", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialogInterface, int i) { 
       String url = hitTestResult.getExtra(); 
       //  Download pictures to local  
       DownPicUtil.downPic(url, new DownPicUtil.DownFinishListener(){ 

        @Override 
        public void getDownPath(String s) { 
         Toast.makeText(context," Download complete ",Toast.LENGTH_LONG).show(); 
         Message msg = Message.obtain(); 
         msg.obj=s; 
         handler.sendMessage(msg); 
        } 
       }); 

      } 
     }); 
     builder.setNegativeButton(" Cancel ", new DialogInterface.OnClickListener() { 
      //  Automatic dismiss 
      @Override 
      public void onClick(DialogInterface dialogInterface, int i) { 
      } 
     }); 
     AlertDialog dialog = builder.create(); 
     dialog.show(); 
    } 
    return true; 
   } 
  }); 

  webView.loadUrl("http://www.baidu.com"); 
 } 

 Handler handler =new Handler(){ 
  @Override 
  public void handleMessage(Message msg) { 
   super.handleMessage(msg); 
   String picFile = (String) msg.obj; 
   String[] split = picFile.split("/"); 
   String fileName = split[split.length-1]; 
   try { 
    MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(), picFile, fileName, null); 
   } catch (FileNotFoundException e) { 
    e.printStackTrace(); 
   } 
   //  Finally notify gallery of updates  
   getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + picFile))); 
   Toast.makeText(context," Picture saved gallery successfully ",Toast.LENGTH_LONG).show(); 
  } 
 }; 


 //  Listen to the return key to return to the web page 1 Layer  
 @Override 
 public boolean onKeyDown(int keyCode, KeyEvent event) { 
  if(keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){ 
   if(webView != null){ 
    webView.goBack(); 
    return true; 
   } 
  } 
  return super.onKeyDown(keyCode, event); 
 } 

} 

Tool class for picture download


import android.os.AsyncTask; 
import android.os.Environment; 
import android.util.Log; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.URL; 
import java.util.Random; 

/** 
 *  Tool class for picture download  
 */ 
public class DownPicUtil { 

 /** 
  * Download the picture and return the address of the picture  
  * @param url 
  */ 
 public static void downPic(String url,DownFinishListener downFinishListener){ 
  //  Get the directory of the memory card  
  String filePath = Environment.getExternalStorageDirectory().getPath(); 
  File file = new File(filePath+File.separator+"webViewCache"); 
  if(!file.exists()){ 
   file.mkdir(); 
  } 

  loadPic(file.getPath(),url,downFinishListener); 

 } 

 private static void loadPic(final String filePath, final String url, final DownFinishListener downFinishListener) { 
  Log.e(" Download the picture url",url); 
  new AsyncTask<Void,Void,String>(){ 
   String fileName; 
   InputStream is; 
   OutputStream out; 

   @Override 
   protected String doInBackground(Void... voids) { 

    //  Name of the downloaded file  
    String[] split = url.split("/"); 
    String newString = split[split.length - 1]; 
    fileName =newString.substring(newString.length()-20,newString.length()-1) ; 
    //  Create a target file , Not a folder  
    File picFile = new File(filePath + File.separator + fileName); 
    if(picFile.exists()){ 
     return picFile.getPath(); 
    } 

    try { 
     URL picUrl = new URL(url); 
     // Open the input stream through the link of the picture  
     is = picUrl.openStream(); 
     if(is==null){ 
      return null; 
     } 
     out = new FileOutputStream(picFile); 
     byte[] b=new byte[1024]; 
     int end ; 
     while ((end=is.read(b))!=-1){ 
      out.write(b,0,end); 
     } 

     Log.e("OK??","----------"); 
     if(is!=null){ 
      is.close(); 
     } 

     if(out!=null){ 
      out.close(); 
     } 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 



    return picFile.getPath(); 
   } 

   @Override 
   protected void onPostExecute(String s) { 
    super.onPostExecute(s); 
    if(s!=null){ 
     downFinishListener.getDownPath(s); 
    } 
   } 
  }.execute(); 
 } 
 // Download the interface to complete the callback  
 public interface DownFinishListener{ 

  void getDownPath(String s); 
 } 
} 

Related articles: