废话就不说了,直接上代码:
case R.id.ll_gx://点击检查更新按钮
get();//http协议get请求
break;
//获取服务器版本号并比较版本号是否相同(这里下载链接URL和服务器版本号都是写在json中)
private void get(){
new Thread(){
@Override
public void run() {
super.run();
Looper.prepare();
String str=loginGet(mUrl);//get请求
try {
JSONObject jsonObject=new JSONObject(str);
url=jsonObject.getString("anzhuo");//服务器版本更新地址
updateVersion=jsonObject.getString("version");//服务器版本号
if (updateVersion.equals(getVersionName())){//版本相同
showDialog();
}else{//版本不同
Message msg = new Message();
msg.what = UPDATA_CLIENT;
handler.sendMessage(msg);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
// 待处理
Message msg = new Message();
msg.what = GET_UNDATAINFO_ERROR;
handler.sendMessage(msg);
e.printStackTrace();
}
Looper.loop();
}
}.start();
}
//get请求
private String loginGet(String url) {
StringBuffer buffer=null;
try {
URL mUrl=new URL(url);//实例化url
HttpURLConnection conn= (HttpURLConnection) mUrl.openConnection();//打开链接
BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));//获取输入流
String line=null;
buffer=new StringBuffer();
while((line=reader.readLine())!=null){
buffer.append(line);
}
reader.close();//关闭流
conn.disconnect();//断开连接
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("-------------------->",buffer.toString());
return buffer==null? "":buffer.toString().trim();
}
/*
* 获取当前程序的版本号
*/
private String getVersionName() throws Exception{
//获取packagemanager的实例
PackageManager packageManager = getPackageManager();
//getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
return packInfo.versionName;
}
//从服务器下载apk
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 ;
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;
}
}
//检测到新版本弹窗提醒是否更新
protected void showUpdataDialog() {
android.app.AlertDialog.Builder builder=new android.app.AlertDialog.Builder(this);
builder.setTitle("检查更新");
builder.setMessage("检查到新版本,是否立即更新?");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
downLoadApk();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
/*
* 从服务器中下载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(url, pd);
sleep(3000);
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");
startActivity(intent);
}
/*
* 进入程序的主界面
*/
private void LoginMain(){
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
//结束掉当前的activity
this.finish();
}
//检测到是最新版本弹窗提醒
private void showDialog() {
android.app.AlertDialog.Builder builder=new android.app.AlertDialog.Builder(this);
builder.setTitle("检查更新");
builder.setMessage("当前已是最新版本");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
//处理事件
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case UPDATA_CLIENT:
//对话框通知用户升级程序
showUpdataDialog();
break;
case GET_UNDATAINFO_ERROR:
//服务器超时
Toast.makeText(getApplicationContext(), "获取服务器更新信息失败", Toast.LENGTH_SHORT).show();
LoginMain();
break;
case DOWN_ERROR:
//下载apk失败
Toast.makeText(getApplicationContext(), "下载新版本失败", Toast.LENGTH_SHORT).show();
LoginMain();
break;
}
};
};