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 ...
随机推荐
- C#三种方式实现序列化(转)
序列化和反序列化我们可能经常会听到,其实通俗一点的解释,序列化就是把一个对象保存到一个文件或数据库字段中去,反序列化就是在适当的时候把这个文件再转化成原来的对象使用. 序列化和反序列化最主要的作用有: ...
- CSS布局:div高度随窗口变化而变化(BUG会有滚动条)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 利用Php ssh2扩展实现svn自动提交到测试服务器
1.安装ssh2扩展 (1)window . 下载 php extension ssh2 下载地址 http://windows.php.net/downloads/pecl/releases/ssh ...
- eval("表达式")
eval就是把字符串转成可执行代码eval("表达式");表达式被翻译成JavaScript代码执行比如eval("alert('test')");等于aler ...
- 2-路插入排序(2-way Insertion Sort)的C语言实现
原创文章,转载请注明来自钢铁侠Mac博客http://www.cnblogs.com/gangtiexia 2-路插入排序(2-way Insertion Sort)的基本思想: 比fis ...
- ppt画笔标记在哪里|ppt中画笔工具功能怎么用?
一.ppt中画笔工具功能在哪里? 这个画笔工具其实就相当于我们的一个标记工具,要实现标记功能首先将需要演示的PPT按住F5进入到放映状态,然后在右击ppt上的空白处就会弹出衣蛾对话框,在对话框中选择“ ...
- Python二分查找
代码: 时间复杂度:O(log2n) #!/usr/bin/env python #coding:utf-8 import copy from copy import deepcopy ''' def ...
- sql server 国内外 2个同步 ,加一个表.加入同步种
国内 和国外sql server 订阅 ,数据同步. 因为表是刚开始就弄好的. 那么如果国内加一个表.国外没法同步过去 步骤:1.国外也建一个一抹一样的表 步骤:2.把国内的数据导入到国外 步骤:3. ...
- Xamarin.Forms WebView
目前本地或网络的网页内容和文件加载 WebView是在您的应用程序显示Web和HTML内容的视图.不像OpenUri,这需要用户在Web浏览器的设备上,WebView中显示您的应用程序内的HTML内容 ...
- 【HDOJ】2510 符号三角形
暴力打表. #include <cstdio> ]={,,,,,,,,,,,,,,,,,,,,,,,,}; int main() { while (scanf("%d" ...