Android 版本自动更新
截图如下:
代码实现如下:

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 版本自动更新的更多相关文章
- Android(2)—Mono For Android App版本自动更新
0.前言 公司Android查询的项目已经开始,整体采用Java后台+App前台来实现,由于项目小,App这块就我一个人开发,首先需要研究的是:Android版本的更新升级问题:本人经过近一周的学习整 ...
- Android实现自动更新功能
Android实现自动更新功能 Android自动更新的功能可以使用第三方的SDK来实现,但是类似友盟,就不支持x86手机的自动更新,科大讯飞,弹窗是全局的,小米手机就会默认把弹窗权限关掉不允许弹出提 ...
- Android应用自动更新功能的实现!
Android应用自动更新功能的实现!http://blog.csdn.net/android_tutor/article/details/7015986 private static final i ...
- C#.Net版本自动更新程序及3种策略实现
C#.Net版本自动更新程序及3种策略实现 C/S程序是基于客户端和服务器的,在客户机编译新版本后将文件发布在更新服务器上,然后建立一个XML文件,该文件列举最新程序文件的版本号及最后修改日期.如程序 ...
- Android App版本自动更新
App在开发过程中,随着业务场景的不断增多,功能的不断完善,早期下载App的用户便无法体验最新的功能,为了能让用户更及时的体验App最新版本,在App开发过程加入App自动更新功能便显得尤为重要.更新 ...
- Android开发-自动更新
为车机写apk,先实现版本的自动更新. 1.不能再主线程中调用会阻塞ui的功能,需要使用异步方式调用网络,引入Android Async Http框架,需要两个包:android-async-http ...
- Android应用自动更新功能的代码实现
由于Android项目开源所致,市面上出现了N多安卓软件市场.为了让我们开发的软件有更多的用户使用,我们需要向N多市场发布,软件升级后,我们也必须到安卓市场上进行更新,给我们增加了工作量.因此我们有必 ...
- 使用七牛云存储实现Android的自动更新
为了修复Bug或更新软件,我们通常需要实现自动更新,没有哪一个牛逼的人能够搞到每一个用户的机子去帮他们更新. 1.自动更新的流程 我们将了解一下自动更新的思路.既然软件要自动更新,那么它必须知道自己是 ...
- Android - 软件自动更新的实现
转自:http://blog.csdn.net/wwj_748/article/details/8195565 接触到一个很实用的技术,那就是软件自动更新.一般开发者是通过自行在应用平台添加更新版本的 ...
随机推荐
- Even Fibonacci numbers
--Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting ...
- REST_FRAMEWORK加深记忆-加了API_ROOT及超链接的CASE
urls.py from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patter ...
- TDD三个阶段
TDD的三个阶段 红灯.绿灯.重构 :明确了实施TDD所要遵循的工作流 (需求--->测试-->代码[重构]) 红灯阶段: 为不存在的代码编写测试 绿灯阶段: 仅编写适 ...
- Windows JDK环境变量的配置
下载JDK:http://www.oracle.com/technetwork/java/javase/downloads/index.html 安装 计算机-->属性-->高级系统设置- ...
- 为什么开发者热衷在Stack Overflow上查阅API文档?
摘要:一项新研究跟踪了Android开发者的访问历史,发现开发者多达二分之一的文档是从Stack Overflow上获取到的,而Stack Overflow上的示例也多于官方指南,开发者通过搜索更多时 ...
- javascript基础之数组对象
一.定义数组的方法: 定义了一个空数组: var myArray =new Array(); 指定有n个空元素的数组: var myArray=new Array(n); 定义数组并赋值: var m ...
- 基于IDEA 最新Spirng3.2+hibernate4+struts2.3 全注解配置 登录
原文 基于IDEA 最新Spirng3.2+hibernate4+struts2.3 全注解配置 登录 首先说说 IDEA 12,由于myeclipse越来越卡,我改用idea12 了,发现其功能强悍 ...
- ogre, dx, opengl坐标矩阵
opengl 右手坐标系 列向量 左乘 列主序存储矩阵osg 右手坐标系 行向量 右乘 行主序存储矩阵d3d 左手坐标系 行向量 右乘 行主序存储矩阵ogre 右手坐标系 列向量 ...
- ACM - ICPC World Finals 2013 B Hey, Better Bettor
原题下载:http://icpc.baylor.edu/download/worldfinals/problems/icpc2013.pdf 这题真心的麻烦……程序不长但是推导过程比较复杂,不太好想 ...
- 函数fsp_alloc_from_free_frag
/**********************************************************************//** Allocates a single free ...