Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android之WebView應用

android之WebView應用

編輯:關於Android編程

本實例主要介紹通過WebView實現如何通過網頁設計UI(當網頁UI請求錯誤時,怎樣給用戶返回友好的界面)、如何利用WebView實現下載功能、以及通過cookie實現免登陸功能。

 

xml布局文件

 



主體功能代碼

 

 

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 list = new ArrayList();
		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 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後台代碼

 

登陸頁面

 



姓 名
密 碼
 

cookie設置頁面

 

 

 

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved