欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

联网更新版本功能的流程说明

程序员文章站 2022-04-19 10:25:28
...

版本更新的流程逻辑图
联网更新版本功能的流程说明
1、判断手机是否可以联网

    /**
     * 判断手机是否联网
     * ConnectivityManager
     */
    private boolean isConnected() {
        boolean connected = false;

        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null) {
            connected = networkInfo.isConnected();
        }
        return connected;
    }

2、有移动网络,联网获取服务器的最新版本
①联网成功:获取当前版本号与从服务器获取的版本号做比较,如果一致则进入主页面MainActivity.class,否则弹出一个版本更新弹出框

               case DOWNLOAD_VERSION_SUCCESS:
                    //获取当前应用的版本信息
                    String version = getVersion();
                    //更新页面显示的版本信息
                    tvWelcomeVersion.setText(version);
                    //比较服务器获取的最新版本跟本应用的版本是否一致
                    if (version.equals(updateInfo.version)) {
                        UIUtils.toast("已經是最新版本", false);
                        toMain();
                    } else {
                        showDownloadDialog();
                    }
                    break;

    /**
     * 获取当前版本号
     *
     * @return
     */
    private String getVersion() {
        String version = "未知版本";
        PackageManager manager = getPackageManager();
        try {
            PackageInfo packageInfo = manager.getPackageInfo(getPackageName(), 0);
            version = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            //e.printStackTrace(); //如果找不到对应的应用包信息, 就返回"未知版本"
        }
        return version;
    }
    /**
     * 显示下载的dialog
     */
    private void showDownloadDialog() {
        new AlertDialog.Builder(this)
                .setTitle("下载最新版本")
                .setMessage(updateInfo.desc)
                .setPositiveButton("立即下载", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //启动分线程下载apk
                        downloadApk();
                    }
                })
                .setNegativeButton("暂不下载", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toMain();
                    }
                })
                .show();
    }

    /**
     * 下載最新的APK
     */
    private ProgressDialog dialog;//新建一个下载进度条
    private File apkFile;//apk文件数据
    private void downloadApk() {
        //初始化dialog
        dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.show();
        //初始化数据要保存的位置
        File filesDir;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            filesDir = this.getExternalFilesDir("");
        } else {
            filesDir = this.getFilesDir();
        }
        apkFile = new File(filesDir, "update.apk");
        //启动一个分线程联网下载数据:
        new Thread() {
            @Override
            public void run() {
                String path = updateInfo.apkUrl;
                InputStream is = null;
                FileOutputStream fos = null;
                HttpURLConnection conn = null;
                try {
                    URL url = new URL(path);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    conn.connect();
                    if (conn.getResponseCode() == 200) {
                        dialog.setMax(conn.getContentLength());//设置dialog的最大值
                        is = conn.getInputStream();
                        fos = new FileOutputStream(apkFile);
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = is.read(buffer)) != -1) {
                            //更新dialog的进度
                            dialog.incrementProgressBy(len);
                            fos.write(buffer, 0, len);
                        }
                        handler.sendEmptyMessage(DOWNLOAD_APK_SUCCESS);
                        UIUtils.toast("下载应用数据成功", false);
                    } else {
                        handler.sendEmptyMessage(DOWNLOAD_APK_FAIL);
                        UIUtils.toast("联网下载数据失败", false);
                        toMain();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }.start();
    }

下载完成之后,销毁dialog,安装apk,销毁WelcomActivity

 case DOWNLOAD_APK_SUCCESS:
                    UIUtils.toast("下载应用数据成功", false);
                    dialog.dismiss();
                    installApk();//安装Apk
                    finish();//结束当前的WelcomeActivity的显示
                    break;
    /**
     * 安装apk应用
     */
    private void installApk() {
        Intent intent = new Intent("android.intent.action.INSTALL_PACKAGE");
        intent.setData(Uri.parse("file:" + apkFile.getAbsolutePath()));
        startActivity(intent);
    }

②联网失败:进入主页面MainActivity.class


    /**
     * 更新APK版本
     */
    private void updateApkFile() {
        //获取系统当前时间
        startTime = System.currentTimeMillis();
        //1、判断手机是否可以联网
        boolean connect = isConnected();
        if (!connect) {//没有移动网络
            UIUtils.toast("当前没有移动数据网络", false);
            toMain();
        } else {//有移动网络
            //联网获取服务器的最新版本
            AsyncHttpClient client = new AsyncHttpClient();
            String url = AppNetConfig.UPDATE;
            client.post(url, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(String content) {
                    //解析json数据
                    updateInfo = JSON.parseObject(content, UpdateInfo.class);
                    handler.sendEmptyMessage(DOWNLOAD_VERSION_SUCCESS);
                }

                @Override
                public void onFailure(Throwable error, String content) {
                    handler.sendEmptyMessage(DOWNLOAD_APK_FAIL);
                }
            });
        }
    }
