版本更新的点击事件
public void update(View v) {
dialog = new AlertDialog.Builder(MainActivity.this).setTitle("软件版本更新")
.setPositiveButton("确定", onclick)
.setNegativeButton("以后再说", null).create();
// 开启线程检查版本信息
new Thread(new CheckVersionTask()).start();
}
确定onclick点击事件
/**
* 立即更新的监听
*/
DialogInterface.OnClickListener onclick = new DialogInterface.OnClickListener() {
* 立即更新的监听
*/
DialogInterface.OnClickListener onclick = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
handler.sendEmptyMessage(1);
public void onClick(DialogInterface dialog, int which) {
handler.sendEmptyMessage(1);
}
};
};
线程中的CheckVersionTask()方法
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();
bean = UpdateTools.getUpdateBean(is);
// 当前版本号
int versionCode = MainActivity.this.getPackageManager()
.getPackageInfo(MainActivity.this.getPackageName(), 0).versionCode;
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();
bean = UpdateTools.getUpdateBean(is);
// 当前版本号
int versionCode = MainActivity.this.getPackageManager()
.getPackageInfo(MainActivity.this.getPackageName(), 0).versionCode;
if (Integer.parseInt(bean.getVersionCode()) <= versionCode) {
Log.i("xxx", "版本号相同无需升级");
} else {
Log.i("xxxx", "版本号不同 ,提示用户升级 ");
handler.sendEmptyMessage(0);
Log.i("xxx", "版本号相同无需升级");
} else {
Log.i("xxxx", "版本号不同 ,提示用户升级 ");
handler.sendEmptyMessage(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Handler中下载APK包
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 1) {
downLoadApk();
}
if(msg.what==0){
dialog.setMessage(bean.getUpdateLog());
dialog.show();
}
};
};
public void handleMessage(android.os.Message msg) {
if (msg.what == 1) {
downLoadApk();
}
if(msg.what==0){
dialog.setMessage(bean.getUpdateLog());
dialog.show();
}
};
};
downLoadApk方法
/*
* 从服务器中下载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(bean.getDownloadUrl(), pd);
sleep(3000);
* 从服务器中下载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(bean.getDownloadUrl(), pd);
sleep(3000);
UpdateTools tools = new UpdateTools();
// 安装APk
tools.installApk(file, MainActivity.this);
pd.dismiss(); // 结束掉进度条对话框
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
// 安装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;
}
}
* 下载方法
*
* @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;
}
}
解析更新的数据和安装的方法
public static UpdateBean getUpdateBean(InputStream is) throws Exception {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(is, "utf-8");// 设置解析的数据源
int type = parser.getEventType();
UpdateBean info = new UpdateBean();// 实体
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()); // 获取要升级的APK文件
} else if ("updateLog".equals(parser.getName())) {
info.setUpdateLog(parser.nextText()); // 获取该文件的信息
}
break;
}
type = parser.next();
}
XmlPullParser parser = Xml.newPullParser();
parser.setInput(is, "utf-8");// 设置解析的数据源
int type = parser.getEventType();
UpdateBean info = new UpdateBean();// 实体
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()); // 获取要升级的APK文件
} else if ("updateLog".equals(parser.getName())) {
info.setUpdateLog(parser.nextText()); // 获取该文件的信息
}
break;
}
type = parser.next();
}
return info;
}
// 安装apk
public static 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");// 编者按:此处Android应为android,否则造成安装不了
context.startActivity(intent);
};
public static 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");// 编者按:此处Android应为android,否则造成安装不了
context.startActivity(intent);
};
权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />