WebView實現檔案下載功能
阿新 • • 發佈:2019-01-26
WebView控制呼叫相應的WEB頁面進行展示。當碰到頁面有下載連結的時候,點選上去是一點反應都沒有的。原來是因為WebView預設沒有開啟檔案下載的功能,如果要實現檔案下載的功能,需要設定WebView的DownloadListener,通過實現自己的DownloadListener來實現檔案的下載。具體操作如下:
1、設定WebView的DownloadListener:
webView.setDownloadListener(new MyWebViewDownLoadListener());
我在專案中的運用
專案要求這樣:
1,需要使用WebView載入一個網頁;
2,網頁中有檔案下載的連結,點選後需要下載檔案到SDcard;
3,然後自動開啟檔案;
下面是具體解決辦法
第一步,對WebView進行一系列設定。
1、設定WebView的DownloadListener:
webView.setDownloadListener(new MyWebViewDownLoadListener());
2、實現MyWebViewDownLoadListener這個類,具體可以如下這樣:
- privateclass MyWebViewDownLoadListener implements DownloadListener{
- @Override
- publicvoid onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
- long contentLength) {
- Log.i("tag", "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
- startActivity(intent);
- }
- }
我在專案中的運用
專案要求這樣:
1,需要使用WebView載入一個網頁;
2,網頁中有檔案下載的連結,點選後需要下載檔案到SDcard;
3,然後自動開啟檔案;
下面是具體解決辦法
第一步,對WebView進行一系列設定。
- 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);
- // 設定web檢視客戶端
- webview.setWebViewClient(new MyWebViewClient());
- webview.setDownloadListener(new MyWebViewDownLoadListener());
- //內部類
- publicclass MyWebViewClient extends WebViewClient {
- // 如果頁面中連結,如果希望點選連結繼續在當前browser中響應,
- // 而不是新開Android的系統browser中響應該連結,必須覆蓋 webview的WebViewClient物件。
- publicboolean shouldOverviewUrlLoading(WebView view, String url) {
- L.i("shouldOverviewUrlLoading");
- view.loadUrl(url);
- returntrue;
- }
- publicvoid onPageStarted(WebView view, String url, Bitmap favicon) {
- L.i("onPageStarted");
- showProgress();
- }
- publicvoid onPageFinished(WebView view, String url) {
- L.i("onPageFinished");
- closeProgress();
- }
- publicvoid onReceivedError(WebView view, int errorCode,
- String description, String failingUrl) {
- L.i("onReceivedError");
- closeProgress();
- }
- }
- // 如果不做任何處理,瀏覽網頁,點選系統“Back”鍵,整個Browser會呼叫finish()而結束自身,
- // 如果希望瀏覽的網 頁回退而不是推出瀏覽器,需要在當前Activity中處理並消費掉該Back事件。
- publicboolean onKeyDown(int keyCode, KeyEvent event) {
- // if((keyCode==KeyEvent.KEYCODE_BACK)&&webview.canGoBack()){
- // webview.goBack();
- // return true;
- // }
- returnfalse;
- }
- //內部類
- privateclass MyWebViewDownLoadListener implements DownloadListener {
- @Override
- publicvoid 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);
- }
- }
- //內部類
- privateclass 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);//設定超時
- 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{
- returnnull;
- }
- } catch (Exception e) {
- e.printStackTrace();
- returnnull;
- }
- }
- @Override
- protectedvoid onCancelled() {
- // TODO Auto-generated method stub
- super.onCancelled();
- }
- @Override
- protectedvoid onPostExecute(String result) {
- // TODO Auto-generated method stub
- super.onPostExecute(result);
- closeProgressDialog();
- if(result==null){
- Toast t=Toast.makeText(mContext, "連線錯誤!請稍後再試!", 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
- protectedvoid onPreExecute() {
- // TODO Auto-generated method stub
- super.onPreExecute();
- showProgressDialog();
- }
- @Override
- protectedvoid onProgressUpdate(Void... values) {
- // TODO Auto-generated method stub
- super.onProgressUpdate(values);
- }
- }
- <span style="font-family:Helvetica, Tahoma, Arial, sans-serif;">private ProgressDialog mDialog;
- privatevoid showProgressDialog(){
- if(mDialog==null){
- mDialog = new ProgressDialog(mContext);
- mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//設定風格為圓形進度條
- mDialog.setMessage("正在載入 ,請等待...");
- mDialog.setIndeterminate(false);//設定進度條是否為不明確
- mDialog.setCancelable(true);//設定進度條是否可以按退回鍵取消
- mDialog.setCanceledOnTouchOutside(false);
- mDialog.setOnDismissListener(new OnDismissListener() {
- @Override
- publicvoid onDismiss(DialogInterface dialog) {
- // TODO Auto-generated method stub
- mDialog=null;
- }
- });
- mDialog.show();
- }
- }
- privatevoid 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;
- }
- publicvoid 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 = newbyte[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();
- /* 取得副檔名 */
- String end=fName.substring(fName.lastIndexOf(".")+1,fName.length()).toLowerCase();
- /* 依副檔名的型別決定MimeType */
- if(end.equals("pdf")){
- type = "application/pdf";//
- }
- elseif(end.equals("m4a")||end.equals("mp3")||end.equals("mid")||
- end.equals("xmf")||end.equals("ogg")||end.equals("wav")){
- type = "audio/*";
- }
- elseif(end.equals("3gp")||end.equals("mp4")){
- type = "video/*";
- }
- elseif(end.equals("jpg")||end.equals("gif")||end.equals("png")||
- end.equals("jpeg")||end.equals("bmp")){
- type = "image/*";
- }
- elseif(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{
- // /*如果無法直接開啟,就跳出軟體列表給使用者選擇 */
- type="*/*";
- }
- return type;
- } </span>
- <span style="font-family:Helvetica, Tahoma, Arial, sans-serif;">轉自:<a href="http://gundumw100.iteye.com/blog/1338645">http://gundumw100.iteye.com/blog/1338645</a>
- </span>