溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Android WebView實(shí)現(xiàn)文件下載功能

發(fā)布時(shí)間:2020-10-11 22:30:06 來(lái)源:腳本之家 閱讀:391 作者:攝氏三十七度 欄目:移動(dòng)開(kāi)發(fā)

WebView控制調(diào)用相應(yīng)的WEB頁(yè)面進(jìn)行展示。當(dāng)碰到頁(yè)面有下載鏈接的時(shí)候,點(diǎn)擊上去是一點(diǎn)反應(yīng)都沒(méi)有的。原來(lái)是因?yàn)閃ebView默認(rèn)沒(méi)有開(kāi)啟文件下載的功能,如果要實(shí)現(xiàn)文件下載的功能,需要設(shè)置WebView的DownloadListener,通過(guò)實(shí)現(xiàn)自己的DownloadListener來(lái)實(shí)現(xiàn)文件的下載。具體操作如下:

1、設(shè)置WebView的DownloadListener: 

 webView.setDownloadListener(new MyWebViewDownLoadListener());

2、實(shí)現(xiàn)MyWebViewDownLoadListener這個(gè)類(lèi),具體可以如下這樣: 

private class MyWebViewDownLoadListener implements DownloadListener{ 
 
  @Override 
  public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, 
         long contentLength) {    
   Log.i("tag", "url="+url);    
   Log.i("tag", "userAgent="+userAgent); 
   Log.i("tag", "contentDisposition="+contentDisposition);   
   Log.i("tag", "mimetype="+mimetype); 
   Log.i("tag", "contentLength="+contentLength); 
   Uri uri = Uri.parse(url); 
   Intent intent = new Intent(Intent.ACTION_VIEW, uri); 
   startActivity(intent);    
  } 
} 

這只是調(diào)用系統(tǒng)中已經(jīng)內(nèi)置的瀏覽器進(jìn)行下載,還沒(méi)有WebView本身進(jìn)行的文件下載,不過(guò),這也基本上滿足我們的應(yīng)用場(chǎng)景了。

我在項(xiàng)目中的運(yùn)用

項(xiàng)目要求這樣:
1.需要使用WebView加載一個(gè)網(wǎng)頁(yè);
2.網(wǎng)頁(yè)中有文件下載的鏈接,點(diǎn)擊后需要下載文件到SDcard;
3.然后自動(dòng)打開(kāi)文件;

下面是具體解決辦法
第一步,對(duì)WebView進(jìn)行一系列設(shè)置。

WebView webview=(WebView)layout.findViewById(R.id.webview); 
    webview.getSettings().setJavaScriptEnabled(true); 
    webview.setWebChromeClient(new MyWebChromeClient()); 
    webview.requestFocus(); 
//    webview.loadUrl("file:///android_asset/risktest.html"); 
    webview.loadUrl(jcrs_sub.get(position).addr); 
    // 設(shè)置web視圖客戶端 
    webview.setWebViewClient(new MyWebViewClient()); 
    webview.setDownloadListener(new MyWebViewDownLoadListener()); 
 
//內(nèi)部類(lèi) 
public class MyWebViewClient extends WebViewClient { 
  // 如果頁(yè)面中鏈接,如果希望點(diǎn)擊鏈接繼續(xù)在當(dāng)前browser中響應(yīng), 
  // 而不是新開(kāi)Android的系統(tǒng)browser中響應(yīng)該鏈接,必須覆蓋 webview的WebViewClient對(duì)象。 
  public boolean shouldOverviewUrlLoading(WebView view, String url) { 
   L.i("shouldOverviewUrlLoading"); 
   view.loadUrl(url); 
   return true; 
  } 
 
  public void onPageStarted(WebView view, String url, Bitmap favicon) { 
   L.i("onPageStarted"); 
   showProgress(); 
  } 
 
  public void onPageFinished(WebView view, String url) { 
   L.i("onPageFinished"); 
   closeProgress(); 
  } 
 
