android之WebView应用

本实例主要介绍通过WebView实现如何通过网页设计UI(当网页UI请求错误时,怎样给用户返回友好的界面)、如何利用WebView实现下载功能、以及通过cookie实现免登陆功能。


xml布局文件

<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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/id_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/selector_back" />

        <TextView
            android:id="@+id/id_url"
            android:singleLine="true"
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="url"
            android:textColor="#44000000"
            android:textSize="23sp" />

        <ImageButton
            android:id="@+id/id_refresh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/selector_refresh" />
    </LinearLayout>
    <View 
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#22000000"/>
    
    <WebView 
        android:id="@+id/id_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

主体功能代码

public class MainActivity extends Activity implements OnClickListener{

	private WebView mWebView;
	private ImageButton mBackBtn, mRefreshBtn;
	private TextView mUrlTv;
	
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			String cookie = (String)msg.obj;
			System.out.println(cookie);
			CookieSyncManager.createInstance(MainActivity.this);
			CookieManager cookieManager = CookieManager.getInstance();
			cookieManager.setAcceptCookie(true);
			cookieManager.setCookie("http://10.10.1.24/android%20web/vebview.php", cookie);
			CookieSyncManager.getInstance().sync();
		
			mWebView.loadUrl("http://10.10.1.24/android%20web/vebview.php");
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mWebView = (WebView) findViewById(R.id.id_webview);
		mBackBtn = (ImageButton) findViewById(R.id.id_back);
		mRefreshBtn = (ImageButton) findViewById(R.id.id_refresh);
		mUrlTv = (TextView) findViewById(R.id.id_url);
		
		mBackBtn.setOnClickListener(this);
		mRefreshBtn.setOnClickListener(this);
		
		mWebView.loadUrl("http://what");
		mWebView.setWebChromeClient(new WebChromeClient(){
			/**
			 * 获取html页面标题
			 */
			@Override
			public void onReceivedTitle(WebView view, String title) {
				mUrlTv.setText(title);
				super.onReceivedTitle(view, title);
			}

		});
		
		mWebView.setWebViewClient(new WebViewClient(){
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return super.shouldOverrideUrlLoading(view, url);
			}
			
			/**
			 * 请求页面错误处理
			 */
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				
				mWebView.loadUrl("file:///android_asset/error.html");
			}
		});
		
		/**
		 * 点击了下载链接处理
		 * 是直接下载还是通过浏览器下载
		 */
		mWebView.setDownloadListener(new MyDownLoadListener());
		
		/**
		 * 通过WebView的cookie实现免登陆功能
		 */
		new HttpCookie(mHandler).start();
	}
	
	class MyDownLoadListener implements DownloadListener{

		@Override
		public void onDownloadStart(String url, String userAgent,
				String contentDisposition, String mimetype, long contentLength) {
			/**
			 * 点击了下载链接时,并且下载文件为apk
			 * 开始下载文件
			 */
			if(url.endsWith(".apk")){
				//new HttpThread(url).start();
				Uri uri = Uri.parse(url);
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(intent);
			}
		}
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.id_refresh:
			mWebView.reload();
			break;

		case R.id.id_back:
			finish();
			break;
		}
	}

}

实现下载功能的线程

public class HttpThread extends Thread {
	
	private String mUrl;
	
	public HttpThread(String url) {
		this.mUrl = url;
	}
	
	@Override
	public void run() {
		InputStream is = null;
		FileOutputStream fos = null;
		try {
			URL httpUrl = new URL(mUrl);
			HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
			
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setConnectTimeout(5000);
			File downloadFolder;
			File downloadfile;
			is = conn.getInputStream();
			if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
				downloadFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "WebDownd");
				if(!downloadFolder.exists()){
					downloadFolder.mkdir();
				}
				downloadfile = new File(downloadFolder, "test.apk");
				fos = new FileOutputStream(downloadfile);
			}
			
			byte[] buffer = new byte[1024];
			int len;
			while ((len = is.read(buffer)) != -1) {
				fos.write(buffer,0,len);
			}
			System.out.println("download sucess");
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			
			try {
				if (is != null)
					is.close();
				if (fos != null)
					fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			;
		}
	}
}

Cookie获取线程

public class HttpCookie extends Thread {
	
	private Handler mHandler;
	
	public HttpCookie(Handler handler) {
		this.mHandler = handler;
	}
	
	@Override
	public void run() {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://10.10.1.24/android%20web/login.php");
		
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("name", "zhangliang"));
		list.add(new BasicNameValuePair("pwd", "123"));
		try {
			post.setEntity(new UrlEncodedFormEntity(list));
		
			HttpResponse response = client.execute(post);

			if(response.getStatusLine().getStatusCode() == 200){
				AbstractHttpClient absClient = (AbstractHttpClient) client;
				List<Cookie> cookies = absClient.getCookieStore().getCookies();
				String ck = null;
				for (Cookie cookie : cookies) {
					System.out.println(cookie.getName() + cookie.getValue());
					
					ck = cookie.getName() + "=" + cookie.getValue() + ";domain=" + cookie.getDomain() + ";";
				}
				Message message = new Message();
				message.obj = ck;
				mHandler.sendMessage(message);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


以下部分是php后台代码

登陆页面

<?php
	$name = $_COOKIE['name'];
	$age = $_COOKIE['pwd'];
	if(!empty($name)){
		header("Location:welocom.html");
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title> new document </title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
 </head>
	
 <body>
  <form action="login.php" method="post">
	姓 名<input type="text" name="name"/><br/>
	密 码<input type="text" name="pwd"/><br/>
	<input type="submit" value="提交">
  </form>
 </body>
</html>

cookie设置页面

<?php
	$name = $_POST['name'];
	$age = $_POST['pwd'];

	setCookie("name", $name, time() + 3600);
	setCookie("pwd", $age, time() + 3600);

	if(!empty($name)){
		echo "welcom to login!";
	}
?>

源码下载


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。