今天就来做一个版本更新的小例子,这个例子中也包含了xml数据的解析,使用listview展示,点击button提示版本更新,会完成下载
布局的话,使用正常的listview控件,增加一个button按钮
<RelativeLayout 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"
>
<Button
android:layout_alignParentRight="true"
android:id="@+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="检测新版本"
/>
<ListView
android:id="@+id/main_lv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btn_update"
></ListView>
</RelativeLayout>
item页面也是简单的写了三个TextView来展示
<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="标题" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="作者" />
<TextView
android:id="@+id/pubDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="更新日期" />
</LinearLayout>
</LinearLayout>
接下来 根据接收到的更新地址
http://www.oschina.net/MobileAppVersion.xml
得到更新需要的数据,创建Entity类 UpdateEntity
package com.bwie.test.bean;
public class UpdateEntity {
//版本号
public String versionCode;
//下载地址
public String downloadUrl;
//更新描述
public String updateLog;
public String getVersionCode() {
return versionCode;
}
public void setVersionCode(String versionCode) {
this.versionCode = versionCode;
}
public String getDownloadUrl() {
return downloadUrl;
}
public void setDownloadUrl(String downloadUrl) {
this.downloadUrl = downloadUrl;
}
public String getUpdateLog() {
return updateLog;
}
public void setUpdateLog(String updateLog) {
this.updateLog = updateLog;
}
}
创建简单的listview新闻界面展示的实体类 News
package com.bwie.test;
public class News {
public String title;
public String author;
public String pubDate;
}
适配器类MyAdapter 对数据进行适配
public class MyAdapter extends BaseAdapter {
Context context;
List<News> list;
public MyAdapter(Context context, List<News> list) {
super();
this.context = context;
this.list = list;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup arg2) {
ViewHolder holder=null;
//优化ListView
if(convertView==null){
convertView=View.inflate(context, R.layout.item_list, null);
holder=new ViewHolder();
holder.title=(TextView) convertView.findViewById(R.id.title);
holder.author=(TextView) convertView.findViewById(R.id.author);
holder.pubDate=(TextView) convertView.findViewById(R.id.pubDate);
convertView.setTag(holder);
}else{
holder=(ViewHolder) convertView.getTag();
}
holder.title.setText(list.get(position).title);
holder.author.setText(list.get(position).author);
holder.pubDate.setText(list.get(position).pubDate);
return convertView;
}
// 优化类
class ViewHolder {
TextView title;
TextView author;
TextView pubDate;
}
}
配置版本更新的工具类,在这里集成了版本更新的方法和apk安装方法
UpdateUtil
public class UpdateUtil {
// 用pull 解析器解析服务器返回的xml文件(xml封装了版本号)
public static UpdateEntity getUpdateInfo(InputStream is) throws Exception {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(is, "utf-8");
int type = parser.getEventType();
UpdateEntity info = new UpdateEntity();
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_TAG:
if ("versionCode".equals(parser.getName())) {
info.setVersionCode(parser.nextText());
} else if ("downloadUrl".equals(parser.getName())) {
info.setDownloadUrl(parser.nextText());
} else if ("updateLog".equals(parser.getName())) {
info.setUpdateLog(parser.nextText());
}
break;
}
type = parser.next();
}
return info;
}
// 安装apk
public void installApk(File file, Context context) {
Intent intent = new Intent();
// 执行动作
intent.setAction(Intent.ACTION_VIEW);
// 执行的数据类型
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
context.startActivity(intent);
}
}
接下来 写一下MainActivity的执行逻辑
public class MainActivity extends Activity {
private AlertDialog dialog;
private Button btnUpdate;
private ListView lv;
private String path1 = "http://www.oschina.net/action/api/news_list?catalog=1&pageIndex=0&pageSize=20";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 找控件
btnUpdate = (Button) findViewById(R.id.btn_update);
lv = (ListView) findViewById(R.id.main_lv);
// 解析数据
getData();
// 设置版本更新的监听
btnUpdate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = new AlertDialog.Builder(MainActivity.this)
.setTitle("软件版本更新").setPositiveButton("立即更新", onclick)
.setNegativeButton("以后再说", null).create();
// 开启线程检查版本信息
new Thread(new CheckVersionTask()).start();
}
});
}
/**
* 版本更新的Hnadler
*/
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0:
dialog.setMessage(updateEntity.getUpdateLog());
dialog.show();
break;
case 1:
downLoadApk();
break;
}
};
};
/*
* 从服务器中下载APK
*/
protected void downLoadApk() {
final ProgressDialog pd; // 进度条对话框
pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("正在下载更新");
pd.show();
new Thread() {
@Override
public void run() {
try {
File file = getFileFromServer(
updateEntity.getDownloadUrl(), pd);
sleep(3000);
UpdateUtil tools = new UpdateUtil();
// 安装APk
tools.installApk(file, MainActivity.this);
pd.dismiss(); // 结束掉进度条对话框
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
/**
* 下载方法
*
* @param path
* @param pd
* @return
* @throws Exception
*/
public File getFileFromServer(String path, ProgressDialog pd)
throws Exception {
// 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
// 获取到文件的大小
pd.setMax(conn.getContentLength());
InputStream is = conn.getInputStream();
File file = new File(Environment.getExternalStorageDirectory(),
"updata.apk");
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len;
int total = 0;
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
total += len;
// 获取当前下载量
pd.setProgress(total);
}
fos.close();
bis.close();
is.close();
return file;
} else {
return null;
}
}
/*
* 从服务器获取xml解析并进行比对版本号
*/
private UpdateEntity updateEntity;
public class CheckVersionTask implements Runnable {
public void run() {
try {
// 从资源文件获取服务器 地址
String path = "http://www.oschina.net/MobileAppVersion.xml";
// 包装成url的对象
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(5000);
InputStream is = conn.getInputStream();
updateEntity = UpdateUtil.getUpdateInfo(is);
// 当前版本号
int versionCode = MainActivity.this.getPackageManager()
.getPackageInfo(MainActivity.this.getPackageName(), 0).versionCode;
if (Integer.parseInt(updateEntity.getVersionCode()) <= versionCode) {
Log.i("xxx", "版本号相同无需升级");
} else {
Log.i("xxxx", "版本号不同 ,提示用户升级 ");
handler.sendEmptyMessage(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 立即更新的监听
*/
DialogInterface.OnClickListener onclick = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
handler.sendEmptyMessage(1);
}
};
/**
* 请求数据的方法
*/
private void getData() {
new Thread() {
public void run() {
try {
// 使用HttpURLConnection解析数据
URL url = new URL(path1);
HttpURLConnection http = (HttpURLConnection) url
.openConnection();
http.setConnectTimeout(5000);
http.setReadTimeout(5000);
http.setRequestMethod("GET");
int responseCode = http.getResponseCode();
if (responseCode == 200) {
InputStream inputStream = http.getInputStream();
// 使用pull解析解析数据
XmlPullParser pullParser = Xml.newPullParser();
pullParser.setInput(inputStream, "UTF-8");
int eventType = pullParser.getEventType();// 产生第一个事件
while (eventType != XmlPullParser.END_DOCUMENT) {// 只要不是文档结束事件
String name = pullParser.getName();// 获取解析器当前指向的元素的名称
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<News>();
break;
case XmlPullParser.START_TAG:
if ("news".equals(name)) {
news = new News();
}
if (news != null) {
if ("title".equals(name)) {
news.title = pullParser.nextText();// 获取解析器当前指向元素的下一个文本节点的值
} else if ("author".equals(name)) {
news.author = pullParser.nextText();
} else if ("pubDate".equals(name)) {
news.pubDate = pullParser.nextText();
}
}
break;
case XmlPullParser.END_TAG:
if ("news".equals(name)) {
list.add(news);
news = null;
}
break;
}
eventType = pullParser.next();
}
// 把解析的数据发送到Handler中处理
mhandler.obtainMessage(1, list).sendToTarget();
}
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
// Handler
Handler mhandler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 1) {
// 接收数据
@SuppressWarnings("unchecked")
List<News> newsList = (List<News>) msg.obj;
// 为ListView设置适配器
MyAdapter adapter = new MyAdapter(MainActivity.this, newsList);
lv.setAdapter(adapter);
}
};
};
List<News> list = null;
News news = null;
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
}
}
以上 就是我对版本更新所做的一个简单的示例,希望通过这个示例能够对大家学习Android有所帮助