1.最终的效果
! 点击fetch
2.布局
菜单栏:
<item
android:id="@+id/fetch"
app:showAsAction="ifRoom|withText"
android:title="Fetch"
/>
<item
android:id="@+id/clear"
app:showAsAction="ifRoom|withText"
android:title="Clear"
/>
主页面:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:gravity="center"
android:text="@string/content"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#ccc"
/>
<TextView
android:id="@+id/tv_code"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
/>
</LinearLayout>
3.逻辑
/*
根据url并通过Http来下载数据
*/
private InputStream downloadUrl(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(10000/*毫秒*/);
conn.setConnectTimeout(15000/*毫秒*/);
conn.setRequestMethod("GET");
conn.setDoInput(true);
//开始连接
conn.connect();
InputStream stream = conn.getInputStream();
return stream;
}
/*
解析InputStream成字符串
*/
private String readIt(InputStream stream,int len) throws IOException {
Reader reader = null;
reader = new InputStreamReader(stream,"utf-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
/*
调用上面的函数返回结果
*/
private String loadFromNetwork(String url) throws IOException {
InputStream stream = null;
String str = "";
try{
stream = downloadUrl(url);
str = readIt(stream,1000);
}finally {
if(null!=stream){
stream.close();
}
}
return str;
}
/*
我们继承AsyncTask来更新UI,前后两个参数一个是返回类型,一个是参数类型
*/
private class DownloadTask extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... params) {
try {
return loadFromNetwork(params[0]);
} catch (IOException e) {
e.printStackTrace();
return "连接出错";
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tv_code.setText(s);
}
}
最后添加菜单栏事件:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.fetch:
new DownloadTask().execute("http://www.baidu.com");
break;
case R.id.clear:
tv_code.setText("");
break;
}
return true;
}
最后别忘了添加网络权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>