  public void onReceivedError(WebView view, int errorCode, 
    String description, String failingUrl) { 
   L.i("onReceivedError"); 
   closeProgress(); 
  } 
 } 
 
// 如果不做任何處理,瀏覽網(wǎng)頁(yè),點(diǎn)擊系統(tǒng)“Back”鍵,整個(gè)Browser會(huì)調(diào)用finish()而結(jié)束自身, 
 // 如果希望瀏覽的網(wǎng) 頁(yè)回退而不是推出瀏覽器,需要在當(dāng)前Activity中處理并消費(fèi)掉該Back事件。 
 public boolean onKeyDown(int keyCode, KeyEvent event) { 
  // if((keyCode==KeyEvent.KEYCODE_BACK)&&webview.canGoBack()){ 
  // webview.goBack(); 
  // return true; 
  // } 
  return false; 
} 

第二步,起線程開(kāi)始下載文件。

//內(nèi)部類(lèi) 
private class MyWebViewDownLoadListener implements DownloadListener { 
 
  @Override 
  public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, 
         long contentLength) { 
   if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ 
    Toast t=Toast.makeText(mContext, "需要SD卡。", Toast.LENGTH_LONG); 
    t.setGravity(Gravity.CENTER, 0, 0); 
    t.show(); 
    return; 
   } 
   DownloaderTask task=new DownloaderTask(); 
   task.execute(url); 
  } 
 
 } 
 //內(nèi)部類(lèi) 
 private class DownloaderTask extends AsyncTask<String, Void, String> { 
 
  public DownloaderTask() { 
  } 
 
  @Override 
  protected String doInBackground(String... params) { 
   // TODO Auto-generated method stub 
   String url=params[0]; 
//   Log.i("tag", "url="+url); 
   String fileName=url.substring(url.lastIndexOf("/")+1); 
   fileName=URLDecoder.decode(fileName); 
   Log.i("tag", "fileName="+fileName); 
    
   File directory=Environment.getExternalStorageDirectory(); 
   File file=new File(directory,fileName); 
   if(file.exists()){ 
    Log.i("tag", "The file has already exists."); 
    return fileName; 
   } 
   try { 
    HttpClient client = new DefaultHttpClient(); 
//    client.getParams().setIntParameter("http.socket.timeout",3000);//設(shè)置超時(shí) 
    HttpGet get = new HttpGet(url); 
    HttpResponse response = client.execute(get); 
    if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){ 
     HttpEntity entity = response.getEntity(); 
     InputStream input = entity.getContent(); 
      
     writeToSDCard(fileName,input); 
      
     input.close(); 
//     entity.consumeContent(); 
     return fileName; 
    }else{ 
     return null; 
    } 
   } catch (Exception e) { 
    e.printStackTrace(); 
    return null; 
   } 
  } 
 
  @Override 
  protected void onCancelled() { 
   // TODO Auto-generated method stub 
   super.onCancelled(); 
  } 
 
  @Override 
  protected void onPostExecute(String result) { 
   // TODO Auto-generated method stub 
   super.onPostExecute(result); 
   closeProgressDialog(); 
   if(result==null){ 
    Toast t=Toast.makeText(mContext, "連接錯(cuò)誤!請(qǐng)稍后再試!", Toast.LENGTH_LONG); 
    t.setGravity(Gravity.CENTER, 0, 0); 
    t.show(); 
    return; 
   } 
    
   Toast t=Toast.makeText(mContext, "已保存到SD卡。", Toast.LENGTH_LONG); 
   t.setGravity(Gravity.CENTER, 0, 0); 
   t.show(); 
   File directory=Environment.getExternalStorageDirectory(); 
   File file=new File(directory,result); 
   Log.i("tag", "Path="+file.getAbsolutePath()); 
    
   Intent intent = getFileIntent(file); 
    
   startActivity(intent); 
     
  } 
 
  @Override 
  protected void onPreExecute() { 
   // TODO Auto-generated method stub 
   super.onPreExecute(); 
   showProgressDialog(); 
  } 
 
  @Override 
  protected void onProgressUpdate(Void... values) { 
   // TODO Auto-generated method stub 
   super.onProgressUpdate(values); 
  } 
 
} 

