3、下载更新APK

下载文件以及安装APK的功能封装成通用函数,方便重用。

下载文件封装到DownLoadUtil类中,安装APK的功能封装到util类中。这两个类统一放在com.example.utils包下管理。

在工程中新建包:com.example.utils,并在该包下分别创建类DownLoadUtil、util,其中DownLoadUtil:

package com.example.utils;

import android.app.ProgressDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by sing on 13-12-24.
 * desc:
 */
public class DownLoadUtil {

    /**
     * 下载文件
     * @param urlpath 网址
     * @param filepath 本地文件路径
     * @param pd 进度条
     * @return
     */
    public static File getFile(String urlpath, String filepath, ProgressDialog pd) {
        File file = null;

        try {
            URL url = new URL(urlpath);
            file = new File(filepath);
            FileOutputStream fos = new FileOutputStream(file);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);

            //设置文件长度为进度条的最大值
            int max = conn.getContentLength();
            pd.setMax(max);

            InputStream is = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            int progress = 0;
            while ( (len = is.read(buffer))!=-1 ) {
                fos.write(buffer, 0 , len);
                progress += len;
                pd.setProgress(progress);
                Thread.sleep(30);
            }

            fos.flush();
            fos.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return file;
    }

    /**
     * 获取网址路径中的文件名
     * @param urlpath
     * @return
     */
    public static String getFileName(String urlpath) {
        return urlpath.substring(urlpath.lastIndexOf("/") + 1, urlpath.length());
    }
}

util:

package com.example.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;

import java.io.File;


/**
 * Created by sing on 13-12-24.
 * desc:
 */
public class util {
    /**
     * 安装apk
     * @param activity
     * @param file
     */
    public static void installApk(Activity activity, File file) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        activity.startActivity(intent);
    }
}

SplashActivity中需要导入:

import com.example.utils.DownLoadUtil;
import com.example.utils.util;

因为是在sdcard中下载文件,并安装apk,需要在AndroidManifest.xml中添加权限:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />


接上文,显示提示升级对话框中,为按钮“升级”和“取消”编写处理事件,用户点击“升级”按钮后创建线程下载APK,下载成功后以消息的形式发送给SplashActivity,

SplashActivity的消息处理过程接受到下载成功的消息后对下载好的APK文件进行安装。

用户点击“取消”按钮直接进入主界面。

/**
     * 显示升级提示对话框
     */
    protected void showUpdateDialog() {

        //创建对话框构造器
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //设置对话框图标
        builder.setIcon(getResources().getDrawable(R.drawable.notification));
        //设置对话框标题
        builder.setTitle("升级提示");
        //设置更新信息为对话框提示内容
        builder.setMessage(updateinfo.getDesc());

        //创建下载进度条
        pd = new ProgressDialog(SplashActivity.this);
        //设置进度条在显示时的提示消息
        pd.setMessage("正在下载");
        //设置下载进度条为水平形状
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        //设置升级按钮及响应事件
        builder.setPositiveButton("升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.i(TAG, "升级,下载:"+updateinfo.getApkurl());
                //判断sdcard是否存在
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    //显示下载进度条
                    pd.show();
                    //开启线程下载apk文件
                    new Thread() {
                        public void run() {
                            File file = new File(Environment.getExternalStorageDirectory(), DownLoadUtil.getFileName(updateinfo.getApkurl()));
                            file = DownLoadUtil.getFile(updateinfo.getApkurl(), file.getAbsolutePath(), pd);
                            if (file != null) {
                                //下载成功
                                Message msg = Message.obtain();
                                msg.what = DOWNLOAD_SUCCESS;
                                msg.obj = file;
                                handler.sendMessage(msg);
                            }else {
                                //下载失败
                                Message msg = Message.obtain();
                                msg.what = DOWNLOAD_ERROR;
                                handler.sendMessage(msg);
                            }

                            //下载完毕,关闭进度条
                            pd.dismiss();
                        };
                    }.start();
                }else{
                    Toast.makeText(getApplicationContext(), "sd卡不可用", 1).show();
                    //进入主界面
                    loadMainUI();
                }
            }
        });
        //设置取消按钮及响应事件
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //进入主界面
                loadMainUI();
            }
        });

        //创建并显示对话框
        builder.create().show();
    }

