检测APK版本有更新,手动升级安装

来源:互联网 发布:美女与野兽 知乎 编辑:程序博客网 时间:2024/06/02 01:26

直接上代码了,此处不难理解。有什么问题可以留言。


从服务器获取xml解析并进行比对版本号

class CheckVersionTask implements Runnable{         public void run() {              try {                  //从资源文件获取服务器 地址                   String update_url = ServerBiz.getServer(HomeActivity.this, "update_url");                //包装成url的对象                   URL url = new URL(update_url);                  HttpURLConnection conn =  (HttpURLConnection) url.openConnection();   (此处报错,输出conn.getResponseCode()看看!)                conn.setConnectTimeout(5000);                  InputStream is =conn.getInputStream();                                   //获得更新文件的信息                UpdateInfo info =  DownLoadManager.getUpdateInfo(is);                 if(info.getVersion().equals(getVersionName())){                      Log.i("liyongjun","版本号相同无需升级");                  }else{                      Log.i("liyongjun","版本号不同 ,提示用户升级 ");                      Intent intent = new Intent("com.ccfrom.cclive.ACTION.ApkUpdate");                    intent.putExtra("updatemsg", info.getDescription());                    intent.putExtra("filepath",info.getUrl());                    sendBroadcast(intent);                }              } catch (Exception e) {                  // 待处理                   Message msg = new Message();                  msg.what = GET_UNDATAINFO_ERROR;                  handler.sendMessage(msg);                  e.printStackTrace();              }           }      }  

获取package的版本号,配置在manifest中的

private String getVersionName() throws Exception{          //获取packagemanager的实例           PackageManager packageManager = getPackageManager();          //getPackageName()是你当前类的包名,0代表是获取版本信息          PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);          return packInfo.versionName;       } 

注册此接收器:

class ApkUpdateReciver extends BroadcastReceiver {        public void onReceive(Context paramContext, Intent paramIntent) {            String str1 = paramIntent.getAction();            if (str1.equals("com.ccfrom.cclive.ACTION.ApkUpdate")) {                String updatemsg = paramIntent.getStringExtra("updatemsg");                String filepath = paramIntent.getStringExtra("filepath");                HomeActivity.this.createUpdateDialog(updatemsg, filepath).show();                HomeActivity.this.removeStickyBroadcast(paramIntent);            }        }    }

创建提示框,是否更新版本

public AlertDialog createUpdateDialog(String updatemsg, final String filepath) {         AlertDialog.Builder builer = new Builder(this) ;              builer.setTitle("版本升级");             builer.setMessage(updatemsg);             builer.setPositiveButton("确定", new OnClickListener() {                 public void onClick(DialogInterface dialog, int which) {                         downLoadApk(filepath);                     }                    });                 builer.setNegativeButton("取消", new OnClickListener() {                     public void onClick(DialogInterface dialog, int which) {                         Log.e("HomeActivity", "Enter Main..");                    }                 });                        return builer.create();    }

从服务器中下载apk

 protected void downLoadApk(final String filePath) {         pd = new  ProgressDialog(this);         pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);         pd.setMessage("正在下载更新");         pd.show();         new Thread(){             @Override             public void run() {                 try {                     File file = DownLoadManager.getFileFromServer(filePath, pd);                     sleep(3000);                                         installApk(file);                     pd.dismiss(); //结束掉进度条对话框                 } catch (Exception e) {                     e.printStackTrace();                     Message msg = new Message();                     msg.what = DOWN_ERROR;                     handler.sendMessage(msg);                 }             }}.start();     }  

安装已下载的apk,并结束当前应用

 protected void installApk(File file) {         Intent intent = new Intent();         //执行动作         intent.setAction(Intent.ACTION_VIEW);         //执行的数据类型         intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");         startActivity(intent);     }  

以下贴上前面需要使用到的类方法:

ServerBiz.java

private static ServerInfo parserServerXml(String paramString) {        ServerInfo mServerInfo = null;        if (paramString != null) {            mServerInfo = new ServerInfo();            try {                DocumentBuilderFactory domfac = DocumentBuilderFactory                        .newInstance();                DocumentBuilder dombuilder = domfac.newDocumentBuilder();                Document doc;                Element root;                NodeList maps;                URL url = new URL(paramString);                doc = dombuilder.parse(url.openStream());                root = doc.getDocumentElement();                maps = root.getChildNodes();                for (Node node = maps.item(1).getFirstChild(); node != null; node = node                        .getNextSibling()) {                    if (node.getNodeType() == Node.ELEMENT_NODE) {                        Log.e("liyongjun","name = " + node.getNodeName());                        if (node.getNodeName().equals("hosturl"))                            mServerInfo.hosturl = node.getTextContent();                        else if (node.getNodeName().equals("liveurl"))                            mServerInfo.liveurl = node.getTextContent();                        else if (node.getNodeName().equals("mv_url"))                            mServerInfo.mv_url = node.getTextContent();                        else if (node.getNodeName().equals("news_url"))                            mServerInfo.news_url = node.getTextContent();                        else if (node.getNodeName().equals("playurl"))                            mServerInfo.playurl = node.getTextContent();                        else if (node.getNodeName().equals("tvback_url"))                            mServerInfo.tvback_url = node.getTextContent();                        else if (node.getNodeName().equals("tvepg_url"))                            mServerInfo.tvepg_url = node.getTextContent();                        else if (node.getNodeName().equals("update_url"))                            mServerInfo.update_url = node.getTextContent();                                           }                }            } catch (Exception e) {                e.printStackTrace();            }        }        return mServerInfo;    }   private static void saveServerInfo(Context paramContext,            ServerInfo paramServerInfo) {        SharedPreferences.Editor localEditor = paramContext                .getSharedPreferences("server_preferences",                        paramContext.MODE_PRIVATE).edit();        localEditor.putString("hosturl", paramServerInfo.hosturl);        localEditor.putString("liveurl", paramServerInfo.liveurl);        localEditor.putString("mv_url", paramServerInfo.mv_url);        localEditor.putString("news_url", paramServerInfo.news_url);        localEditor.putString("playurl", paramServerInfo.playurl);        localEditor.putString("tvback_url", paramServerInfo.tvback_url);        localEditor.putString("tvepg_url", paramServerInfo.tvepg_url);        localEditor.putString("update_url", paramServerInfo.update_url);        localEditor.commit();    }    public static String getServer(Context paramContext, String paramString) {        return paramContext.getSharedPreferences("server_preferences",                paramContext.MODE_PRIVATE).getString(paramString, null);    }

UpdateInfo.java

    private String version;     private String url;     private String description;       public String getVersion() {        return version;    }    public void setVersion(String version) {        this.version = version;    }    public String getUrl() {        return url;    }    public void setUrl(String url) {        this.url = url;    }    public String getDescription() {        return description;    }    public void setDescription(String description) {        this.description = description;    }  

update.xml 此文件放于服务器指定位置,用来比较当前版本的版本号

<?xml version="1.0" encoding="utf-8"?><info>     <version>2.0</version>     <url>http://ccfrom.qtcms.cn/files/CcLive.apk</url>     <description>检测到最新版本,请及时更新!</description> </info>



0 0
原创粉丝点击