本實例主要介紹通過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!";
}
?>