清单文件中:

  1. <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8"/>

清单文件

在主窗口MainActivity中

  1. package fx.qj.xinjiangqj;
  2. import android.os.Bundle;
  3.  
  4. import android.view.KeyEvent;
  5. import android.view.Menu;
  6. import android.view.MenuItem;
  7. import android.widget.Toast;
  8.  
  9. import java.io.BufferedReader;
  10. import java.io.File;
  11. import java.io.FileOutputStream;
  12. import java.io.InputStream;
  13. import java.io.InputStreamReader;
  14. import java.net.HttpURLConnection;
  15. import java.net.URL;
  16.  
  17. import org.apache.http.HttpEntity;
  18. import org.apache.http.HttpResponse;
  19. import org.apache.http.client.HttpClient;
  20. import org.apache.http.client.methods.HttpGet;
  21. import org.apache.http.impl.client.DefaultHttpClient;
  22. import org.json.JSONArray;
  23. import org.json.JSONObject;
  24. import android.app.AlertDialog;
  25. import android.app.Dialog;
  26. import android.app.ProgressDialog;
  27. import android.content.Context;
  28. import android.content.DialogInterface;
  29. import android.content.Intent;
  30. import android.content.pm.PackageManager.NameNotFoundException;
  31. import android.net.Uri;
  32. import android.os.Environment;
  33. import android.os.Handler;
  34. import android.os.Message;
  35. import android.util.Log;
  36. import org.apache.cordova.*;
  37.  
  38. public class MainActivity extends DroidGap {
  39. private long exitTime = 0;
  40. String newVerName = "";//新版本名称
  41. int newVerCode = -1;//新版本号
  42. ProgressDialog pd = null;
  43. String UPDATE_SERVERAPK = "xx.apk";
  44. @Override
  45. public void onCreate(Bundle savedInstanceState) {
  46. super.onCreate(savedInstanceState);
  47. super.init();
  48. android.webkit.WebSettings settings = super.appView.getSettings();
  49. String appCachePath = this.getCacheDir().getAbsolutePath();
  50. settings.setAppCachePath(appCachePath);
  51. settings.setAllowFileAccess(true);
  52. settings.setAppCacheEnabled(true);
  53. super.setIntegerProperty("splashscreen",R.drawable.startup_bg1);
  54. super.loadUrl("file:///android_asset/www/index.html",5000);
  55. updateVersion();
  56. }
  57.  
  58. @Override
  59. public boolean onCreateOptionsMenu(Menu menu) {
  60. // Inflate the menu; this adds items to the action bar if it is present.
  61. getMenuInflater().inflate(R.menu.main, menu);
  62. return true;
  63. }
  64. @Override
  65. public boolean onKeyDown(int keyCode, KeyEvent event) {
  66. if (keyCode == KeyEvent.KEYCODE_BACK) {
  67. exit();
  68. return false;
  69. }
  70. return super.onKeyDown(keyCode, event);
  71. }
  72.  
  73. public void exit() {
  74. if ((System.currentTimeMillis() - exitTime) > 2000) {
  75. Toast.makeText(getApplicationContext(), "再按一次退出程序",
  76. Toast.LENGTH_SHORT).show();
  77. exitTime = System.currentTimeMillis();
  78. } else {
  79. finish();
  80. System.exit(0);
  81. }
  82. }
  83.  
  84. public void updateVersion(){
  85. if(getServerVer()){
  86. int verCode = this.getVerCode(this);
  87. System.out.println(newVerCode);
  88. if(newVerCode>verCode){
  89. doNewVersionUpdate();//更新版本
  90. }else{
  91. //notNewVersionUpdate();//提示已是最新版本
  92. }
  93. }
  94. }
  95.  
  96. public int getVerCode(Context context){
  97. int verCode = -1;
  98. try {
  99. String packName = context.getPackageName();
  100. verCode = context.getPackageManager().getPackageInfo(packName, 0).versionCode;
  101. } catch (NameNotFoundException e) {
  102. // TODO Auto-generated catch block
  103. Log.e("版本号获取异常", e.getMessage());
  104. }
  105. return verCode;
  106. }
  107.  
  108. public String getVerName(Context context){
  109. String verName = "";
  110. try {
  111. String packName = context.getPackageName();
  112. verName = context.getPackageManager().getPackageInfo(packName, 0).versionName;
  113. } catch (NameNotFoundException e) {
  114. Log.e("版本名称获取异常", e.getMessage());
  115. }
  116. return verName;
  117. }
  118.  
  119. public boolean getServerVer(){
  120. try {
  121. String path=getResources().getString(R.string.url_server);
  122. URL url = new URL(path);
  123. HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
  124. //httpConnection.setDoInput(true);
  125. //httpConnection.setDoOutput(true);
  126. //httpConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");
  127. httpConnection.setRequestMethod("GET");
  128. httpConnection.connect();
  129. InputStream inputStream = httpConnection.getInputStream();
  130. InputStreamReader reader = new InputStreamReader(inputStream);
  131. BufferedReader bReader = new BufferedReader(reader);
  132. String json = bReader.readLine();
  133. JSONArray array = new JSONArray(json);
  134. JSONObject jsonObj = array.getJSONObject(0);
  135. newVerCode = Integer.parseInt(jsonObj.getString("verCode"));
  136. newVerName = jsonObj.getString("verName");
  137. } catch (Exception e) {
  138. // TODO Auto-generated catch block
  139. e.printStackTrace();
  140. return true;//如果这里改为false 则不更新会退出程序
  141. }
  142. return true;
  143. }
  144.  
  145. public void notNewVersionUpdate(){
  146. int verCode = this.getVerCode(this);
  147. String verName = this.getVerName(this);
  148. StringBuffer sb = new StringBuffer();
  149. sb.append("当前版本:");
  150. sb.append(verName);
  151. sb.append(" Code:");
  152. sb.append(verCode);
  153. sb.append("\n已是最新版本,无需更新");
  154. Dialog dialog = new AlertDialog.Builder(this)
  155. .setTitle("软件更新")
  156. .setMessage(sb.toString())
  157. .setPositiveButton("确定", new DialogInterface.OnClickListener() {
  158. @Override
  159. public void onClick(DialogInterface dialog, int which) {
  160. // TODO Auto-generated method stub
  161. //finish();
  162. }
  163. }).create();
  164. dialog.show();
  165. }
  166.  
  167. public void doNewVersionUpdate(){
  168. int verCode = this.getVerCode(this);
  169. String verName = this.getVerName(this);
  170. StringBuffer sb = new StringBuffer();
  171. sb.append("当前版本:");
  172. sb.append(verName);
  173. sb.append(" Code:");
  174. sb.append(verCode);
  175. sb.append(",发现版本:");
  176. sb.append(newVerName);
  177. sb.append(" Code:");
  178. sb.append(newVerCode);
  179. sb.append(",是否更新");
  180. Dialog dialog = new AlertDialog.Builder(this)
  181. .setTitle("软件更新")
  182. .setMessage(sb.toString())
  183. .setPositiveButton("更新", new DialogInterface.OnClickListener() {
  184. @Override
  185. public void onClick(DialogInterface dialog, int which) {
  186. // TODO Auto-generated method stub
  187. pd = new ProgressDialog(MainActivity.this);
  188. pd.setTitle("正在下载");
  189. pd.setMessage("请稍后。。。");
  190. pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
  191. String apkpath=getResources().getString(R.string.url_apk);
  192. downFile(apkpath);
  193. }
  194. })
  195. .setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
  196.  
  197. @Override
  198. public void onClick(DialogInterface dialog, int which) {
  199. // TODO Auto-generated method stub
  200. //finish();
  201. }
  202. }).create();
  203. //显示更新框
  204. dialog.show();
  205. }
  206.  
  207. public void downFile(final String url){
  208. pd.show();
  209. new Thread(){
  210. public void run(){
  211. HttpClient client = new DefaultHttpClient();
  212. HttpGet get = new HttpGet(url);
  213. HttpResponse response;
  214. System.out.println(url);
  215. try {
  216. response = client.execute(get);
  217. HttpEntity entity = response.getEntity();
  218. long length = entity.getContentLength();
  219. InputStream is = entity.getContent();
  220. FileOutputStream fileOutputStream = null;
  221. if(is != null){
  222. File file = new File(Environment.getExternalStorageDirectory(),UPDATE_SERVERAPK);
  223. fileOutputStream = new FileOutputStream(file);
  224. byte[] b = new byte[1024];
  225. int charb = -1;
  226. int count = 0;
  227. while((charb = is.read(b))!=-1){
  228. fileOutputStream.write(b, 0, charb);
  229. count += charb;
  230. }
  231. }
  232. fileOutputStream.flush();
  233. if(fileOutputStream!=null){
  234. fileOutputStream.close();
  235. }
  236. down();
  237. } catch (Exception e) {
  238. // TODO Auto-generated catch block
  239. e.printStackTrace();
  240. }
  241. }
  242. }.start();
  243. }
  244.  
  245. Handler handler = new Handler() {
  246. @Override
  247. public void handleMessage(Message msg) {
  248. super.handleMessage(msg);
  249. pd.cancel();
  250. update();
  251. }
  252. };
  253.  
  254. public void down(){
  255. new Thread(){
  256. public void run(){
  257. Message message = handler.obtainMessage();
  258. handler.sendMessage(message);
  259. }
  260. }.start();
  261. }
  262.  
  263. public void update(){
  264. Intent intent = new Intent(Intent.ACTION_VIEW);
  265. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  266. intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),UPDATE_SERVERAPK))
  267. , "application/vnd.android.package-archive");
  268. startActivity(intent);
  269. }
  270. }

