以下代码由PHP200 阿杜整理 
package com.example.syzx;
 
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.cordova.DroidGap;
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 com.example.syzx.MainActivity;
import com.example.syzx.R;
 
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
 
@SuppressLint({ "HandlerLeak", "NewApi" })
public class MainActivity extends DroidGap {
 
String jsonurl = "http://192.168.2.100/app/version.js";
String newVerName = "";// 新版本名称
String downurl = "";//下载 地址
int newVerCode = -1;// 新版本号
String UPDATE_SERVERAPK = "yhupdate.apk";
ProgressDialog pd = null;
 
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
super.setIntegerProperty("splashscreen", R.drawable.splash);
 
if(checkNetWorkStatus()){
updateVersion();
super.loadUrl("file:///android_asset/www/index.html", 3000);
//super.loadUrl("file:///android_asset/www/test/index.html", 3000);
}  
}
 
 
 
 
 
 
 
/**
* 检测版本
*/
public void updateVersion() {
if (getServerVer()) {
int verCode = this.getVerCode(this);
if (newVerCode > verCode) {
doNewVersionUpdate();// 更新版本
}
}
}
 
/**
* 获得版本号
*/
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;
    }
/**
* 检测版本
* @return
* @throws Exception
*/
public String getVerName(){
 //获取包名
 PackageManager packageManager = getPackageManager();
 
 PackageInfo packInfo = null;
try {
packInfo = packageManager.getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
    return packInfo.versionName; 
 }
 
 
/**
* 从服务器端获得版本号与版本名称
*/
public boolean getServerVer() {
try {
URL url = new URL(jsonurl);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("GET");
httpConnection.connect();
InputStreamReader reader = new InputStreamReader(httpConnection.getInputStream());
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");
downurl = jsonObj.getString("downurl");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return true;// 如果这里改为false 则不更新会退出程序
}
return true;
}
 
/**
* 更新版本
*/
public void doNewVersionUpdate() {
int verCode = this.getVerCode(this);
String verName = this.getVerName(this);
StringBuffer sb = new StringBuffer();
sb.append("当前版本:");
sb.append(verName);
sb.append(" V");
sb.append(verCode);
sb.append(",发现版本:");
sb.append(newVerName);
sb.append(" V");
sb.append(newVerCode);
sb.append(",是否更新?");
Dialog dialog = new AlertDialog.Builder(this)
.setTitle("软件更新")
.setMessage(sb.toString())
.setPositiveButton("更新", new DialogInterface.OnClickListener() {
 
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);
downFile(downurl);
}
})
.setNegativeButton("暂不更新",
new DialogInterface.OnClickListener() {
 
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
// finish();
}
}).create();
// 显示更新框
dialog.show();
}
 
/**
* 下载apk
*/
public void downFile(final String url) {
pd.show();
new Thread() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response;
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();
}
};
 
/**
* 下载完成,通过handler将下载对话框取消
*/
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.setDataAndType(Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), UPDATE_SERVERAPK)),
"application/vnd.android.package-archive");
startActivity(intent);
}
 
 
/**
* check network Status
* @return boolean
*/
public boolean checkNetWorkStatus() {
boolean result;
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnected()) { // 当前网络可用
result = true;
} else { // 不可用
 
new AlertDialog.Builder(MainActivity.this)
.setMessage("检查到没有可用的网络连接,请打开网络连接")
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialoginterface, int i) {
ComponentName cn = new ComponentName(
"com.android.settings",
"com.android.settings.Settings");
Intent intent = new Intent();
intent.setComponent(cn);
intent.setAction("android.intent.action.VIEW");
startActivity(intent);
finish();
}
}).show();
result = false;
}
return result;
}
 
}

