public class VersionUpdatingUtil {
private static final int TIMEOUT = 10 * 1000;public static File updateDir = null;
public static File updateFile = null;
/***
* 下载文件
*
* @return
* @throws MalformedURLException
*/
public void downloadUpdateFile(String down_url, String file)
throws Exception {
int down_step = 5;// 提示step
int totalSize;
int downloadCount = 0;// 已经下载好的大小
InputStream inputStream;
OutputStream outputStream;
URL url = new URL(down_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setConnectTimeout(TIMEOUT);
httpURLConnection.setReadTimeout(TIMEOUT);
// 获取下载文件的size
totalSize = httpURLConnection.getContentLength();
if (httpURLConnection.getResponseCode() == 404) {
throw new Exception("fail!");
}
inputStream = httpURLConnection.getInputStream();
outputStream = new FileOutputStream(file, false);// 文件存在则覆盖掉
byte buffer[] = new byte[1024];
int readsize = 0;
while ((readsize = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, readsize);
totalSize += readsize;// 时时获取下载到的大小
/**
* 没
*/
if (downloadCount == 0
|| (totalSize * 100 / totalSize - down_step) > downloadCount) {
}
}
}
/***
* 创建文件
*/
public static void createFile(String name) {
if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
.getExternalStorageState())) {
updateDir = new File(Environment.getExternalStorageDirectory()
+ "/" + App.downloadDir);
updateFile = new File(updateDir + "/" + name + ".apk");
if (!updateDir.exists()) {
updateDir.mkdirs();
}
if (!updateFile.exists()) {
try {
updateFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/***
* 检查是否更新版本
*/
public static void checkVersion(final Context context) {
if (!App.versionName.equals(MainActivity.version_Name)) {
// 发现新版本,提示用户更新
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("软件升级")
.setMessage(MainActivity.description)
.setPositiveButton("更新",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// 开启更新服务UpdateService
// 这里为了把update更好模块化,可以传一些updateService依赖的值
// 如布局ID,资源ID,动态获取的标题,这里以app_name为例
Intent updateIntent = new Intent(context,
UpdateService.class);
updateIntent.putExtra(
"app_name",
context.getResources().getString(
R.string.app_name));
context.startService(updateIntent);
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
alert.create().show();
} else {
Toast.makeText(context, "已是最新版本", Toast.LENGTH_LONG).show();
}
}
}