SplashActivity的消息处理过程:

                case DOWNLOAD_SUCCESS:
                    Log.i(TAG, "文件下载成功");
                    //得到消息中的文件对象,并安装
                    File file = (File)msg.obj;
                    util.installApk(SplashActivity.this, file);
                    break;
                case DOWNLOAD_ERROR:
                    Toast.makeText(getApplicationContext(), "下载文件错误", 1).show();
                    loadMainUI();
                    break;

加载主界面的函数:

    /**
     * 加载主界面
     */
    private void loadMainUI() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();// 把当前的Activity从任务栈里面移除
    }

新建主界面:

在SplashActivity的相同包名下新建“android component”,name:MainActivity,kind:Activity,并勾选:Create layout file。


接着弹出layout创建对话框,file name:activity_main,root element:LinearLayout。


主界面的设计在下一节实现。


SplashActivity的完整代码:

package com.example.mobilesafe;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.xmlpull.v1.XmlPullParserException;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import android.os.Handler;
import com.example.utils.DownLoadUtil;
import com.example.utils.util;

public class SplashActivity extends Activity {
    //常量定义
    public static final int UNKNOWN_ERROR = 99;
    public static final int GET_INFO_SUCCESS = 100;
    public static final int SERVER_ERROR = 101;
    public static final int SERVER_URL_ERROR = 102;
    public static final int PROTOCOL_ERROR = 103;
    public static final int IO_ERROR = 104;
    public static final int XML_PARSER_ERROR = 105;
    public static final int DOWNLOAD_SUCCESS = 106;
    public static final int DOWNLOAD_ERROR = 107;
    public static final String TAG = "SplashActivity";

    //获取的服务器端的更新信息
    UpdateInfo updateinfo;

    //显示版本号的tv控件
    private TextView tv_splash_version;

    //布局控件
    private RelativeLayout r1_splash;

    //升级下载进度条
    ProgressDialog pd;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //设置无标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        //设置全屏模式
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        //设置局部,显示版本号
        setContentView(R.layout.activity_splash);
        r1_splash = (RelativeLayout)findViewById(R.id.r1_splash);
        tv_splash_version = (TextView)findViewById(R.id.tv_splash_version);
        tv_splash_version.setText("版本号:" + getVersion());

        //显示渐进动画
        AlphaAnimation aa = new AlphaAnimation(0.3f, 1.0f);
        aa.setDuration(2000);
        r1_splash.startAnimation(aa);

