zoukankan      html  css  js  c++  java
  • 【android】apk在线升级

        现在android开发,一般采用的是CS模式,那么apk的升级,自然而然需要有server端的支持。一般,我们将升级版本以及一个记录升级版本的配置文件(在本文中采用jsonarray格式)放在server端。当Client初始化时,如果检测到server端有更新的版本(读取server的配置文件),则将在server端的升级版本以Http的方式连接,将其下载下来,然后调用android的api进行替换升级。

    一、配置文件:

    update_version.json

    [{"appname":"myapp","apkname":"myapp.apk","verName":1.0,"verCode":1}]

        版本的比较,是根据update_version.json中的verCode 以及apk文件中AndroidManifest.xml文件中的定义的版本号:

    android:versionCode="1"
    android:versionName="1.0" 

    二、初始化时比较版本

    //比较服务器版本//在 onCreate函数中调用
    if (getServerVerCode()) {
    	int vercode = Config.getVerCode(this);
    	if (newVerCode > vercode) {
    		doNewVersionUpdate();//发现新版本更新
    	} else {
    		Toast.makeText(getApplicationContext(),"目前是最新版本,感谢您的支持",Toast.LENGTH_LONG).show();//没有新版本
    	}
    }//子函数,获取版本号
    
    private boolean getServerVerCode() {
        try {
            //取得服务器地址和接口文件名
            String verjson = NetworkTool.getContent(Config.UPDATE_SERVER
                    + Config.UPDATE_VERJSON);
            JSONArray array = new JSONArray(verjson);
            if (array.length() > 0) {
                JSONObject obj = array.getJSONObject(0);
                try {
                    newVerCode = Integer.parseInt(obj.getString("verCode"));
                    newVerName = obj.getString("verName");
                } catch (Exception e) {
                    newVerCode = -1;
                    newVerName = "";
                    return false;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            return false;
        }
        return true;
    }
    
    
    
    //子函数,若是有新版本,则
    
    private void doNewVersionUpdate() {
        int verCode = Config.getVerCode(this);
        String verName = Config.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(UpdateActivity.this)
                .setTitle("软件更新")
                .setMessage(sb.toString())
                // 设置内容
                .setPositiveButton("更新",// 设置确定按钮
                        new DialogInterface.OnClickListener() { 
    
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                pBar = new ProgressDialog(UpdateActivity.this);
                                pBar.setTitle("正在下载");
                                pBar.setMessage("请稍候...");
                                pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                                downFile(Config.UPDATE_SERVER
                                        + Config.UPDATE_APKNAME);
                            } 
    
                        })
                .setNegativeButton("暂不更新",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                // 点击"取消"按钮之后退出程序
                                finish();
                            }
                        }).create();//创建
        // 显示对话框        
        dialog.show();
    }

    三、下载并升级

    	void downFile(final String url) {
    		pBar.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(),
    								Config.UPDATE_SAVENAME);
    						fileOutputStream = new FileOutputStream(file);
    
    						byte[] buf = new byte[1024];
    						int ch = -1;
    						int count = 0;
    						while ((ch = is.read(buf)) != -1) {
    							fileOutputStream.write(buf, 0, ch);
    							count += ch;
    							if (length > 0) {
    							}
    						}
    
    					}
    					fileOutputStream.flush();
    					if (fileOutputStream != null) {
    						fileOutputStream.close();
    					}
    					down();
    				} catch (ClientProtocolException e) {
    					e.printStackTrace();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    
    		}.start();
    
    	}
    
    	void down() {
    		handler.post(new Runnable() {
    			public void run() {
    				pBar.cancel();
    				update();
    			}
    		});
    
    	}
    
    	void update() {
    
    		Intent intent = new Intent(Intent.ACTION_VIEW);
    		intent.setDataAndType(Uri.fromFile(new File(Environment
    				.getExternalStorageDirectory(), Config.UPDATE_SAVENAME)),
    				"application/vnd.android.package-archive");
    		startActivity(intent);
    	}

    还有一些细节,没有说出来~

    相关文献参考:

    http://blog.csdn.net/xjanker2/article/details/6303937 

    http://blog.csdn.net/muyu114/article/details/6623509 

    http://blog.csdn.net/w200221626/article/details/6690769

  • 相关阅读:
    CF13D. Triangles
    CF1142C. U2
    2020 省选模拟测试 Round #8 solution (20/02/07)
    2020 省选模拟测试 Round #7 solution (20/02/06)
    2020 省选模拟测试 Round #6 solution (20/02/05)
    2020 省选模拟测试 Round #5 solution (20/02/04)
    2020 省选模拟测试 Round #4 solution (20/02/03)
    CF1291D. Irreducible Anagrams
    CF1264E. Beautiful League
    bzoj2002 弹飞绵羊
  • 原文地址:https://www.cnblogs.com/Amandaliu/p/2148936.html
Copyright © 2011-2022 走看看