截图如下:

代码实现如下:

package com.update.apk;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject; import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log; public class MainActivity extends Activity {
/** Called when the activity is first created. */
String newVerName = "";//新版本名称
int newVerCode = -1;//新版本号
ProgressDialog pd = null;
String UPDATE_SERVERAPK = "ApkUpdateAndroid.apk";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(getServerVer()){
int verCode = this.getVerCode(this);
if(newVerCode>verCode){
doNewVersionUpdate();//更新版本
}else{
notNewVersionUpdate();//提示已是最新版本
}
}
} /**
* 获得版本号
*/
public int getVerCode(Context context){
int verCode = -1;
try {
verCode = context.getPackageManager().getPackageInfo("com.update.apk", 0).versionCode;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
Log.e("版本号获取异常", e.getMessage());
}
return verCode;
} /**
* 获得版本名称
*/
public String getVerName(Context context){
String verName = "";
try {
verName = context.getPackageManager().getPackageInfo("com.update.apk", 0).versionName;
} catch (NameNotFoundException e) {
Log.e("版本名称获取异常", e.getMessage());
}
return verName;
} /**
* 从服务器端获得版本号与版本名称
* @return
*/
public boolean getServerVer(){
try {
URL url = new URL("http://10.0.2.2:8080/ApkUpdateService/ver");
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("GET");
httpConnection.connect();
InputStreamReader reader = new InputStreamReader(httpConnection.getInputStream());
BufferedReader bReader = new BufferedReader(reader);
String json = bReader.readLine();
JSONArray array = new JSONArray(json);
JSONObject jsonObj = array.getJSONObject(0);
newVerCode = Integer.parseInt(jsonObj.getString("verCode"));
newVerName = jsonObj.getString("verName");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
} /**
* 不更新版本
*/
public void notNewVersionUpdate(){
int verCode = this.getVerCode(this);
String verName = this.getVerName(this);
StringBuffer sb = new StringBuffer();
sb.append("当前版本:");
sb.append(verName);
sb.append(" Code:");
sb.append(verCode);
sb.append("\n已是最新版本,无需更新");
Dialog dialog = new AlertDialog.Builder(this)
.setTitle("软件更新")
.setMessage(sb.toString())
.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
}).create();
dialog.show();
} /**
* 更新版本
*/
public void doNewVersionUpdate(){
int verCode = this.getVerCode(this);
String verName = this.getVerName(this);
StringBuffer sb = new StringBuffer();
sb.append("当前版本:");
sb.append(verName);
sb.append(" Code:");
sb.append(verCode);
sb.append(",发现版本:");
sb.append(newVerName);
sb.append(" Code:");
sb.append(verCode);
sb.append(",是否更新");
Dialog dialog = new AlertDialog.Builder(this)
.setTitle("软件更新")
.setMessage(sb.toString())
.setPositiveButton("更新", new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("正在下载");
pd.setMessage("请稍后。。。");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
downFile("http://10.0.2.2:8080/ApkUpdateService/ApkUpdateAndroid.apk");
}
})
.setNegativeButton("暂不更新", new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
}).create();
//显示更新框
dialog.show();
} /**
* 下载apk
*/
public void downFile(final String url){
pd.show();
new Thread(){
public void run(){
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response;
try {
response = client.execute(get);
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
InputStream is = entity.getContent();
FileOutputStream fileOutputStream = null;
if(is != null){
File file = new File(Environment.getExternalStorageDirectory(),UPDATE_SERVERAPK);
fileOutputStream = new FileOutputStream(file);
byte[] b = new byte[1024];
int charb = -1;
int count = 0;
while((charb = is.read(b))!=-1){
fileOutputStream.write(b, 0, charb);
count += charb;
}
}
fileOutputStream.flush();
if(fileOutputStream!=null){
fileOutputStream.close();
}
down();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
} Handler handler = new Handler() { @Override
public void handleMessage(Message msg) { super.handleMessage(msg);
pd.cancel();
update();
}
}; /**
* 下载完成,通过handler将下载对话框取消
*/
public void down(){
new Thread(){
public void run(){
Message message = handler.obtainMessage();
handler.sendMessage(message);
}
}.start();
} /**
* 安装应用
*/
public void update(){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),UPDATE_SERVERAPK))
, "application/vnd.android.package-archive");
startActivity(intent);
}
}

from:http://www.cnblogs.com/shmily0703/archive/2012/04/19/shmily_apk_update.html

