清单文件中:

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

js文件:

  1. [{"verName":"xinjiangQJ","verCode":2}]

主窗口MainActivity中的代码:

  1. package fx.qj.cn;
  2.  
  3. import android.os.Bundle;
  4.  
  5. import android.view.KeyEvent;
  6. import android.view.Menu;
  7. import android.view.MenuItem;
  8. import android.view.Window;
  9. import android.widget.Toast;
  10.  
  11. import java.io.BufferedReader;
  12. import java.io.File;
  13. import java.io.FileOutputStream;
  14. import java.io.IOException;
  15. import java.io.InputStream;
  16. import java.io.InputStreamReader;
  17. import java.net.HttpURLConnection;
  18. import java.net.MalformedURLException;
  19. import java.net.URL;
  20.  
  21. import org.apache.http.HttpEntity;
  22. import org.apache.http.HttpResponse;
  23. import org.apache.http.client.ClientProtocolException;
  24. import org.apache.http.client.HttpClient;
  25. import org.apache.http.client.methods.HttpGet;
  26. import org.apache.http.impl.client.DefaultHttpClient;
  27. import org.json.JSONArray;
  28. import org.json.JSONException;
  29. import org.json.JSONObject;
  30. import android.app.AlertDialog;
  31. import android.app.Dialog;
  32. import android.app.ProgressDialog;
  33. import android.content.Context;
  34. import android.content.DialogInterface;
  35. import android.content.Intent;
  36. import android.content.pm.PackageManager.NameNotFoundException;
  37. import android.net.Uri;
  38. import android.os.Environment;
  39. import android.os.Handler;
  40. import android.os.Message;
  41. import android.util.Log;
  42. import org.apache.cordova.*;
  43.  
  44. public class MainActivity extends DroidGap {
  45. private long exitTime = 0;
  46. //自动检查更新开始
  47. private String localApkName = "XJQJW。apk";//存在于本地的apk名字
  48. private String packageName = "fx.qj.cn";//本应用包名,用于获取本地版本号
  49. private int serverVersion = 0;//服务端版本号
  50. private int localVersion = 0;//本地版本号
  51. private ProgressDialog pBar = null;//“正在下载”对话框
  52.  
  53. @Override
  54. public void onCreate(Bundle savedInstanceState) {
  55. requestWindowFeature(Window.FEATURE_NO_TITLE);
  56. super.onCreate(savedInstanceState);
  57. super.init();
  58. android.webkit.WebSettings settings = super.appView.getSettings();
  59. String appCachePath = this.getCacheDir().getAbsolutePath();
  60. settings.setAppCachePath(appCachePath);
  61. settings.setAllowFileAccess(true);
  62. settings.setAppCacheEnabled(true);
  63. super.setIntegerProperty("splashscreen",R.drawable.startup_bg1);
  64. super.loadUrl("file:///android_asset/www/index.html",5000);
  65. checkUpdate();//自动检查更新
  66. }
  67.  
  68. //双击退出
  69. @Override
  70. public boolean onCreateOptionsMenu(Menu menu) {
  71. // Inflate the menu; this adds items to the action bar if it is present.
  72. getMenuInflater().inflate(R.menu.main, menu);
  73. return true;
  74. }
  75. @Override
  76. public boolean onKeyDown(int keyCode, KeyEvent event) {
  77. if (keyCode == KeyEvent.KEYCODE_BACK) {
  78. exit();
  79. return false;
  80. }
  81. return super.onKeyDown(keyCode, event);
  82. }
  83.  
  84. public void exit() {
  85. if ((System.currentTimeMillis() - exitTime) > 2000) {
  86. Toast.makeText(getApplicationContext(), "再按一次退出程序",
  87. Toast.LENGTH_SHORT).show();
  88. exitTime = System.currentTimeMillis();
  89. } else {
  90. finish();
  91. System.exit(0);
  92. }
  93. }
  94.  
  95. //自动更新
  96. private void checkUpdate() {
  97. localVersion = getLocalVersion();
  98. new Thread() {
  99.  
  100. @Override
  101. public void run() {
  102. // TODO Auto-generated method stub
  103. super.run();
  104. URL url_2;
  105. String str = "";
  106. int apkVersion = 0;
  107. String apkPath = "";
  108. try {
  109. String path=getResources().getString(R.string.url_server);
  110. url_2 = new URL(path);
  111. HttpURLConnection conn = (HttpURLConnection) url_2
  112. .openConnection();
  113. conn.setConnectTimeout(5000);
  114. InputStream is = conn.getInputStream();
  115. byte[] json = new byte[1024];
  116. is.read(json);
  117. str = new String(json, "utf-8");
  118. JSONArray array = new JSONArray(str);
  119. JSONObject item = array.getJSONObject(0);
  120. apkVersion = item.getInt("verCode");
  121. String apkpath=getResources().getString(R.string.url_server);
  122. apkPath = apkpath;
  123. } catch (MalformedURLException e) {
  124. // TODO Auto-generated catch block
  125. e.printStackTrace();
  126. } catch (IOException e) {
  127. // TODO Auto-generated catch block
  128. e.printStackTrace();
  129. } catch (JSONException e) {
  130. // TODO Auto-generated catch block
  131. e.printStackTrace();
  132. }
  133.  
  134. Bundle data = new Bundle();
  135. data.putInt("apkVersion", apkVersion);
  136. data.putString("apkPath", apkPath);
  137. Message msg = new Message();
  138. msg.what = 1;
  139. msg.setData(data);
  140. hander.sendMessage(msg);
  141. }
  142.  
  143. }.start();
  144. }
  145.  
  146. private int getLocalVersion(){
  147. int version=-1;
  148. try {
  149. version = this.getPackageManager().getPackageInfo(packageName, 0).versionCode;
  150. } catch (NameNotFoundException e) {
  151. // TODO Auto-generated catch block
  152. e.printStackTrace();
  153. Log.e("TAG",e.getMessage());
  154. }
  155. return version;
  156. }
  157.  
  158. private Handler hander = new Handler() {
  159. @Override
  160. public void handleMessage(Message msg) {
  161. super.handleMessage(msg);
  162. switch (msg.what) {
  163. case 1:
  164. Bundle b = msg.getData();
  165. serverVersion = b.getInt("apkVersion");
  166. final String apkPath = b.getString("apkPath");
  167. Log.v("apkVersion", serverVersion+"");
  168. if(localVersion<serverVersion){
  169. AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
  170. alert.setTitle("软件更新").setMessage("发现新版本,建议立即更新使用.").setPositiveButton("更新", new DialogInterface.OnClickListener() {
  171.  
  172. @Override
  173. public void onClick(DialogInterface dialog, int which) {
  174. // 确定更新
  175. pBar = new ProgressDialog(MainActivity.this);
  176. pBar.setTitle("正在下载");
  177. pBar.setMessage("请稍后。。。");
  178. pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
  179. String apkpath=getResources().getString(R.string.url_apk);
  180. downFile(apkpath);
  181. }
  182. }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
  183.  
  184. @Override
  185. public void onClick(DialogInterface dialog, int which) {
  186. dialog.dismiss();
  187. }
  188. });
  189. alert.create().show();
  190. }
  191. break;
  192. }
  193. }
  194. };
  195.  
  196. public void downFile(final String url){
  197. pBar.show();
  198. new Thread(){
  199. public void run(){
  200. HttpClient client = new DefaultHttpClient();
  201. HttpGet get = new HttpGet(url);
  202. HttpResponse response;
  203. System.out.println(url);
  204. try {
  205. response = client.execute(get);
  206. HttpEntity entity = response.getEntity();
  207. long length = entity.getContentLength();
  208. InputStream is = entity.getContent();
  209. FileOutputStream fileOutputStream = null;
  210. if(is != null){
  211. File file = new File(Environment.getExternalStorageDirectory(),localApkName);
  212. fileOutputStream = new FileOutputStream(file);
  213. byte[] b = new byte[1024];
  214. int charb = -1;
  215. int count = 0;
  216. while((charb = is.read(b))!=-1){
  217. fileOutputStream.write(b, 0, charb);
  218. count += charb;
  219. }
  220. }
  221. fileOutputStream.flush();
  222. if(fileOutputStream!=null){
  223. fileOutputStream.close();
  224. }
  225. down();
  226. } catch (Exception e) {
  227. // TODO Auto-generated catch block
  228. e.printStackTrace();
  229. }
  230. }
  231. }.start();
  232. }
  233.  
  234. Handler handler = new Handler() {
  235. @Override
  236. public void handleMessage(Message msg) {
  237. super.handleMessage(msg);
  238. pBar.cancel();
  239. update();
  240. }
  241. };
  242.  
  243. public void down(){
  244. new Thread(){
  245. public void run(){
  246. Message message = handler.obtainMessage();
  247. handler.sendMessage(message);
  248. }
  249. }.start();
  250. }
  251.  
  252. public void update(){
  253. Intent intent = new Intent(Intent.ACTION_VIEW);
  254. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  255. intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),localApkName))
  256. , "application/vnd.android.package-archive");
  257. startActivity(intent);
  258. }
  259. }