在服务器上的js文件

  1. [{"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的时候的自动更新与升级的更多相关文章

  1. Android App版本自动更新

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

  2. git 远程版本库,github提供服务原理,git自动更新发送邮件

    1.安装好Linux,安装好Git(192.168.1.239) 2.创建一个用户zph(让此用户提供git on server),密码设置为12345678 # useradd zph # pass ...

  3. ASP.NET网站版本自动更新程序及代码[转]

    1.自动更新程序主要负责从服务器中获取相应的更新文件,并且把这些文件下载到本地,替换现有的文件.达到修复Bug,更新功能的目的.用户手工点击更新按钮启动更新程序.已测试.2.环境VS2008,采用C# ...

  4. ios开发 数据库版本迁移手动更新迭代和自动更新迭代

    数据库版本迁移顾名思义就是在原有的数据库中更新数据库,数据库中的数据保持不变对表的增.删.该.查. 数据持久化存储: plist文件(属性列表) preference(偏好设置) NSKeyedArc ...

  5. 批量自动更新SVN版本库 - Windows

    开发过程中每天都要从SVN代码库里一个一个的update各个项目代码,不仅效率实在是低,也不符合程序员的"懒"精神,由于是在Windows环境做开发,自然就想到了使用bat来实现自 ...

  6. ios开发数据库版本迁移手动更新迭代和自动更新迭代艺术(二)

    由于大家都热衷于对ios开发数据库版本迁移手动更新迭代和自动更新迭代艺术(一)的浏览下面我分享下我的源文件git仓库: 用法(这边我是对缓存的一些操作不需要可以省去):https://github.c ...

  7. iOS企业版使用第三方实现自动更新版本

    1.获取本地版本和互联网版本          NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];     N ...

  8. CS程序自动更新实现原理及代码(支持多版本多文件更新)

    公司主要项目为CS端,经常遇到客户需求变更及bug处理,在没有引用自动更新之前每次更新程序,必须手动对每个客户端进行更新,这样导致技术支持工作量特别大,也给客户不好的印象,因此我需要一个自动更新程序! ...

  9. nvidia驱动自动更新版本后问题解决 -- failed to initialize nvml: driver/library version mismatch

    因为必须关闭桌面窗口, 建议另外一台电脑ssh连接操作 1. 卸载旧版本并关闭图形界面 sudo apt-get remove --purge nvidia-\* sudo service light ...

随机推荐

  1. Maven 安装记

    java初学者 昨天通m2e插件把maven项目导入eclipse的时候各种bug,看了各家技术博客,决定安装maven好好了解下. 安装maven也是一波三折的,先是看各种安装指导,结果环境变量都没 ...

  2. windows批处理命令之ren

    1.批处理批量修改文件后缀名(假设我需要把一个文件夹中的很多txt文件改为sql文件): 1)在需要被处理的文件的文件夹里先新建一个txt文本,然后在文本中写入: ren *.txt *.sql 2) ...

  3. jQuery简单导航示例

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  4. Delphi-CompareText 函数

    函数名称 CompareText 所在单元 System.SysUtils 函数原型 function CompareText(const S1, S2: string): Integer; 函数功能 ...

  5. C语言笔记(数组地址一些细节)

     一.数组的a+1和&a+1的区别 先看看测试代码: ]={}; printf(" sizeof(data) = %d.\n", sizeof(data)); printf ...

  6. socket本地模拟UDP 服务器+客户端(三)

    UDP: TCP是建立可靠连接,并且通信双方都可以以流的形式发送数据.相对TCP,UDP则是面向无连接的协议. 使用UDP协议时,不需要建立连接,只需要知道对方的IP地址和端口号,就可以直接发数据包. ...

  7. 转:Mongodb中随机的查询文档记录

    简述,摘要:在实际应用场景中,几乎都会有随机获取数据记录的需求.而这个需求在Mongodb却不是很好实现,就目前而言,大致上有三种解决方案:1. 先计算出一个从0到记录总数之间的随机数,然后采用ski ...

  8. API Hook完全手册

    文章来源: http://blog.csdn.net/atfield 原文作者: ATField 整理日期: 2008-07-16 发表评论 字体大小: 小 中 大   注:本文是根据我两年前写的一个 ...

  9. 使用 Spring Boot 快速构建 Spring 框架应用,PropertyPlaceholderConfigurer

    Spring 框架对于很多 Java 开发人员来说都不陌生.自从 2002 年发布以来,Spring 框架已经成为企业应用开发领域非常流行的基础框架.有大量的企业应用基于 Spring 框架来开发.S ...

  10. 2015WF有感

    World Final题目连接:http://icpc.baylor.edu/worldfinals/problems/icpc2015.pdf 建议:可以倒序阅读来获得最直观的赛场体验... 2:1 ...