第三步,實(shí)現(xiàn)一些工具方法。

private ProgressDialog mDialog; 
 private void showProgressDialog(){ 
  if(mDialog==null){ 
   mDialog = new ProgressDialog(mContext); 
   mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//設(shè)置風(fēng)格為圓形進(jìn)度條 
   mDialog.setMessage("正在加載 ,請(qǐng)等待..."); 
   mDialog.setIndeterminate(false);//設(shè)置進(jìn)度條是否為不明確 
   mDialog.setCancelable(true);//設(shè)置進(jìn)度條是否可以按退回鍵取消 
   mDialog.setCanceledOnTouchOutside(false); 
   mDialog.setOnDismissListener(new OnDismissListener() { 
     
    @Override 
    public void onDismiss(DialogInterface dialog) { 
     // TODO Auto-generated method stub 
     mDialog=null; 
    } 
   }); 
   mDialog.show(); 
    
  } 
 } 
 private void closeProgressDialog(){ 
  if(mDialog!=null){ 
   mDialog.dismiss(); 
   mDialog=null; 
  } 
 } 
  public Intent getFileIntent(File file){ 
//  Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf"); 
  Uri uri = Uri.fromFile(file); 
  String type = getMIMEType(file); 
  Log.i("tag", "type="+type); 
  Intent intent = new Intent("android.intent.action.VIEW"); 
  intent.addCategory("android.intent.category.DEFAULT"); 
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
  intent.setDataAndType(uri, type); 
  return intent; 
  } 
  
 public void writeToSDCard(String fileName,InputStream input){ 
   
  if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ 
   File directory=Environment.getExternalStorageDirectory(); 
   File file=new File(directory,fileName); 
//   if(file.exists()){ 
//    Log.i("tag", "The file has already exists."); 
//    return; 
//   } 
   try { 
    FileOutputStream fos = new FileOutputStream(file); 
    byte[] b = new byte[2048]; 
    int j = 0; 
    while ((j = input.read(b)) != -1) { 
     fos.write(b, 0, j); 
    } 
    fos.flush(); 
    fos.close(); 
   } catch (FileNotFoundException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
   } catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
   } 
  }else{ 
   Log.i("tag", "NO SDCard."); 
  } 
 } 
  
 private String getMIMEType(File f){  
  String type=""; 
  String fName=f.getName(); 
  /* 取得擴(kuò)展名 */ 
  String end=fName.substring(fName.lastIndexOf(".")+1,fName.length()).toLowerCase(); 
  
  /* 依擴(kuò)展名的類(lèi)型決定MimeType */ 
  if(end.equals("pdf")){ 
   type = "application/pdf";// 
  } 
  else if(end.equals("m4a")||end.equals("mp3")||end.equals("mid")|| 
  end.equals("xmf")||end.equals("ogg")||end.equals("wav")){ 
  type = "audio/*";  
  } 
  else if(end.equals("3gp")||end.equals("mp4")){ 
  type = "video/*"; 
  } 
  else if(end.equals("jpg")||end.equals("gif")||end.equals("png")|| 
  end.equals("jpeg")||end.equals("bmp")){ 
  type = "image/*"; 
  } 
  else if(end.equals("apk")){  
  /* android.permission.INSTALL_PACKAGES */  
  type = "application/vnd.android.package-archive"; 
  } 
//  else if(end.equals("pptx")||end.equals("ppt")){ 
//  type = "application/vnd.ms-powerpoint"; 
//  }else if(end.equals("docx")||end.equals("doc")){ 
//  type = "application/vnd.ms-word"; 
//  }else if(end.equals("xlsx")||end.equals("xls")){ 
//  type = "application/vnd.ms-excel"; 
//  } 
  else{ 
//  /*如果無(wú)法直接打開(kāi),就跳出軟件列表給用戶選擇 */ 
  type="*/*"; 
  } 
  return type; 
} 

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI