清单文件中:

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

  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. 实用iPhone Cydia插件

      BadgeClear(角标清除):可以清除App推送所在图标右上角出现的红色角标.在桌面长按图标后,图标开始左右摇动,再双击图标即可清除点击的图标角标.   Bitesms(短信):收费插件,具有 ...

  2. Yii框架AR对象数据转化为数组

    demo函数作用:将AR对象数据转化为数组 局限:仅用于findAll的多维数组,find一维数组可以先转化为多维数组的一个元素在使用 function actionIndex() { $data = ...

  3. C:\WINDOWS\system32\config\systemprofile\Desktop引用了一个不可用的位置

    使用迅雷下载压缩文件到桌面时,下载完毕后,如果直接点击"打开文件",则迅雷会报错: C:\WINDOWS\system32\config\systemprofile\Desktop ...

  4. 『Python』 爬取 WooYun 论坛所有漏洞条目的相关信息

    每个漏洞条目包含: 乌云ID,漏洞标题,漏洞所属厂商,白帽子,漏洞类型,厂商或平台给的Rank值 主要是做数据分析使用:可以分析某厂商的各类型漏洞的统计:或者对白帽子的能力进行分析..... 数据更新 ...

  5. 转:eclipse载入extjs4出现内存溢出错误的解决方法

    去掉.project文件中的以下部分:第一部分:<buildCommand>    <name>org.eclipse.wst.jsdt.core.javascriptVali ...

  6. 【Hybrid App】一个产品经理眼中的PhoneGap Vs. AppCan

    首先在写这篇文章前,必须先申明一下,本人是技术出身,对HTML技术及手机客户端都有过编程经验,只是出于工作岗位的变动,便没有再具体代码工作,以下文章涉及的中间件的基本代码实现及前期的API使用,都是自 ...

  7. C51 库函数(2)

    3.2 STDIO.H:一般I/O函数 C51编译器包含字符I/O函数,它们通过处理器的串行接口操作,为支持其它I/O机制,只需修改getkey()和putchar()函数,其它所有I/O支持函数依赖 ...

  8. 【HDOJ】4628 Pieces

    最开始的想法是搜索,发现不对,后来发现数据量很小,可以状态压缩+DP. /* 4628 */ #include <cstdio> #include <cstring> #inc ...

  9. BZOJ 1023 [SCOI2009]生日快乐

    1024: [SCOI2009]生日快乐 Time Limit: 1 Sec  Memory Limit: 162 MBSubmit: 1729  Solved: 1219[Submit][Statu ...

  10. 设计模式(六):Singleton 单件模式 -- 创建型模式

    1.定义 当需要控制一个类的实例数量且调用者可以从一个公共的访问点访问时. 2.适用场景 1. 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时. 2. 当这个唯一实例应该是通过子类化可扩 ...