Phonegap 版本minSdkVersion为8的时候的自动更新与升级
清单文件中:
- <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8"/>
清单文件
在主窗口MainActivity中
- package fx.qj.xinjiangqj;
- import android.os.Bundle;
- import android.view.KeyEvent;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.widget.Toast;
- 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.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.Environment;
- import android.os.Handler;
- import android.os.Message;
- import android.util.Log;
- import org.apache.cordova.*;
- public class MainActivity extends DroidGap {
- private long exitTime = 0;
- String newVerName = "";//新版本名称
- int newVerCode = -1;//新版本号
- ProgressDialog pd = null;
- String UPDATE_SERVERAPK = "xx.apk";
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- super.init();
- android.webkit.WebSettings settings = super.appView.getSettings();
- String appCachePath = this.getCacheDir().getAbsolutePath();
- settings.setAppCachePath(appCachePath);
- settings.setAllowFileAccess(true);
- settings.setAppCacheEnabled(true);
- super.setIntegerProperty("splashscreen",R.drawable.startup_bg1);
- super.loadUrl("file:///android_asset/www/index.html",5000);
- updateVersion();
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_BACK) {
- exit();
- return false;
- }
- return super.onKeyDown(keyCode, event);
- }
- public void exit() {
- if ((System.currentTimeMillis() - exitTime) > 2000) {
- Toast.makeText(getApplicationContext(), "再按一次退出程序",
- Toast.LENGTH_SHORT).show();
- exitTime = System.currentTimeMillis();
- } else {
- finish();
- System.exit(0);
- }
- }
- public void updateVersion(){
- if(getServerVer()){
- int verCode = this.getVerCode(this);
- System.out.println(newVerCode);
- if(newVerCode>verCode){
- doNewVersionUpdate();//更新版本
- }else{
- //notNewVersionUpdate();//提示已是最新版本
- }
- }
- }
- public int getVerCode(Context context){
- int verCode = -1;
- try {
- String packName = context.getPackageName();
- verCode = context.getPackageManager().getPackageInfo(packName, 0).versionCode;
- } catch (NameNotFoundException e) {
- // TODO Auto-generated catch block
- Log.e("版本号获取异常", e.getMessage());
- }
- return verCode;
- }
- public String getVerName(Context context){
- String verName = "";
- try {
- String packName = context.getPackageName();
- verName = context.getPackageManager().getPackageInfo(packName, 0).versionName;
- } catch (NameNotFoundException e) {
- Log.e("版本名称获取异常", e.getMessage());
- }
- return verName;
- }
- public boolean getServerVer(){
- try {
- String path=getResources().getString(R.string.url_server);
- URL url = new URL(path);
- HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
- //httpConnection.setDoInput(true);
- //httpConnection.setDoOutput(true);
- //httpConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");
- httpConnection.setRequestMethod("GET");
- httpConnection.connect();
- InputStream inputStream = httpConnection.getInputStream();
- InputStreamReader reader = new InputStreamReader(inputStream);
- 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 true;//如果这里改为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(newVerCode);
- 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);
- String apkpath=getResources().getString(R.string.url_apk);
- downFile(apkpath);
- }
- })
- .setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- // TODO Auto-generated method stub
- //finish();
- }
- }).create();
- //显示更新框
- dialog.show();
- }
- public void downFile(final String url){
- pd.show();
- new Thread(){
- public void run(){
- HttpClient client = new DefaultHttpClient();
- HttpGet get = new HttpGet(url);
- HttpResponse response;
- System.out.println(url);
- 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();
- }
- };
- 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.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),UPDATE_SERVERAPK))
- , "application/vnd.android.package-archive");
- startActivity(intent);
- }
- }
在服务器上的js文件
- [{"verName":"xinjiangQJ","verCode":2}]
参考资料: http://blog.sina.com.cn/s/blog_5419658701014wg0.html
未测试的资料,使用xml存储数据:
http://blog.csdn.net/coolszy/article/details/7518345
http://blog.csdn.net/furongkang/article/details/6886526
Phonegap 版本minSdkVersion为8的时候的自动更新与升级的更多相关文章
- Android App版本自动更新
App在开发过程中,随着业务场景的不断增多,功能的不断完善,早期下载App的用户便无法体验最新的功能,为了能让用户更及时的体验App最新版本,在App开发过程加入App自动更新功能便显得尤为重要.更新 ...
- git 远程版本库,github提供服务原理,git自动更新发送邮件
1.安装好Linux,安装好Git(192.168.1.239) 2.创建一个用户zph(让此用户提供git on server),密码设置为12345678 # useradd zph # pass ...
- ASP.NET网站版本自动更新程序及代码[转]
1.自动更新程序主要负责从服务器中获取相应的更新文件,并且把这些文件下载到本地,替换现有的文件.达到修复Bug,更新功能的目的.用户手工点击更新按钮启动更新程序.已测试.2.环境VS2008,采用C# ...
- ios开发 数据库版本迁移手动更新迭代和自动更新迭代
数据库版本迁移顾名思义就是在原有的数据库中更新数据库,数据库中的数据保持不变对表的增.删.该.查. 数据持久化存储: plist文件(属性列表) preference(偏好设置) NSKeyedArc ...
- 批量自动更新SVN版本库 - Windows
开发过程中每天都要从SVN代码库里一个一个的update各个项目代码,不仅效率实在是低,也不符合程序员的"懒"精神,由于是在Windows环境做开发,自然就想到了使用bat来实现自 ...
- ios开发数据库版本迁移手动更新迭代和自动更新迭代艺术(二)
由于大家都热衷于对ios开发数据库版本迁移手动更新迭代和自动更新迭代艺术(一)的浏览下面我分享下我的源文件git仓库: 用法(这边我是对缓存的一些操作不需要可以省去):https://github.c ...
- iOS企业版使用第三方实现自动更新版本
1.获取本地版本和互联网版本 NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary]; N ...
- CS程序自动更新实现原理及代码(支持多版本多文件更新)
公司主要项目为CS端,经常遇到客户需求变更及bug处理,在没有引用自动更新之前每次更新程序,必须手动对每个客户端进行更新,这样导致技术支持工作量特别大,也给客户不好的印象,因此我需要一个自动更新程序! ...
- nvidia驱动自动更新版本后问题解决 -- failed to initialize nvml: driver/library version mismatch
因为必须关闭桌面窗口, 建议另外一台电脑ssh连接操作 1. 卸载旧版本并关闭图形界面 sudo apt-get remove --purge nvidia-\* sudo service light ...
随机推荐
- Maven 安装记
java初学者 昨天通m2e插件把maven项目导入eclipse的时候各种bug,看了各家技术博客,决定安装maven好好了解下. 安装maven也是一波三折的,先是看各种安装指导,结果环境变量都没 ...
- windows批处理命令之ren
1.批处理批量修改文件后缀名(假设我需要把一个文件夹中的很多txt文件改为sql文件): 1)在需要被处理的文件的文件夹里先新建一个txt文本,然后在文本中写入: ren *.txt *.sql 2) ...
- jQuery简单导航示例
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- Delphi-CompareText 函数
函数名称 CompareText 所在单元 System.SysUtils 函数原型 function CompareText(const S1, S2: string): Integer; 函数功能 ...
- C语言笔记(数组地址一些细节)
一.数组的a+1和&a+1的区别 先看看测试代码: ]={}; printf(" sizeof(data) = %d.\n", sizeof(data)); printf ...
- socket本地模拟UDP 服务器+客户端(三)
UDP: TCP是建立可靠连接,并且通信双方都可以以流的形式发送数据.相对TCP,UDP则是面向无连接的协议. 使用UDP协议时,不需要建立连接,只需要知道对方的IP地址和端口号,就可以直接发数据包. ...
- 转:Mongodb中随机的查询文档记录
简述,摘要:在实际应用场景中,几乎都会有随机获取数据记录的需求.而这个需求在Mongodb却不是很好实现,就目前而言,大致上有三种解决方案:1. 先计算出一个从0到记录总数之间的随机数,然后采用ski ...
- API Hook完全手册
文章来源: http://blog.csdn.net/atfield 原文作者: ATField 整理日期: 2008-07-16 发表评论 字体大小: 小 中 大 注:本文是根据我两年前写的一个 ...
- 使用 Spring Boot 快速构建 Spring 框架应用,PropertyPlaceholderConfigurer
Spring 框架对于很多 Java 开发人员来说都不陌生.自从 2002 年发布以来,Spring 框架已经成为企业应用开发领域非常流行的基础框架.有大量的企业应用基于 Spring 框架来开发.S ...
- 2015WF有感
World Final题目连接:http://icpc.baylor.edu/worldfinals/problems/icpc2015.pdf 建议:可以倒序阅读来获得最直观的赛场体验... 2:1 ...