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 ...
随机推荐
- 在IE6/7/8下识别html5标签
识别html5标签: html5添加了许多语义化的标签,比如<nav></nav>,<aside></aside>,<article>< ...
- JS indexOf() lastIndexOf()与substring()截取字符串的区别
1. String.IndexOf 方法 (value[,startIndex]) value:要查找的 Unicode 字符. 必选项startIndex:搜索起始位置. 可选项 不写从开头查找 ...
- Serilog with Autofac
http://serilog.net/ ---不错的日志工具 1.直接绑定 builder.Register<ILogger>((c, p) => { return new Log ...
- laravel框架——composer导入laravel
第一种: composer create-project --prefer-dist laravel/laravel 名称 "5.2.*"第二种: composer global ...
- codevs 2806 红与黑
2806 红与黑 时间限制: 1 s 空间限制: 64000 KB 题目等级 : 白银 Silver 题解 查看运行结果 题目描述 Description 有一个矩形房间,覆盖正方形瓷 ...
- 【Java】环境变量的配置
注意点 1.环境变量不能有空格,比如C:\Program Files 2.JAVA_HOME:D:\Java\jdk1.7.0_67------------->注意不能加;分号
- Jest
http://www.ibm.com/developerworks/cn/java/j-javadev2-24/
- j2ee爬坑行之一:web容器
什么是容器? servlet没用main方法,它们受控于另一个java应用程序,这个应用程序就称为容器. tomcat就是这样一个容器.当web服务器得到一个指向某servlet的请求,此时服务器不是 ...
- 【字典树】【贪心】Codeforces 706D Vasiliy's Multiset
题目链接: http://codeforces.com/contest/706/problem/D 题目大意: 三种操作,1.添加一个数,2.删除一个数,3.查询现有数中与x异或最大值.(可重复) 题 ...
- Android新浪微博客户端(五)——主界面的TabHost和WeiboUtil
原文出自:方杰|http://fangjie.info/?p=183转载请注明出处 最终效果演示:http://fangjie.info/?page_id=54 该项目代码已经放到github:htt ...