android 版本更新

1.先创建个辅助类,封装获取当前软件版本号和版本名称(一般只需要获取版本号,进行版本号比对)

// 获取软件版本号
public static int getVerCode(Context context) {
int verCode = -1;
try {
verCode = context.getPackageManager().getPackageInfo("", 0).versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return verCode;
}


// 获取软件版本名称
public static String getVerName(Context context) {
String verName = "";
try {
verName = context.getPackageManager().getPackageInfo("", 0).versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return verName;


}

2.创建个 AsyncTask的子类,重写doInBackground()方法 (此方法运行在工作线程中,不会阻塞主线程)和onPostExecute()方法(此方法与运行在主线程,当doInBackground()执行完成后的结果会作为onPostExecute()de参数),在doInBackground()中先创建个方法判断是否有新的版本,将结果返还给onPostExecute(),如果没有就弹出个dialog或者toast提示用户当前版本已经是最新版本,反之,则弹出可供用户选择“更新”和“暂不更新”的dialog,选择更新就像后台请求下载地址,获取下载地址保存到本地文件中,下载完成后就自动安装软件。


public class MainActivity extends Activity {
long newVerCode; // 最新版的版本号
String newVerName; // 最新版的版本名
String appName; // 下载到本地要给这个APP命的名字
private Handler mainHandler;
private ProgressDialog progressDlg;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainHandler = new Handler();
progressDlg = new ProgressDialog(this);
progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
progressDlg.setIndeterminate(false);
appName = "my.apk";
Button version = (Button) findViewById(R.id.btn_ver_update);
version.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
new checkNewestVersionAsyncTask().execute();
}
});
}


class checkNewestVersionAsyncTask extends AsyncTask<Void, Void, Boolean> {


protected Boolean doInBackground(Void... params) {
if (isNewVersion()) {// 是否有新的版本号


int verCode = CommonUpdate.getVerCode(getApplicationContext());


if (newVerCode > verCode) {// 有新版本
return true;
} else {// 没有新版本
return false;
}
}
return false;
}


@Override
protected void onPostExecute(Boolean result) {
if (result) {// 表示有新版本
doNewVersionUpdate(); // 更新新版本
} else {// 没有新版本
notNewVersionDlgShow(); // 提示当前为最新版本
}
super.onPostExecute(result);
}


}


/*
* 从服务器获取最新版本号,\获取成功为true,获取失败为false
*/


public boolean isNewVersion() {
// 发送post请求,获取最新版本号,如果获取失败newVerCode和newVerName清空下,将代码省略


return false;
}


public void notNewVersionDlgShow() {
AlertDialog dialog = new AlertDialog.Builder(getApplicationContext())
.setTitle("版本更新").setMessage("当前为最新版本")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();


}
}).create();
dialog.show();
}


public void doNewVersionUpdate() {
int verCode = CommonUpdate.getVerCode(getApplicationContext());
String verName = CommonUpdate.getVerName(getApplicationContext());


String str = "当前版本:" + verName + " Code:" + verCode + " ,发现新版本:"
+ newVerName + " Code:" + newVerCode + " ,是否更新?";
AlertDialog dialog = new AlertDialog.Builder(getApplicationContext())
.setTitle("软件更新")
.setMessage(str)
.setNegativeButton("暂不更新",
new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();


}
})
.setPositiveButton("更新", new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
progressDlg.setTitle("正在下载");
progressDlg.setMessage("请稍候...");
doFile("下载软件的地址");
}
}).create();
dialog.show();


}


// 向服务端发送请求,获取APK文件
private void doFile(final String url) {
progressDlg.show();
new Thread() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response;
try {
response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
progressDlg.setMax((int) length);// 设置进度条的最大值
InputStream is = entity.getContent();
FileOutputStream fileOutputStream = null;
if (is != null) {
File file = new File(
Environment.getExternalStorageDirectory(),
appName);
fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int ch = -1;
int count = 0;
while ((ch = is.read(buf)) != -1) {
fileOutputStream.write(buf, 0, ch);
count += ch;
if (length > 0) {
// 设置当前进度
progressDlg
.setProgress((int) (count * 100 / length));
}
}
}
fileOutputStream.flush();
if (fileOutputStream != null) {
fileOutputStream.close();
}
down();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}


// 告诉handler已经下载完成了
private void down() {
mainHandler.post(new Runnable() {
public void run() {
progressDlg.cancel();
update();
}
});
}


// 安装APK
public void update() {
Intent i = new Intent(Intent.ACTION_VIEW);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setDataAndType(Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), appName)),
"application/vnd.android.package-archive");
startActivity(i);
finish();


}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值