Android 版本自动更新的更多相关文章

  1. Android(2)—Mono For Android App版本自动更新

    0.前言 公司Android查询的项目已经开始,整体采用Java后台+App前台来实现,由于项目小,App这块就我一个人开发,首先需要研究的是:Android版本的更新升级问题:本人经过近一周的学习整 ...

  2. Android实现自动更新功能

    Android实现自动更新功能 Android自动更新的功能可以使用第三方的SDK来实现,但是类似友盟,就不支持x86手机的自动更新,科大讯飞,弹窗是全局的,小米手机就会默认把弹窗权限关掉不允许弹出提 ...

  3. Android应用自动更新功能的实现!

    Android应用自动更新功能的实现!http://blog.csdn.net/android_tutor/article/details/7015986 private static final i ...

  4. C#.Net版本自动更新程序及3种策略实现

    C#.Net版本自动更新程序及3种策略实现 C/S程序是基于客户端和服务器的,在客户机编译新版本后将文件发布在更新服务器上,然后建立一个XML文件,该文件列举最新程序文件的版本号及最后修改日期.如程序 ...

  5. Android App版本自动更新

    App在开发过程中,随着业务场景的不断增多,功能的不断完善,早期下载App的用户便无法体验最新的功能,为了能让用户更及时的体验App最新版本,在App开发过程加入App自动更新功能便显得尤为重要.更新 ...

  6. Android开发-自动更新

    为车机写apk,先实现版本的自动更新. 1.不能再主线程中调用会阻塞ui的功能,需要使用异步方式调用网络,引入Android Async Http框架,需要两个包:android-async-http ...

  7. Android应用自动更新功能的代码实现

    由于Android项目开源所致,市面上出现了N多安卓软件市场.为了让我们开发的软件有更多的用户使用,我们需要向N多市场发布,软件升级后,我们也必须到安卓市场上进行更新,给我们增加了工作量.因此我们有必 ...

  8. 使用七牛云存储实现Android的自动更新

    为了修复Bug或更新软件,我们通常需要实现自动更新,没有哪一个牛逼的人能够搞到每一个用户的机子去帮他们更新. 1.自动更新的流程 我们将了解一下自动更新的思路.既然软件要自动更新,那么它必须知道自己是 ...

  9. Android - 软件自动更新的实现

    转自:http://blog.csdn.net/wwj_748/article/details/8195565 接触到一个很实用的技术,那就是软件自动更新.一般开发者是通过自行在应用平台添加更新版本的 ...

随机推荐

  1. XEE介绍

    摘要: XMl Entity Expansion(攻击)某种程度上类似于 XML Entity Expansion,但是它主要试图通过消耗目标程序的服务器环境来进行DOS攻击的.这种攻击基于XML E ...

  2. Python性能分析指南

    http://www.admin10000.com/document/2861.html 尽管并非每个你写的Python程序都需要严格的性能分析,但了解一下Python的生态系统中很多优秀的在你需要做 ...

  3. POJ 1922 Ride to School(贪心+模拟)

    题意:起点与终点相隔4500米.现Charley 需要从起点骑车到终点.但是,他有个习惯,沿途需要有人陪伴,即以相同的速度, 与另外一个人一起骑.而当他遇到以更快的速度骑车的人时,他会以相应的速度跟上 ...

  4. POJ 1775

    #include <iostream> using namespace std; ,,,,,,,,,}; bool boo; void DFS(int time,int sum); int ...

  5. hdu 1352 I Conduit!

    计算几何,主要是排序问题,其他都很好做…… ;}

  6. dynamic介绍

    Visual C# 2010 引入了一个新类型 dynamic. 该类型是一种静态类型,但类型为 dynamic 的对象会跳过静态类型检查. 大多数情况下,该对象就像具有类型 object 一样. 在 ...

  7. 华为3C抢购难度

    上周小米2S降价到1299买了一个,今天突然想体验一下抢购红米和3C的难度.万一抢到了,拿到手机市场贵100块钱卖掉,然后可以请女神吃个饭~~~哈哈哈哈! 结果确实不怎么好抢.刚刚试了一下3C: 验证 ...

  8. [转]C++四种cast操作符

    http://blog.csdn.net/starryheavens/article/details/4617637 C 风格(C-style)强制转型如下: (T) expression 或 T(e ...

  9. Windows下获取高精度时间注意事项

    Windows下获取高精度时间注意事项 [转贴 AdamWu]   花了很长时间才得到的经验,与大家分享. 1. RDTSC - 粒度: 纳秒级 不推荐优势: 几乎是能够获得最细粒度的计数器抛弃理由: ...

  10. mysql shell

    mysql 查询10分钟以内的数据:select *from t_agent where int_last_login>=CURRENT_TIMESTAMP - INTERVAL 10 MINU ...