把http请求【HttpURLConnection conn = (HttpURLConnection) url_2.openConnection();】放到了主线程中来运行,

报错android.os.NetworkOnMainThreadException

直接翻译就是:网络工作在主线程中的异常;网上一查发现是android中规定网络请求等耗时操作是不允许在主线程中出现的,需要另起线程,线程若有数据需要与主线程交互就可以用handler来接收。

参考资料连接: http://my.eoe.cn/1222037/archive/21064.html

Phonegap 安卓的自动升级与更新。当版本为4.0的时候的更多相关文章

  1. [转]Android 应用的自动升级、更新模块的实现

    本文转自:http://www.oschina.net/question/163910_28462 我们看到很多Android应用都具有自动更新功能,用户一键就可以完成软件的升级更新.得益于Andro ...

  2. Android应用的自动升级、更新模块的实现(转)

    我们看到很多Android应用都具有自动更新功能,用户一键就可以完成软件的升级更新.得益于Android系统的软件包管理和安装机制,这一功能实现起来相当简单,下面我们就来实践一下.首先给出界面效果: ...

  3. Android应用的自动升级、更新模块的实现

    我们看到很多Android应用都具有自动更新功能,用户一键就可以完成软件的升级更新.得益于Android系统的软件包管理和安装机制,这一功能实现起来相当简单,下面我们就来实践一下.首先给出界面效果: ...

  4. sublime text3入门笔记以及屏蔽sublime自动升级检测更新

    两个月前学习python的时候,有人推荐这个程序员最好用的编辑器,我下载了之后,发现比notepad++要好用很多,目前来说,网上成熟的版本是sublime text2简体中文版,插件也是很兼容,我用 ...

  5. 安卓App自动升级

    procedure _InstallApk(Apk: string); var LFile: JFile; LIntent: JIntent; begin LFile := TJFile.JavaCl ...

  6. WebMisSharp升级说明,最新版本1.6.0

    尊敬的C3 AM.C3 FX.WebMisSharp用户您好: 非常感谢长期来您对WebMisSharp系列产品的支持,您的使用和反馈是我们进步的最大动力.在你们的帮助下我们又向前迈进了一步,我们功能 ...

  7. 《GK101任意波发生器》升级固件发布(版本:1.0.1build803)

    一.固件说明: 硬件版本:0,logic.3 固件版本:1.0.1.build803 编译日期:2014-08-06 ====================================== 二. ...

  8. 《GK101任意波发生器》升级固件发布(版本:1.0.2build851)

    一.固件说明: 硬件版本:0,logic.3 固件版本:1.0.2.build851 编译日期:2015-06-26 ====================================== 二. ...

  9. 《GK101任意波发生器》升级固件发布(版本:1.0.2.build124)

    一.固件说明: 硬件版本:0,logic.3 固件版本:1.0.2.build124 编译日期:2014-08-19 ====================================== 二. ...

