package com.android;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.xmlpull.v1.XmlPullParser;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;
public class UpdateVersion {
public final String TAG = this.getClass().getName();
public final static int UPDATA_NONEED = 0;
public final static int UPDATA_CLIENT = 1;
public final static int GET_UNDATAINFO_ERROR = 2;
public final static int SDCARD_NOMOUNTED = 3;
public final static int DOWN_ERROR = 4;
private Context mContext;
private UpdataInfo info;
private String localVername;
private int localVerCode = -1;
private CheckVersionTask cv;
private Thread mThread;
private DownCallBack mCallBack;
public UpdateVersion(Context mContext,DownCallBack callBack) {
super();
this.mContext = mContext;
this.mCallBack = callBack;
}
public void start(){
try {
localVername = getVersionName(mContext);
localVerCode = getVerCode(mContext);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cv = new CheckVersionTask();
// new Thread(cv).start();
mThread = new Thread(cv);
mThread.start();
}
private InputStream readAssets(){
AssetManager assetManager = mContext.getAssets();
String[] files = null;
try {
files = assetManager.list("ver");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
InputStream inputStream = null;
try {
inputStream = assetManager.open("version.xml");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return inputStream;
}
/*
* 从服务器获取xml解析并进行比对版本号
*/
public class CheckVersionTask implements Runnable {
public void run() {
try {
// 从资源文件获取服务器 地址
String path = mContext.getResources().getString(R.string.url_server);
// 包装成url的对象
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(5000);
InputStream is = readAssets();//conn.getInputStream();
info = getUpdataInfo(is);
if (Integer.parseInt(info.getVercode()) > localVerCode) {
Log.i(TAG, "版本号不同 ,提示用户升级 ");
Message msg = new Message();
msg.what = UPDATA_CLIENT;
handler.sendMessage(msg);
} else {
/*(info.getVername().equals(localVername))*/
Log.i(TAG, "版本号相同无需升级");
Message msg = new Message();
msg.what = UPDATA_NONEED;
handler.sendMessage(msg);
// LoginMain();
}
} catch (Exception e) {
// 待处理
Message msg = new Message();
msg.what = GET_UNDATAINFO_ERROR;
handler.sendMessage(msg);
e.printStackTrace();
}
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case UPDATA_NONEED:
showDialog();
mCallBack.onDownCallBack(UPDATA_NONEED, "版本号相同无需升级");
break;
case UPDATA_CLIENT:
// 对话框通知用户升级程序
// Toast.makeText(getApplicationContext(), "可以升级程序啦~",
// 1).show();
showUpdataDialog();
break;
case GET_UNDATAINFO_ERROR:
// 服务器超时
mCallBack.onDownCallBack(GET_UNDATAINFO_ERROR, "获取服务器更新信息失败");
// LoginMain();
break;
case SDCARD_NOMOUNTED:
// sdcard不可用
mCallBack.onDownCallBack(SDCARD_NOMOUNTED, "SD卡不可用");
break;
case DOWN_ERROR:
// 下载apk失败
mCallBack.onDownCallBack(DOWN_ERROR, "下载新版本失败");
// LoginMain();
break;
}
}
};
/*
*
* 弹出对话框通知用户更新程序
*
* 弹出对话框的步骤: 1.创建alertDialog的builder. 2.要给builder设置属性, 对话框的内容,样式,按钮
* 3.通过builder 创建一个对话框 4.对话框show()出来
*/
protected void showUpdataDialog() {
AlertDialog.Builder builer = new Builder(mContext);
builer.setTitle("版本升级");
builer.setMessage("当前版本:"+localVername + ",发现新版本:" + info.getVername() + ", 是否更新");
// 当点确定按钮时从服务器上下载 新的apk 然后安装
builer.setPositiveButton("更新", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.i(TAG, "下载apk,更新");
downLoadApk();
}
});
// 当点取消按钮时进行登录
builer.setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
// LoginMain();
}
});
AlertDialog dialog = builer.create();
dialog.show();
}
/*
*
* 弹出对话框通知用户意识最新
*
*/
protected void showDialog() {
AlertDialog.Builder builer = new Builder(mContext);
builer.setTitle("温馨提示");
builer.setMessage("您的版本已经是最新的了!");
// 当点取消按钮时进行登录
builer.setNegativeButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
AlertDialog dialog = builer.create();
dialog.show();
}
/*
* 从服务器中下载APK
*/
protected void downLoadApk() {
final ProgressDialog pd; // 进度条对话框
pd = new ProgressDialog(mContext);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("正在下载更新");
pd.setCanceledOnTouchOutside(false);
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Message msg = new Message();
msg.what = SDCARD_NOMOUNTED;
handler.sendMessage(msg);
} else {
pd.show();
new Thread() {
@Override
public void run() {
try {
File file = getFileFromServer(
info.getUrl(), pd);
sleep(1000);
installApk(file);
pd.dismiss(); // 结束掉进度条对话框
} catch (Exception e) {
Message msg = new Message();
msg.what = DOWN_ERROR;
handler.sendMessage(msg);
e.printStackTrace();
}
}
}.start();
}
}
// 安装apk
protected void installApk(File file) {
Intent intent = new Intent();
// 执行动作
intent.setAction(Intent.ACTION_VIEW);
// 执行的数据类型
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
mContext.startActivity(intent);
}
/**
* 从服务器下载apk
* @param path
* @param pd
* @return
* @throws Exception
*/
public static 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 ;
i