/**
 * 作者: willkong on 2017/11/24.
 * 作用:版本信息
 */
public class UpdateInfo {
    public String version;//服务器的最新版本
    public String apkUrl;//最新版本的路径
    public String desc;//版本更新细节


}
    private static final int TO_MAIN = 1;
    private static final int DOWNLOAD_VERSION_SUCCESS = 2;
    private static final int DOWNLOAD_APK_SUCCESS = 3;
    private static final int DOWNLOAD_APK_FAIL = 4;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TO_MAIN://进入MainActivity主页面
                    finish();//结束当前的WelcomeActivity
                    startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
                    break;
                case DOWNLOAD_VERSION_SUCCESS:
                    //获取当前应用的版本信息
                    String version = getVersion();
                    //更新页面显示的版本信息
                    tvWelcomeVersion.setText(version);
                    //比较服务器获取的最新版本跟本应用的版本是否一致
                    if (version.equals(updateInfo.version)) {
                        UIUtils.toast("已經是最新版本", false);
                        toMain();
                    } else {
                        showDownloadDialog();
                    }
                    break;
                case DOWNLOAD_APK_SUCCESS:
                    UIUtils.toast("下载应用数据成功", false);
                    dialog.dismiss();
                    installApk();//安装Apk
                    finish();//结束当前的WelcomeActivity的显示
                    break;
                case DOWNLOAD_APK_FAIL:
                    UIUtils.toast("联网请求数据失败", false);
                    toMain();
                    break;
            }
        }
    };
    /**
     * 进入主界面
     */
    private void toMain() {
        //保证动画已经执行完毕
        long currentTime = System.currentTimeMillis();
        long delayTime = 3000 - (currentTime - startTime);
        if (delayTime < 0) {
            delayTime = 0;
        }
        //等待动画执行完进入主界面
        handler.sendEmptyMessageDelayed(TO_MAIN, delayTime);
    }

整体的文件代码


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
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.SystemClock;
import android.support.annotation.Nullable;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.willkong.p2pclient.R;
import com.willkong.p2pclient.bean.UpdateInfo;
import com.willkong.p2pclient.common.AppNetConfig;
import com.willkong.p2pclient.util.UIUtils;

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

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 作者: willkong on 2017/10/31.
 * 作用:欢迎界面
 */