随机推荐

  1. BZOJ 1014 火星人prefix

    Description 火星人最近研究了一种操作:求一个字串两个后缀的公共前缀.比方说,有这样一个字符串:madamimadam,我们将这个字符串的各个字符予以标号:序号: 1 2 3 4 5 6 7 ...

  2. 使用Flexible 实现手淘H5 页面的终端适配学习

    Amfe阿里无线前端团队双11技术连载之际,一个实战案例来展示多终端适配. Device metrics 1.0 mdpi 2.0 xhdpi 3.0xxhdpi(iphone 6 plus) 手淘h ...

  3. Unity3D 3D横版跑酷 跳跃

    Unity3d 跑酷动画的控制 首先给个图吧, 我们跑酷里面需要动画的,今天说一下动画的知识! 1.导入骨骼动画模型文件之后,如果使用之前版本的unity的播放动画的方式,需要设置AnimationT ...

  4. codeforces Upgrading Array

    思路:对于每个数分解质因子然后记录每一个质因子的个数,对与在b中出现的质因子就减去1,否则加1,求出总的,然后从后面一次对它们的最大公约数,然后判断除以最大公约数之后,改变量是不是变化,求最大值,变化 ...

  5. yum命令常见方法

    yum check-update 检查可更新的所有软件包 yum update 下载更新系统已安装的所有软件包 yum upgrade 大规模的版本升级,与yum update不同的是,连旧的淘汰的包 ...

  6. Apache CXF多个远程拒绝服务漏洞(CVE-2013-2160)

    漏洞版本: Apache Group CXF <= 2.5.10 Apache Group CXF 2.7.4 Apache Group CXF 2.6.7 漏洞描述: BUGTRAQ ID: ...

  7. weblogic启动报错之未修改hosts产生错误

    报错如下: Enter username to boot WebLogic server:weblogic Enter password to boot WebLogic server: <Ju ...

  8. HDOJ 2056 Rectangles

    Problem Description Given two rectangles and the coordinates of two points on the diagonals of each ...

  9. Jack Straws(判断线段是否相交 + 并查集)

    /** http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=1840    题意:    判断线段 ...

  10. Codeforces Round #259 (Div. 2) D. Little Pony and Harmony Chest 状压DP

    D. Little Pony and Harmony Chest   Princess Twilight went to Celestia and Luna's old castle to resea ...