当前位置: 代码迷 >> Web前端 >> webView小小结
  详细解决方案

webView小小结

热度:232   发布时间:2013-02-27 10:48:11.0
webView小总结
package com.zhangqu.age.testwebview;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsoluteLayout;

/**
 * @author 小阿哥
 * @des    webview介绍。。  QQ:247124629
 * @date    2013-2-19
 *
 */
public class TestWebViewActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        //方式1:本地文件。 通过文件名。
//        AbsoluteLayout absLayout=new AbsoluteLayout(this);
//        absLayout.setBackgroundColor(0xffff0000);
//	        WebView webView=new WebView(this);
//	        webView.getSettings().setJavaScriptEnabled(true);	        
//	        webView.setBackgroundColor(0x00000000);	        	        
//	        webView.loadUrl("file:///android_asset/1.htm");	        	        	        
//	        webView.setWebViewClient(new WebViewClient(){       
//                public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                	 System.out.println("click.........URL:"+url);
//                    return true;       
//                }
//	        });
//	        
//        absLayout.addView(webView, new AbsoluteLayout.LayoutParams(700, 400, 50, 50));        
//        setContentView(absLayout);
        
        
        
//        //方式2:网络文件。 通过URL。。。。
//        AbsoluteLayout absLayout=new AbsoluteLayout(this);
//        absLayout.setBackgroundColor(0xffff0000);
//	        WebView webView=new WebView(this);
//	        webView.getSettings().setJavaScriptEnabled(true);	        
//	        webView.setBackgroundColor(0x00000000);	        	        
//	        webView.loadUrl("http://www.baidu.com/");	        	        	        
//	        webView.setWebViewClient(new WebViewClient(){       
//                public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                	 System.out.println("click.........URL:"+url);
//                    return true;       
//                }
//	        });
//	        
//        absLayout.addView(webView, new AbsoluteLayout.LayoutParams(700, 400, 50, 50));        
//        setContentView(absLayout);
        
        
//      //方式3:本地文件。 通过文件内容。
//      String data=getAssetsFileToString("1.htm","gbk",this);      
//      AbsoluteLayout absLayout=new AbsoluteLayout(this);
//      absLayout.setBackgroundColor(0xffff0000);
//	        WebView webView=new WebView(this);
//	        webView.getSettings().setJavaScriptEnabled(true);	        
//	        webView.setBackgroundColor(0x00000000);
//	        webView.loadDataWithBaseURL("file:///android_asset/", data, null, "utf-8", null);//一般都是这个编码格式。	        	        	        	       
//	        webView.setWebViewClient(new WebViewClient(){       
//              public boolean shouldOverrideUrlLoading(WebView view, String url) {
//              	 System.out.println("click.........URL:"+url);
//                  return true;       
//              }
//	        });
//	        
//      absLayout.addView(webView, new AbsoluteLayout.LayoutParams(700, 400, 50, 50));        
//      setContentView(absLayout);
        
        
      //方式4:网络文件。 通过文件内容。        
        Handler.Callback callBack=new Handler.Callback() {			
			@Override
			public boolean handleMessage(Message msg) {
				// TODO Auto-generated method stub
				int what=msg.what;
				
				if(what==123)
				{
					AbsoluteLayout absLayout=new AbsoluteLayout(TestWebViewActivity.this);
			        absLayout.setBackgroundColor(0xffff0000);
			  	        WebView webView=new WebView(TestWebViewActivity.this);
			  	        webView.getSettings().setJavaScriptEnabled(true);	        
			  	        webView.setBackgroundColor(0x00000000);
			  	        webView.loadData((String)msg.obj, "text/html", "utf-8");  	        	        	        	        	      
			  	        webView.setWebViewClient(new WebViewClient(){       
			                public boolean shouldOverrideUrlLoading(WebView view, String url) {
			                	 System.out.println("click.........URL:"+url);
			                    return true;       
			                }
			  	        });			  	        
			        absLayout.addView(webView, new AbsoluteLayout.LayoutParams(400, 700, 50, 50));        
			        setContentView(absLayout);					
				}				
				return false;
			}
		};
		
		final Handler handler=new Handler(callBack);
        
        new Thread(new Runnable() {			
			@Override
			public void run() {
				// TODO Auto-generated method stub
					String url="http://www.baidu.com/";				
				 	String data=requestWebContent(url,"UTF-8");					 					 	
				 	Message message=new Message();
				 	message.what=123;
				 	message.obj=data;
				 	handler.sendMessage(message);				      			       
			}
		}).start();
    }
    
    public String requestWebContent(String url,String charset)
    {    	    	
    	boolean usePxoxy=false;		
		HttpURLConnection conn = getUrlConnection(url, usePxoxy);
		try {
			int responseCode = conn.getResponseCode();
			if (responseCode == HttpURLConnection.HTTP_OK) {
				byte receiverContent[] = getByteArrayFromStream(conn.getInputStream());
				String content=new String(receiverContent,charset);
				return content;
			}
		} catch (Exception e) {
			Debug.println("getContentFromUrl Ex:" + e.toString());
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
		return null;
    }
    
   
    
    
    private HttpURLConnection getUrlConnection(String url, boolean useProxy) {
    	final int CONNECTION_TIMEOUT = 5 * 1000;
    	final String USER_AGENT = "IFENG/269013000720 Platform/AndroidV1.5/480x800";  
		HttpURLConnection connection = null;
		try {
			URL httpUrl = new URL(url);
			connection = (HttpURLConnection) httpUrl.openConnection();
			if (connection != null) {
				connection.setConnectTimeout(CONNECTION_TIMEOUT);
				connection.addRequestProperty("User-Agent", USER_AGENT);
			}

			if (connection.usingProxy()) {
				// Log.d("NetProxy", "Use Proxy");
			} else {
				// Log.d("NetProxy", "Don't use Proxy");
			}
		} catch (Exception ex) {
			Debug.println("getUrlConnection EX:" + ex.toString());
		}
		return connection;
	}
    
    
    public static final  byte[] getByteArrayFromStream(InputStream inputStream) {
		byte result[] = null;
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte buf[] = new byte[1024];
		int len;
		try {
			while ((len = inputStream.read(buf)) != -1) {
				outputStream.write(buf, 0, len);
			}
			outputStream.flush();
			result = outputStream.toByteArray();
			outputStream.close();
			outputStream = null;
			inputStream.close();
		} catch (Exception e) {
			Debug.println("getStreamByteArray().EX:" + e.toString());
		}
		return result;
	}
    
    public static String getAssetsFileToString(String filename, String decoder,Context ctx)
    {
    	StringBuilder sb = new StringBuilder();
    	InputStream file;
		try {
			file = ctx.getAssets().open(filename);					
			BufferedReader br = new BufferedReader(new InputStreamReader(file,decoder));   
             String row;  
             while((row = br.readLine())!= null)  
             {  
            	 sb.append(row);
             }  
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return sb.toString();
    }
}

?欢迎阅读。欢迎交流。

相关参考:

http://www.cnblogs.com/oakpip/archive/2011/04/08/2009800.html

http://developer.51cto.com/art/201008/216488.htm

http://www.2cto.com/kf/201112/113189.html