要更新前必须由后台接口提供服务器app的版本号名serviceVersionName和app下载链接downPath
添加权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
package com.czz.demo3_05;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
/**
* Created by czz on 2015/10/8.
* 应用更新
*/
public class UpdateUtils {
public static boolean cancelUpdate = false; // 取消更新
public static String downPath = "http://www.inetgoes.com/kangfangqu/app/kfq.apk";
private String mSavePath = ""; //下载的保存路径
private String mSaveName = "kfq.apk"; //apk保存的名称
public static String serviceVersionName = "3.0.1"; //服务器的应用版本号名称
public static String currentVersionName = "2.0.1"; //当前应用版本号名称
public Context mContext;
/* 更新进度条 */
private ProgressBar mProgress;
private Dialog mDownloadDialog;
/* 记录进度条数量 */
private int progress;
private static UpdateUtils mUpdateUtils;
private UpdateUtils(Context context) {
mContext = context;
}
public static UpdateUtils getInstance(Context context) {
if (mUpdateUtils == null) {
synchronized (UpdateUtils.class) {
if (mUpdateUtils == null)
mUpdateUtils = new UpdateUtils(context);
}
}
return mUpdateUtils;
}
/**
* 判断当前网络是否连接可用
*
* @param context 上下文
* @return boolean
*/
public boolean isNetworkAble(Context context) {
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager != null) {
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
return true;
}
}
return false;
}
/**
* 获取应用版本名称 例:2.0.1
*
* @param context
* @return
*/
public String getVersionName(Context context) {
String versionName = null;
try {
versionName = context.getPackageManager().getPackageInfo("com.inetgoes.fangdd", 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
/**
* 获取应用版本号 例:2
*
* @param context
* @return
*/
public int getVersionCode(Context context) {
int versionCode = 0;
try {
versionCode = context.getPackageManager().getPackageInfo("com.inetgoes.fangdd", 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}
/**
* 检查软件是否有更新版本
*
* @return
*/
public boolean isUpdate() {
currentVersionName = getVersionName(mContext);
if (serviceVersionName.length() == currentVersionName.length()) {
if (getCode(serviceVersionName) > getCode(currentVersionName)) {
return true;
}
}
return false;
}
/**
* 把应用版本号名称转化为整数 例:2.0.1 ---> 201
*
* @param versionName
* @return
*/
public int getCode(String versionName) {
String[] s = versionName.split("\\.");
if (s.length == 0)
return 0;
StringBuffer sb = new StringBuffer();
for (String c : s) {
sb.append(c);
}
return Integer.valueOf(sb.toString());
}
/**
* 显示软件更新对话框
*/
public void showNoticeDialog() {
// 构造对话框
AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.kfqAppThemeDialog);
builder.setTitle(R.string.update_title);
builder.setMessage(R.string.update_info);
// 更新
builder.setPositiveButton(R.string.update_updatebtn, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 异步下载
new DownLoadApkAsy().execute();
dialog.dismiss();
}
});
// 稍后更新
builder.setNegativeButton(R.string.update_later, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog noticeDialog = builder.create();
noticeDialog.show();
}
/**
* 显示软件下载对话框
*/
public void showDownloadDialog() {
// 构造软件下载对话框
AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.kfqAppThemeDialog);
builder.setTitle(R.string.updating);
// 给下载对话框增加进度条
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.update_progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
builder.setView(v);
// 取消更新
builder.setNegativeButton(R.string.update_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// 设置取消状态
cancelUpdate = true;
}
});
mDownloadDialog = builder.create();
mDownloadDialog.show();
}
public void loadapk(){
new DownLoadApkAsy().execute();
}
private class DownLoadApkAsy extends AsyncTask<String, Integer, Boolean> {
@Override
protected Boolean doInBackground(String... params) {//软件下载
InputStream is = null;
FileOutputStream fos = null;
// 判断SD卡是否存在,并且是否具有读写权限
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
mSavePath = Environment.getExternalStorageDirectory() + "/" + "Download";
try {
URL url = new URL(downPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK){
int fileSize = conn.getContentLength();//获取文件大小
is = conn.getInputStream();
File file = new File(mSavePath);
if (!file.exists()) {
file.mkdir();
}
File apkFile = new File(mSavePath, mSaveName);
fos = new FileOutputStream(apkFile);
int count = 0;
byte[] buf = new byte[4 * 1024]; //缓存
do {
int numread = is.read(buf);
count += numread;
progress = (int) (((float) count / fileSize) * 100);
onProgressUpdate(progress);// 更新进度
if (numread <= 0) {
return true;// 下载完成
}
// 写入文件
fos.write(buf, 0, numread);
} while (!cancelUpdate);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return false;
}
@Override
protected void onPreExecute() {
//显示软件下载对话框
showDownloadDialog();
}
@Override
protected void onProgressUpdate(Integer... values) {
//进度条更新
mProgress.setProgress(values[0]);
}
@Override
protected void onPostExecute(Boolean aBoolean) {
mDownloadDialog.dismiss();
if (aBoolean){
installApk();//软件安装
}
}
}
/**
* 安装APK文件
*/
private void installApk() {
File apkfile = new File(mSavePath, mSaveName);
if (!apkfile.exists()) {
return;
}
// 通过Intent安装APK文件
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
mContext.startActivity(i);
}
}