zoukankan      html  css  js  c++  java
  • android 软件在线版本更新功能的实现

    首先需要建立几个辅助类:

    一、ConnectUtil类,判断时候具有可用网络,需要借助系统的ConnectivityManager

    public class ConnectUtil {
        public static boolean isConnect(Context context){
            ConnectivityManager manager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if(manager!=null){
                NetworkInfo info=manager.getActiveNetworkInfo();
                if(info!=null&&info.isConnected()){
                    if(info.getState()==NetworkInfo.State.CONNECTED){
                        return true;
                    }
                }
            }
            return false;
        }
    }

    二、检查已有的版本信息,借助系统的packagerManager类

        PackageManager manager = getPackageManager();
            PackageInfo info;
            try {
                info = manager.getPackageInfo(getPackageName(), 0);
            } catch (NameNotFoundException e) {
                e.printStackTrace();
            }
            String versionName = info.versionName;
            // 下载时刻出现一个进度条
            pd = new ProgressDialog(this);

    三、从服务器上下载apk文件

    这里有两个问题尚未彻底弄明白:URLencoding进行URL编码的意义何在

    封装后的HttpGet、HttpPost仅仅适用于请求返回为字符串的情况吗?如果请求返回二进制的apk,或者图片,就必须借助原始的HttpURLConnection?

    package com.example.util;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.List;
    import java.util.Map;
    
    import org.apache.http.HttpConnection;
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpStatus;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EncodingUtils;
    import org.apache.http.util.EntityUtils;
    
    import android.app.ProgressDialog;
    import android.content.SharedPreferences;
    import android.os.Environment;
    
    public class DownLoadUtil {
        // 下载apk并将其保存在sd卡的路径中
        public void downloadApk(String urlPath, ProgressDialog pd) {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;
                FileOutputStream fos = null;
    
                try {
                    // url中带有中文,之前首先需要编码
                    // 应当仅仅编码其中的中文部分
                    /*
                     * System.out.println("编码前"+urlPath);
                     * System.out.println("编码后"+URLEncoder.encode(urlPath));
                     */
                    urlPath = URLEncoder.encode(urlPath).replaceAll("%3A", ":")
                            .replaceAll("%2F", "/");
                    System.out.println(urlPath);
                    URL url = new URL(urlPath);
                    HttpURLConnection connection = (HttpURLConnection) url
                            .openConnection();
                    connection.setConnectTimeout(5000);
                    bis = new BufferedInputStream(connection.getInputStream());
                    File file = new File(Environment.getExternalStorageDirectory()
                            + "/update/");
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    // 如果下载的时候需要出现进度条
    
                    // 如果实现文件不存在的话,outputstream构造函数调用时候会自动创建新文件
                    //但是前提是目录需要存在
                    fos = new FileOutputStream(file.getAbsolutePath() + "/绿萝空气.apk");
                    bos = new BufferedOutputStream(fos);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    int total = 0;
                    pd.setMax(connection.getContentLength());
                    while ((len = bis.read(buffer)) > 0) {
                        bos.write(buffer);
                        total += len;
                        pd.setProgress(total);
                        if (total == pd.getMax()) {
                            pd.dismiss();
                        }
                    }
    
                } catch (Exception e) {
                    e.printStackTrace();
    
                } finally {
                    try {
                        bis.close();
                        fos.close();
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                }
    
            }
    
        }
    
        /*// 如果发送的是get请求,使用这种方法可以下载apk么?
        public String sendGetRequest(String url) {
            HttpGet get = new HttpGet(url);
            HttpClient client = new DefaultHttpClient();
            try {
                HttpResponse result = client.execute(get);
    
                if (result != null
                        && result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    
                     * BufferedInputStream bis=new
                     * BufferedInputStream(result.getEntity().getContent()) ; byte[]
                     * buffer=new byte[bis.available()]; bis.read(buffer);
                     * System.out.println(new String(buffer));
                     
                    String resultString = EntityUtils.toString(result.getEntity());
                    // System.out.println(resultString);
                    return resultString;
                }
    
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
    
            }
            return null;
    
        }
    */
    }


    apk的安装,借助系统的intent

        protected void installApk(File file) {
            Intent intent = new Intent();
            // 执行动作
            // 这里是系统配置的intent,因此不需要在配置文件中进行过多的更改
            intent.setAction(Intent.ACTION_VIEW);
            // 执行的数据类型
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
            startActivity(intent);
        }

    这时候发现了一个问题,apk安装时候提示“解析包时出现问题”;是由于签名的原因吗?不很确定

  • 相关阅读:
    LibreOJ2302
    POJ3693
    BZOJ3697
    BZOJ2599
    BZOJ2152
    BZOJ1468
    BZOJ4653
    BZOJ4553
    BZOJ4552
    BZOJ4551
  • 原文地址:https://www.cnblogs.com/bobodeboke/p/3072536.html
Copyright © 2011-2022 走看看