public class WelcomeActivity extends Activity {
    private static final int TO_MAIN = 1;
    private static final int DOWNLOAD_VERSION_SUCCESS = 2;
    private static final int DOWNLOAD_APK_SUCCESS = 3;
    private static final int DOWNLOAD_APK_FAIL = 4;
    @Bind(R.id.iv_welcome_icon)
    ImageView ivWelcomeIcon;
    @Bind(R.id.rl_welcome)
    RelativeLayout rlWelcome;
    @Bind(R.id.tv_welcome_version)
    TextView tvWelcomeVersion;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TO_MAIN:
                    finish();//结束当前的WelcomeActivity
                    startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
                    break;
                case DOWNLOAD_VERSION_SUCCESS:
                    //获取当前应用的版本信息
                    String version = getVersion();
                    //更新页面显示的版本信息
                    tvWelcomeVersion.setText(version);
                    //比较服务器获取的最新版本跟本应用的版本是否一致
                    if (version.equals(updateInfo.version)) {
                        UIUtils.toast("已經是最新版本", false);
                        toMain();
                    } else {
                        showDownloadDialog();
                    }
                    break;
                case DOWNLOAD_APK_SUCCESS:
                    UIUtils.toast("下载应用数据成功", false);
                    dialog.dismiss();
                    installApk();//安装Apk
                    finish();//结束当前的WelcomeActivity的显示
                    break;
                case DOWNLOAD_APK_FAIL:
                    UIUtils.toast("联网请求数据失败", false);
                    toMain();
                    break;
            }
        }
    };

    /**
     * 安装apk应用
     */
    private void installApk() {
        Intent intent = new Intent("android.intent.action.INSTALL_PACKAGE");
        intent.setData(Uri.parse("file:" + apkFile.getAbsolutePath()));
        startActivity(intent);
    }

    /**
     * 显示下载的dialog
     */
    private void showDownloadDialog() {
        new AlertDialog.Builder(this)
                .setTitle("下载最新版本")
                .setMessage(updateInfo.desc)
                .setPositiveButton("立即下载", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //启动分线程下载apk
                        downloadApk();
                    }
                })
                .setNegativeButton("暂不下载", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toMain();
                    }
                })
                .show();
    }

    /**
     * 下載最新的APK
     */
    private ProgressDialog dialog;
    private File apkFile;
    private void downloadApk() {
        //初始化dialog
        dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.show();
        //初始化数据要保存的位置
        File filesDir;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            filesDir = this.getExternalFilesDir("");
        } else {
            filesDir = this.getFilesDir();
        }
        apkFile = new File(filesDir, "update.apk");
        //启动一个分线程联网下载数据:
        new Thread() {
            @Override
            public void run() {
                String path = updateInfo.apkUrl;
                InputStream is = null;
                FileOutputStream fos = null;
                HttpURLConnection conn = null;
                try {
                    URL url = new URL(path);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    conn.connect();
                    if (conn.getResponseCode() == 200) {
                        dialog.setMax(conn.getContentLength());//设置dialog的最大值
                        is = conn.getInputStream();
                        fos = new FileOutputStream(apkFile);
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = is.read(buffer)) != -1) {
                            //更新dialog的进度
                            dialog.incrementProgressBy(len);
                            fos.write(buffer, 0, len);
                            SystemClock.sleep(1);
                        }
                        handler.sendEmptyMessage(DOWNLOAD_APK_SUCCESS);
                        UIUtils.toast("下载应用数据成功", false);
                    } else {
                        handler.sendEmptyMessage(DOWNLOAD_APK_FAIL);
                        UIUtils.toast("联网下载数据失败", false);
                        toMain();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }.start();
    }

    /**
     * 当前版本号
     *
     * @return
     */
    private String getVersion() {
        String version = "未知版本";
        PackageManager manager = getPackageManager();
        try {
            PackageInfo packageInfo = manager.getPackageInfo(getPackageName(), 0);
            version = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            //e.printStackTrace(); //如果找不到对应的应用包信息, 就返回"未知版本"
        }
        return version;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去掉窗口标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //隐藏顶部的状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_welcome);
        ButterKnife.bind(this);
        //提供启动动画
        setAnimation();

        //联网更新应用
        updateApkFile();
    }

    long startTime;
    UpdateInfo updateInfo;

    /**
     * 更新APK版本
     */
    private void updateApkFile() {
        //获取系统当前时间
        startTime = System.currentTimeMillis();
        //1、判断手机是否可以联网
        boolean connect = isConnected();
        if (!connect) {//没有移动网络
            UIUtils.toast("当前没有移动数据网络", false);
            toMain();
        } else {//有移动网络
            //联网获取服务器的最新版本
            AsyncHttpClient client = new AsyncHttpClient();
            String url = AppNetConfig.UPDATE;
            client.post(url, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(String content) {
                    //解析json数据
                    updateInfo = JSON.parseObject(content, UpdateInfo.class);
                    handler.sendEmptyMessage(DOWNLOAD_VERSION_SUCCESS);
                }

                @Override
                public void onFailure(Throwable error, String content) {
                    handler.sendEmptyMessage(DOWNLOAD_APK_FAIL);
                }
            });
        }
    }

    /**
     * 进入主界面
     */
    private void toMain() {
        //保证动画已经执行完毕
        long currentTime = System.currentTimeMillis();
        long delayTime = 3000 - (currentTime - startTime);
        if (delayTime < 0) {
            delayTime = 0;
        }
        //等待动画执行完进入主界面
        handler.sendEmptyMessageDelayed(TO_MAIN, delayTime);
    }

    /**
     * 判断手机是否联网
     * ConnectivityManager
     */
    private boolean isConnected() {
        boolean connected = false;

        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null) {
            connected = networkInfo.isConnected();
        }
        return connected;
    }

    private void setAnimation() {
        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);//0:完全透明  1:完全不透明
        alphaAnimation.setDuration(3000);
        alphaAnimation.setInterpolator(new AccelerateInterpolator());//设置动画的变化率

//        //方式一:
//        alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
//            @Override
//            public void onAnimationStart(Animation animation) {
//
//            }
//
//            //当动画结束时:调用如下方法
//            @Override
//            public void onAnimationEnd(Animation animation) {
//                Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
//                startActivity(intent);
//                finish();//销毁当前页面
//            }
//
//            @Override
//            public void onAnimationRepeat(Animation animation) {
//
//            }
//        });
        //方式二:使用handler
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
//                startActivity(intent);
////                finish();//销毁当前页面
//                //结束activity的显示,并从栈空间中移除
//                ActivityManager.getInstance().remove(WelcomeActivity.this);
//            }
//        }, 3000);

        //启动动画
        rlWelcome.startAnimation(alphaAnimation);

    }
}
相关标签: boolean 手机