先交代背景
主機:Ubuntu16.04LTS
安裝服務:Apache2 http服務,80端口已開啓
網絡:無線網卡登錄 動態分配內網IP 192.168.1.106
1.本地網頁已經寫入,放在/var/www/html中,設爲默認網頁.文件名:index.html.因爲不進行具體的解析工作,網頁代碼不加展示.
2.App源代碼以及註釋
1)網絡請求屬於耗時操作,將其封裝入Thread類中.
public class HttpThread extends Thread{
private String url;
private WebView web;
private Handler handler;
private StringBuffer sb = new StringBuffer();
// 初始化
public HttpThread(String url,WebView web,Handler handler){
this.url = url;
this.web = web;
this.handler = handler;
}
//編寫主要耗時操作
@override
public void run(){
try{
URL myUrl = new URL(url);
HttpURLConnection localCon =(HttpURLConnection)myUrl.openConnection();
localCon.setRequestMethod("GET");
//通過Connection對象的open方法拿到輸入流,傳入InputStreamReader對象中,構建BufferedReader對象
BufferedReader reader = new BufferedReader( new InputStreamReader( localCon.getInputStream() ) );
String str = null;
while( (str=reader.readLine() ) != null){
sb.append(str);
}//while
//發送耗時邏輯
handler.post(new Runnable){
@override
public void run(){
web.loadData(sb.toString(),"text/html;charset=utf-8",null);
}
}//handler
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
e.printStackTrace();
}
}//run
}//class
2)主活動調用即可
Public Class MainActivity extends Activity{
private WebView web;
private Handler handler;
private String str = "http://192.168.1.106";
@override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
initiate();
// **線程必須開啓纔會生效**,調用start()方法.
new HttpThread(str,web,handler).start();
}
public void initiate(){
web = (WebView)findViewById(R.id.webview);
}
}