这里是给大家简单实现安卓版本更新的一个Demo
以下就是版本更新的全部代码
注:加上网络权限和SD卡读写权限
这里是MainActivity的代码,仅仅只是点击事件调用检查更新方法
<span style="color:#666666;">package com.bwie.updatev;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void update(View v){
UpdateVersionutil.getUpdataManger(this).checkUpdata();
}
}</span><span style="color:#ff0000;">
</span>
这里是ManiActivity的布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="更新"
android:onClick="update" />
</RelativeLayout>
接下来就是重点了
这里贴出的就是解析服务器返回信息的实体类
package com.bwie.updatev;
import java.io.Serializable;
import java.util.ArrayList;
public class UpdataInfo implements Serializable{
public Update_Data data;
}
<span style="color:#333333;">package com.bwie.updatev;
public class Update_Data {
public String description;
public String forcibly;
public String last_version;
public String needUpdate;
public String url;
public String version_Name;
public Update_Data(String description, String forcibly,
String last_version, String needUpdate, String url,
String version_Name) {
super();
this.description = description;
this.forcibly = forcibly;
this.last_version = last_version;
this.needUpdate = needUpdate;
this.url = url;
this.version_Name = version_Name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getForcibly() {
return forcibly;
}
public void setForcibly(String forcibly) {
this.forcibly = forcibly;
}
public String getLast_version() {
return last_version;
}
public void setLast_version(String last_version) {
this.last_version = last_version;
}
public String getNeedUpdate() {
return needUpdate;
}
public void setNeedUpdate(String needUpdate) {
this.needUpdate = needUpdate;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getVersion_Name() {
return version_Name;
}
public void setVersion_Name(String version_Name) {
this.version_Name = version_Name;
}
}
</span>
紧接着是解析服务器信息的方法
<span style="color:#666666;">package com.bwie.updatev;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import com.google.gson.Gson;
/**
* 版本更新数据转换解析
* @author Administrator
* @date 2016-7-12
*
*/
public class UpdataInfoParserUtil {
/**
* 用于解析版本更新的数据流,返回版本更新的对象那个
* @param is
* @return
*/
public static UpdataInfo getUpdataInfo(InputStream is) {
// TODO Auto-generated method stub
String parseInputStream = parseInputStream(is);
System.out.println(parseInputStream);
Gson g=new Gson();
UpdataInfo fromJson = g.fromJson(parseInputStream, UpdataInfo.class);
return fromJson;
}
/**
* 将数据输入流转换为字符串
* @param is
* @return
*/
private static String parseInputStream(InputStream is) {
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int len=0;
byte[] b=new byte[1024];
try {
while((len=is.read(b))!=-1){
baos.write(b, 0, len);
}
return baos.toString("UTF-8").trim();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}</span><span style="color:#ff0000;">
</span>
最后重中之重就是这里了
package com.bwie.updatev;
import java.io.BufferedInputStream;
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.URL;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
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.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
/**
* 更新版本的工具类
* @author Administrator
* @date 2016-7-11
*
*/
public class UpdateVersionutil {
private final String TAG = this.getClass().getName();
private final int UPDATA_NONEED = 0;
private final int UPDATA_CLIENT = 1;
private final int GET_UNDATAINFO_ERROR = 2;
private final int SDCARD_NOMOUNTED = 3;
private final int DOWN_ERROR = 4;
private Button getVersion;
private static UpdataInfo info;
private String localVersion;
public static Context mContext;
private static UpdateVersionutil updateVersionutil;
public static boolean mNeedUpdate;
public UpdateVersionutil(Context mContext) {
super();
this.mContext = mContext;
}
public void startUpdate(){
localVersion = getVersionName();
CheckVersionTask cv = new CheckVersionTask();
new Thread(cv).start();
}
public static UpdateVersionutil getUpdataManger(Context context){
if(updateVersionutil==null){
updateVersionutil=new UpdateVersionutil(context);
}
return updateVersionutil;
}
public static void checkUpdata(){
updateVersionutil.startUpdate();
}
private String getVersionName() {
//getPackageName()是你当前类的包名,0代表是获取版本信息
PackageManager packageManager =mContext.getPackageManager();
PackageInfo packInfo = null;
try {
packInfo = packageManager.getPackageInfo(mContext.getPackageName(),
0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return packInfo.versionName;
}
public class CheckVersionTask implements Runnable {
InputStream is;
public void run() {
try {
URL url = new URL("http://m.yunifang.com/yunifang/mobile/version?random=67603&encode=e441af3089cbeeb6b58ac72393a66667&clientType=android&clientVersion=10000");
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
// 从服务器获得一个输入流
is = conn.getInputStream();
}
info = UpdataInfoParserUtil.getUpdataInfo(is);
Url = info.data.getUrl();
System.out.println("新版版本名:"+info.data.getVersion_Name());
System.out.println("本地版本名:"+localVersion);
if (info.data.getVersion_Name().equals(localVersion)) {
mNeedUpdate=false;
Log.i(TAG, "版本号相同");
Message msg = new Message();
msg.what = UPDATA_NONEED;
handler.sendMessage(msg);
// LoginMain();
} else {
mNeedUpdate=true;
Log.i(TAG, "版本号不相同 ");
Message msg = new Message();
msg.what = UPDATA_CLIENT;
handler.sendMessage(msg);
}
} 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:
Toast.makeText(mContext, "不需要更新",
Toast.LENGTH_SHORT).show();
case UPDATA_CLIENT:
//对话框通知用户升级程序
showUpdataDialog();
break;
case GET_UNDATAINFO_ERROR:
//服务器超时
Toast.makeText(mContext, "获取服务器更新信息失败", 1).show();
break;
case DOWN_ERROR:
//下载apk失败
Toast.makeText(mContext, "下载新版本失败", 1).show();
break;
}
}
};
/*
*
* 弹出对话框通知用户更新程序
*
* 弹出对话框的步骤:
* 1.创建alertDialog的builder.
* 2.要给builder设置属性, 对话框的内容,样式,按钮
* 3.通过builder 创建一个对话框
* 4.对话框show()出来
*/
protected void showUpdataDialog() {
AlertDialog.Builder builer = new Builder(mContext);
builer.setTitle("版本升级");
builer.setMessage(info.data.getDescription());
//当点确定按钮时从服务器上下载 新的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
//do sth
}
});
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.show();
new Thread(){
@Override
public void run() {
try {
File file = DownLoadManager.getFileFromServer(info.data.getUrl(), 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");
mContext.startActivity(intent);
}
public static String Url;
public static String getUrl(){
return Url;
}
public static class DownLoadManager {
public static File getFileFromServer(String path, ProgressDialog pd) {
//如果相等的话表示当前的sdcard挂载在手机上并且是可用的
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
URL url = null;
try {
url = new URL(path);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.setConnectTimeout(5000);
//获取到文件的大小
pd.setMax(conn.getContentLength());
InputStream is = null;
try {
is = conn.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len ;
int total=0;
try {
while((len =bis.read(buffer))!=-1){
fos.write(buffer, 0, len);
total+= len;
//获取当前下载量
pd.setProgress(total);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
else{
return null;
}
}
}
}
好了,到这里,你就已经可以实现安卓的版本更新功能了,希望可以帮助到你
反馈QQ:1225089341