        //检查更新
        new Thread(new checkUpdate()) {
        }.start();
    }

    //获取当前应用程序的版本号
    private String getVersion() {
        String version = "";

        //获取系统包管理器
        PackageManager pm = this.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(getPackageName(), 0);
            version = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 消息处理器
     */
    private Handler handler = new Handler() {
         public void handleMessage(Message msg) {
            switch (msg.what) {
                case UNKNOWN_ERROR:
                    Toast.makeText(getApplicationContext(), "未知错误", 1).show();
                    loadMainUI();
                    break;
                case GET_INFO_SUCCESS:
                    String serverVersion = updateinfo.getVersion();
                    String currentVersion = getVersion();
                    if (currentVersion.equals(serverVersion)) {
                        Log.i(TAG, "版本号相同无需升级,直接进入主界面");
                        loadMainUI();
                    }else {
                        Log.i(TAG, "版本号不同需升级,显示升级对话框");
                        showUpdateDialog();
                    }
                    break;
                case SERVER_ERROR:
                    Toast.makeText(getApplicationContext(), "服务器内部异常", 1).show();
                    loadMainUI();
                    break;
                case SERVER_URL_ERROR:
                    Toast.makeText(getApplicationContext(), "服务器路径错误", 1).show();
                    loadMainUI();
                    break;
                case PROTOCOL_ERROR:
                    Toast.makeText(getApplicationContext(), "协议错误", 1).show();
                    loadMainUI();
                    break;
                case XML_PARSER_ERROR:
                    Toast.makeText(getApplicationContext(), "XML解析错误", 1).show();
                    loadMainUI();
                    break;
                case IO_ERROR:
                    Toast.makeText(getApplicationContext(), "I/O错误", 1).show();
                    loadMainUI();
                    break;
                case DOWNLOAD_SUCCESS:
                    Log.i(TAG, "文件下载成功");
                    //得到消息中的文件对象,并安装
                    File file = (File)msg.obj;
                    util.installApk(SplashActivity.this, file);
                    break;
                case DOWNLOAD_ERROR:
                    Toast.makeText(getApplicationContext(), "下载文件错误", 1).show();
                    loadMainUI();
                    break;
            }
        }
    };

    /**
     * 加载主界面
     */
    private void loadMainUI() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();// 把当前的Activity从任务栈里面移除
    }

    /**
     * 检查更新
     */
    private class checkUpdate implements Runnable {
       public void run() {
           long startTime = System.currentTimeMillis();
           long endTime = startTime;
           Message msg = Message.obtain();
           try {
               //获取服务器更新地址
               String serverurl = getResources().getString(R.string.serverurl);
               URL url = new URL(serverurl);
               HttpURLConnection conn = (HttpURLConnection)url.openConnection();
               conn.setRequestMethod("GET");
               conn.setConnectTimeout(5000);
               int code = conn.getResponseCode();
               if (code == 200) {
                   //success
                   InputStream is = conn.getInputStream();
                    //解析出更新信息
                   updateinfo = UpdateInfoParser.getUpdateInfo(is);
                   endTime = System.currentTimeMillis();
                   long time = endTime - startTime;
                   if (time < 2000) {
                       try {
                           Thread.sleep(2000 - time);
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }

                   msg.what = GET_INFO_SUCCESS;
                   handler.sendMessage(msg);
               } else {
                   //服务器错误
                   msg.what = SERVER_ERROR;
                   handler.sendMessage(msg);
                   endTime = System.currentTimeMillis();
                   long time = endTime - startTime;
                   if (time < 2000) {
                       try {
                           Thread.sleep(2000 - time);
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }
               }

           } catch (MalformedURLException e) {
               msg.what = SERVER_URL_ERROR;
               handler.sendMessage(msg);
               e.printStackTrace();
           } catch (ProtocolException e) {
               msg.what = PROTOCOL_ERROR;
               handler.sendMessage(msg);
               e.printStackTrace();
           } catch (IOException e) {
               msg.what = IO_ERROR;
               handler.sendMessage(msg);
               e.printStackTrace();
           } catch (XmlPullParserException e) {
               msg.what = XML_PARSER_ERROR;
               handler.sendMessage(msg);
               e.printStackTrace();
           } catch (Exception e) {
               msg.what = UNKNOWN_ERROR;
               handler.sendMessage(msg);
               e.printStackTrace();
           }

       }
    }

    /**
     * 显示升级提示对话框
     */
    protected void showUpdateDialog() {

        //创建对话框构造器
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //设置对话框图标
        builder.setIcon(getResources().getDrawable(R.drawable.notification));
        //设置对话框标题
        builder.setTitle("升级提示");
        //设置更新信息为对话框提示内容
        builder.setMessage(updateinfo.getDesc());

        //创建下载进度条
        pd = new ProgressDialog(SplashActivity.this);
        //设置进度条在显示时的提示消息
        pd.setMessage("正在下载");
        //设置下载进度条为水平形状
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        //设置升级按钮及响应事件
        builder.setPositiveButton("升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.i(TAG, "升级,下载:"+updateinfo.getApkurl());
                //判断sdcard是否存在
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    //显示下载进度条
                    pd.show();
                    //开启线程下载apk文件
                    new Thread() {
                        public void run() {
                            File file = new File(Environment.getExternalStorageDirectory(), DownLoadUtil.getFileName(updateinfo.getApkurl()));
                            file = DownLoadUtil.getFile(updateinfo.getApkurl(), file.getAbsolutePath(), pd);
                            if (file != null) {
                                //下载成功
                                Message msg = Message.obtain();
                                msg.what = DOWNLOAD_SUCCESS;
                                msg.obj = file;
                                handler.sendMessage(msg);
                            }else {
                                //下载失败
                                Message msg = Message.obtain();
                                msg.what = DOWNLOAD_ERROR;
                                handler.sendMessage(msg);
                            }

                            //下载完毕,关闭进度条
                            pd.dismiss();
                        };
                    }.start();
                }else{
                    Toast.makeText(getApplicationContext(), "sd卡不可用", 1).show();
                    //进入主界面
                    loadMainUI();
                }
            }
        });
        //设置取消按钮及响应事件
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //进入主界面
                loadMainUI();
            }
        });

        //创建并显示对话框
        builder.create().show();
    }
}



运行效果图:







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

asmcvc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值