編輯:Android 開發實例
本文動手做一個簡單的手機博客客戶端。這一版先完成兩件事:
1、從伺服器取得一段 XML 資料,解析後呈現在畫面上;
2、點擊圖片可以放大檢視。
一、主畫面版面配置
使用 ListView 呈現串流:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/blogLV"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>
二、單筆項目(item)版面配置
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/portraitIV"
android:layout_width="50dp"
android:layout_height="50dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="@+id/nameTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:text="姓名"
android:textSize="20sp" />
<TextView
android:id="@+id/contentTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:textSize="15sp" />
<ImageView
android:id="@+id/picIV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:adjustViewBounds="true"
android:maxHeight="100dp"
android:maxWidth="100dp" />
<TextView
android:id="@+id/fromTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:textColor="#55FFFFFF"
android:text="來自新浪博客"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
三、資料模型 Blog.java
package cn.itcast.blog;
public class Blog {
private String portrait;
private String name;
private String content;
private String pic;
private String from;
public Blog() {
super();
}
public Blog(String portrait, String name, String content, String pic,
String from) {
super();
this.portrait = portrait;
this.name = name;
this.content = content;
this.pic = pic;
this.from = from;
}
public String getPortrait() { return portrait; }
public void setPortrait(String portrait) { this.portrait = portrait; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public String getPic() { return pic; }
public void setPic(String pic) { this.pic = pic; }
public String getFrom() { return from; }
public void setFrom(String from) { this.from = from; }
@Override
public String toString() {
return "Blog [portrait=" + portrait + ", name=" + name + ", content="
+ content + ", pic=" + pic + ", from=" + from + "]";
}
}
四、主介面 MainActivity
package cn.itcast.blog;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class mainActivity extends Activity {
private ListView blogLV;
private List<Blog> blogs;
private ImageService imageService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
imageService = new ImageService(getApplicationContext());
BlogService blogservice = new BlogService();
blogs = blogservice.getBlogs();
blogLV = (ListView) this.findViewById(R.id.blogLV);
blogLV.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "服務器忙", 0).show();
}
}
private BaseAdapter adapter = new BaseAdapter() {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView == null
? View.inflate(getApplicationContext(), R.layout.item, null)
: convertView;
ImageView portraitIV = (ImageView) view.findViewById(R.id.portraitIV);
TextView nameTV = (TextView) view.findViewById(R.id.nameTV);
TextView contentTV = (TextView) view.findViewById(R.id.contentTV);
ImageView picIV = (ImageView) view.findViewById(R.id.picIV);
TextView fromTV = (TextView) view.findViewById(R.id.fromTV);
final Blog blog = blogs.get(position);
nameTV.setText(blog.getName());
contentTV.setText(blog.getContent());
fromTV.setText(blog.getFrom());
try {
portraitIV.setImageBitmap(imageService.getImage(blog.getPortrait()));
} catch (Exception e) {
e.printStackTrace();
}
try {
picIV.setImageBitmap(imageService.getImage(blog.getPic()));
// 點擊圖片開啟檢視
picIV.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(blog.getPic()));
startActivity(intent);
}
});
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
@Override
public long getItemId(int position) { return 0; }
@Override
public Object getItem(int position) { return null; }
@Override
public int getCount() {
return blogs.size();
}
};
}
五、圖片服務 ImageService(含磁碟快取)
package cn.itcast.blog;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import android.accounts.NetworkErrorException;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
public class ImageService {
private Context context;
public ImageService(Context context) {
this.context = context;
}
public Bitmap getImage(String address) throws Exception {
// 1. 沒有資源就直接回傳 null
if (address == null) return null;
// 2. 開啟連線
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
// 3. 準備快取檔,並帶入最後修改時間做條號比對
File cacheFile = new File(context.getCacheDir(),
URLEncoder.encode(address));
if (cacheFile.exists()) {
conn.setIfModifiedSince(cacheFile.lastModified());
}
int code = conn.getResponseCode();
if (code == 200) {
// 4. 讀網路資料並轉為圖片
byte[] data = Util.read(conn.getInputStream());
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
// 5. 另開執行緒寫入快取
writeCache(cacheFile, bm);
return bm;
} else if (code == 304) {
// 6. 未修改,直接讀本地快取
return BitmapFactory.decodeFile(cacheFile.getAbsolutePath());
}
throw new NetworkErrorException("訪問服務器出錯:" + code);
}
// 在背景執行緒寫入圖片快取
private void writeCache(final File cacheFile, final Bitmap bm) {
new Thread() {
public void run() {
try {
FileOutputStream fos = new FileOutputStream(cacheFile);
bm.compress(CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
};
}.start();
}
}
六、博客服務 BlogService(HTTP + XML 解析)
package cn.itcast.blog;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import android.accounts.NetworkErrorException;
import android.util.Xml;
public class BlogService {
public List<Blog> getBlogs() throws Exception {
// 1. 指定伺服器位址
URL url = new URL("https://192.168.1.126/Myweb/blogs.xml");
// 2. 開啟連線並設定逾時
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
// 3. 判斷回應碼
int code = conn.getResponseCode();
if (code == 200) {
return parseBlog(conn.getInputStream());
}
throw new NetworkErrorException("連接失敗:" + code);
}
private List<Blog> parseBlog(InputStream inputStream) throws Exception {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(inputStream, "UTF-8");
List<Blog> blogs = new ArrayList<Blog>();
Blog blog = null;
for (int type = parser.getEventType();
type != XmlPullParser.END_DOCUMENT;
type = parser.next()) {
if (type == XmlPullParser.START_TAG) {
if ("blog".equals(parser.getName())) {
blog = new Blog();
blogs.add(blog);
} else if ("portrait".equals(parser.getName())) {
blog.setPortrait(parser.nextText());
} else if ("name".equals(parser.getName())) {
blog.setName(parser.nextText());
} else if ("content".equals(parser.getName())) {
blog.setContent(parser.nextText());
} else if ("pic".equals(parser.getName())) {
blog.setPic(parser.nextText());
} else if ("from".equals(parser.getName())) {
blog.setFrom(parser.nextText());
}
}
}
return blogs;
}
}
七、工具類別 Util
package cn.itcast.blog;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Util {
public static byte[] read(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
return baos.toByteArray();
}
}
八、伺服器端 XML 範例
<?xml version="1.0" encoding="UTF-8"?>
<blogs>
<blog>
<portrait>https://192.168.1.126/Myweb/b1.jpg</portrait>
<name>QQ音樂</name>
<content>問自己一個問題:既然 1+2 等於 2+1,那麼 I love you 是否等於 you love me?</content>
<pic>https://192.168.1.126/Myweb/b2.jpg</pic>
<from>來自 QQ空間說說</from>
</blog>
<blog>
<portrait>https://192.168.1.126/Myweb/portrait2.jpeg</portrait>
<name>江南小丑</name>
<content>為什麼總感覺還會再見到你?既然走了為什麼再回來?</content>
<from>來自 QQ空間說說</from>
</blog>
<blog>
<portrait>https://192.168.1.126/Myweb/portrait3.jpeg</portrait>
<name>美食廣場</name>
<content>好誘人的美食哦,你要不要嘗嘗?</content>
<pic>https://192.168.1.126/Myweb/content1.jpeg</pic>
<from>來自騰訊微博</from>
</blog>
</blogs>
實作要點回顧
1、圖片一律走快取策略:以「HTTP 條號比對(If-Modified-Since)」搭配 304 判斷,命中快取時完全不重新下載,這在 ListView 反覆捲動的情境下省下大量流量。
2、快取寫檔一定要另開執行緒,否則會卡住 UI。
3、getView() 中重用 convertView,避免每捲動一次就重新 inflate 版面。
4、别忘了在 AndroidManifest.xml 加上 android.permission.INTERNET 權限,並把範例中的內網 IP 換成你自己的伺服器位址。
用 MediaPlayer 實作 Android 音樂播放器(含進度條與 ±5 秒跳轉)
要在 App 裡播放一段音樂,Android 給了你不少選擇,但最常被拿出來用的仍是 MediaPlayer。它把底層的播放服務包成一個好操作的物件,不論音樂是打包在 A
Android MediaPlayer 教學:打造可播放、暫停與快轉的音樂播放器
要在 App 裡播放音訊或影片,最直接的方式是使用 Android 內建的 MediaPlayer 類別。它封裝了底層的播放服務,讓你不必煩惱解碼細節,專心處理播放控制。
Android JSON 解析器:解析 JSON 並提取所需資訊
JSON 代表 JavaScript Object Notation。它是一種獨立的資料交換格式,也是 XML 的最佳替代品。本章介紹如何解析 JSON 檔案,並從中提取
Android 監聽應用安裝與卸載:BroadcastReceiver 兩種註冊方式實測
想知道裝置上何時裝了新 App、何時有 App 被移除?Android 提供了 PACKAGE_ADDED 與 PACKAGE_REMOVED 這兩個系統廣播,透過 Br