1. 程式人生 > >Android WebView詳解之檔案下載

Android WebView詳解之檔案下載

1、佈局檔案activity_main.xml:線性佈局,TextView顯示頁面標題,WebView顯示頁面。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

2、Java類實現MainActivity:
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.Window;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

public class MainActivity extends Activity {
	private TextView textView;
	private WebView webView;

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		
		textView = (TextView) findViewById(R.id.textView1);
		webView = (WebView) findViewById(R.id.webView1);
		
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setWebViewClient(new WebViewClient(){ 
		     public boolean shouldOverrideUrlLoading(WebView view, String url) {
                 view.loadUrl(url);
                 return true;
		     }
		}); 
		webView.setWebChromeClient(new WebChromeClient(){
			@Override
			public void onReceivedTitle(WebView view, String title) {
				// TODO Auto-generated method stub
				textView.setText(title);
				super.onReceivedTitle(view, title);
			}
		});
		webView.setDownloadListener(new MyDownloadStart());
		webView.loadUrl("http://shouji.baidu.com");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	class MyDownloadStart implements DownloadListener{

		@Override
		public void onDownloadStart(String url, String userAgent,
				String contentDisposition, String mimetype, long contentLength) {
			// TODO Auto-generated method stub
			//呼叫自己的下載方式
//			new HttpThread(url).start();
			//呼叫系統瀏覽器下載
			Uri uri = Uri.parse(url);  
	        Intent intent = new Intent(Intent.ACTION_VIEW, uri);  
	        startActivity(intent);      
		}
		
	}
}
3、在使用自己的下載方式時,還需要下面的Java類HttpThread實現下載:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Environment;

public class HttpThread extends Thread {
	private String mUrl;
	
	public HttpThread(String url){
		this.mUrl = url;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			URL httpUrl = new URL(mUrl);
			HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
			//get請求的話預設就行了,post請求需要setDoOutput(true),這個預設是false的。
//			conn.setDoInput(true);
//			conn.setDoOutput(true);
			InputStream in = conn.getInputStream();
			
			File downloadFile;
			File sdFile;
			FileOutputStream out = null;
			//判斷SD卡
			if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
				downloadFile = Environment.getExternalStorageDirectory();
				sdFile = new File(downloadFile, "test.apk");
				out = new FileOutputStream(sdFile);
			}
			
			byte[] b = new byte[6*1024];
			int len;
			
			while((len=in.read(b))!=-1){
				if(out!=null){
					out.write(b, 0, len);
				}
			}
			if(out != null){
				out.close();
			}
			
			if(in != null){
				in.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

4、需要許可權:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

下載原始碼

文章推薦:http://gundumw100.iteye.com/blog/1338645