安卓升级提示 phoneGap APK软件更新提示的更多相关文章

  1. Phonegap 安卓的自动升级与更新。当版本为4.0的时候

    清单文件中: <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14"/> ...

  2. Android Studio实现APK的更新、下载、安装

    先不讲那么多看效果图: 下面来讲解一些更新CODE,原理大家都知道,不废话,直接上代码.里面有一些是我自己做的测试例子,所以大家可以直接删掉就好了 第一个:activity_main.xml < ...

  3. Android软件更新安装。

    app的开发有一个问题是避免不了的,那就是软件的升级维护. 这里我在查过一些资料和写了一个升级帮助类.使用很方便.直接导入就可以了. ( VersionBean.class为更新地址返回的数据对象,我 ...

  4. Android中使用AsyncTask实现文件下载以及进度更新提示

    Android提供了一个工具类:AsyncTask,它使创建需要与用户界面交互的长时间运行的任务变得更简单.相对Handler来说AsyncTask更轻量级一些,适用于简单的异步处理,不需要借助线程和 ...

  5. iPhone取消软件更新上边的1

    去除设置的更新+1小红点提示主要分为越狱和非越狱设备两种方法. 越狱状态下方法: 首先将你的设备进行越狱: 越狱后安装ifile(这个自行搜索安装): 用ifile打开/System/Library/ ...

  6. android之apk自动更新解析包失败问题

    在apk自动更新(相关问题可以看我的博客http://blog.csdn.net/caicongyang) 从服务器下载完成后,点击notification提示安装时,每次都报解析包失败错误!首先我想 ...

  7. Android Apk增量更新

    前言 有关APK更新的技术比较多,例如:增量更新.插件式开发.热修复.RN.静默安装. 下面简单介绍一下: 什么是增量更新?   增量更新就是原有app的基础上只更新发生变化的地方,其余保持原样. 与 ...

  8. Ubuntu更新提示哈希和不匹配“Hash Sum mismatch”

    Ubuntu更新提示哈希和不匹配"Hash Sum mismatch" 今天在常规更新软件的时候,我的ubuntu报了一个错误. 应该是ubuntu程序更新转交给另外一个更新造成 ...

  9. [英中双语] Pragmatic Software Development Tips 务实的软件开发提示

    Pragmatic Software Development Tips务实的软件开发提示 Care About Your Craft Why spend your life developing so ...

随机推荐

  1. Invoke与BeginInvoke

    一.为什么 Control类提供了 Invoke和 BeginInvoke机制? 关于这个问题的最主要的原因已经是 dotnet程序员众所周知的,我在此费点笔墨再次记录到自己的日志,以便日后提醒一下自 ...

  2. 在Hadoop伪分布式模式下安装Hive(derby,mysql)

    我的Hadoop版本是1.2.0,mysql版本是5.6.12. 先介绍一下嵌入式derby模式: 1.下载/解压 在hive官网上选择要下载的版本,我选择的版本是hive-0.10.0. 下载好解压 ...

  3. github的large file storeage

    https://git-lfs.github.com/ 1.从这个网址下载git-lfs-windows-amd64-1.1.0.exe,运行这个安装包 2.然后打开git bash 输入git lf ...

  4. 关于Hibernate中的Configuration

    Hibernate中,关于从 Configuration中建立一个SessionFactory常用的可以有两种方法,一种是为Configuration提供hibernate.cfg.xml配置文件,还 ...

  5. 真正解决ASP.NET每一个页面首次访问超级慢的问题 (转载)

    原文:http://www.afuhao.com/article_articleId-219.shtml 摘要:ASP.NET页面首次打开很慢,但别的页面如果没有访问过,去访问也会慢.你也许认为它是在 ...

  6. BZOJ3105: [cqoi2013]新Nim游戏

    题解: 线性基?类似于向量上的基底. 此题题解戳这里:http://blog.csdn.net/wyfcyx_forever/article/details/39477673 代码: #include ...

  7. [经验] - JQuery.Ajax + 跨域 (crossDomain) + POST + JSON + WCF RESTful, 5大陷阱和解决方案

    最近在开发WSS RESTful服务的时候, 碰到了这些个纠结的问题. 在网上查找了半天, 找到n多种解决方案, 但是都是部分的, 要么是没有跨域的情况, 要么是没有post的情况, 要么不是用WCF ...

  8. Java [Leetcode 70]Climbing Stairs

    题目描述: You are climbing a stair case. It takes n steps to reach to the top. Each time you can either ...

  9. ffmpeg基础与编译_在VS2008下调试output_example.c(详细步骤)

    注意:这个是编译Debug版本的.必要资源:FFMPEG SDK 3.2(已经编译好的,可以去http://www.bairuitech.com/html/ruanjianxiazai/ffmpeg/ ...

  10. 【转】如何在eclipse里关联查看android源码

    原文网址:http://fengbohaishang.blog.51cto.com/5106297/1339556 以前没怎么注意过这个问题,不怎么看源码,现在发现源码确实是很好的学习资源. 直入正题 ...