截图如下:

代码实现如下:

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. Eclipse Error: Unable to set localhost. This prevents creation of a GUID.

    Symptoms The following error appears in the atlassian-confluence.log: 2011-03-16 18:20:03,021 ERROR ...

  2. 2> How Struts 2 Works

    The first thing we should consider is that the workflow of figure 1.4 still obeys the sim- pler MVC ...

  3. What is the difference between database table and database view?

    The database table has a physical existence in the database. A view is a virtual table, that is one ...

  4. POJ 1740

    #include <iostream> #define MAXN 100 using namespace std; int _m[MAXN]; bool mark[MAXN]; int m ...

  5. 匿名用户访问sharepoint2010中的列表

    Allow anonymous users to access listitems on a publishing site in SharePoint 2010 https://knowledge. ...

  6. Hadoop-eclipse-plugin插件安装

    Hadoop-eclipse-plugin插件安装 学习Hadoop有一段时间了,以前每次的做法都是先在win下用eclipse写好Mapreduce程序,然后打成jar文件,上传到linux下用ha ...

  7. 【Linux高频命令专题(3)】uniq

    简述 用途 报告或删除文件中重复的行. 语法 uniq [ -c | -d | -u ] [ -f Fields ] [ -s Characters ] [ -Fields ] [ +Characte ...

  8. ADO.NET入门教程(三) 连接字符串,你小觑了吗?

    出处:http://www.cnblogs.com/liuhaorain/archive/2012/02/12/2347914.html 摘要 ADO.NET强大的优势在于对不同的数据源提供一致的访问 ...

  9. Linux之vi/vim命令

    vi命令是linux中必不可少的一个编辑器工具.那么vi与vim又有什么区别呢,可以简单理解为vim是vi的升级版.在编辑一个文本时,vi不会显示颜色,而vim会显示颜色.显示颜色更易于用户进行编辑, ...

  10. 5、处理模型数据ModelAndView、Map、Model以及@SessionAttributes注解

    Spring MVC提供了以下几种途径输出模型数据 —— ModelAndView: 处理方法返回值类型为ModelAndView时,方法体即可通过该对象添加模型数据.数据会添加到request域中. ...