版本更新的两个重要类

发布时间:2020-07-10 21:32:09 作者:truesea
来源:网络 阅读:358

1. VersionUpdate用于检测是否有新版本,以及如果有新版本以何种方式提示给用户。

public class VersionUpdate {
                                                                                                                                                                                 
    private String TAG = "VersionUpdate";
    public final String APK_URL = "http://gdown.baidu.com/data/wisegame/086ad68302fb074d/WeChat_352.apk";
    private Context context;
    private UpdateManager updateManager;
    private int mUpdateRole = 12; // 版本更新用到
    private UpdateListener updateListener;
                                                                                                                                                                                 
    public void setUpdateListener(UpdateListener updateListener) {
        this.updateListener = updateListener;
    }
                                                                                                                                                                                 
    public interface UpdateListener {
        public void onUpdate(double remoteVersion, double localVersion);
    }
                                                                                                                                                                                 
    public VersionUpdate(Context context) {
                                                                                                                                                                                     
        this.context = context;
        updateManager = new UpdateManager(context);
    }
                                                                                                                                                                                 
    public void checkUpdate() {
                                                                                                                                                                                     
        IVideoFetcher.CallBack callback = new IVideoFetcher.CallBackAdapter() {
                                                                                                                                                                                         
            @Override
            public void onComplete(IVideoResult result) {
                if(!result.isSuccess()) return;
                VersionData data = (VersionData)result.getData();
                if(data == null) return;
                data.setApkUrl(APK_URL);
                updateManager.setApkUrl(data.getApkUrl());
                Log.i(TAG, new Gson().toJson(data));
                double remoteVersion = 0.0;
                double localVersion = 0.0;
                try {
                    remoteVersion = Double.valueOf(data.getVersion());
                    localVersion = Double.valueOf(getVersion());
                    mUpdateRole = Integer.valueOf(data.getRole());
                } catch(NumberFormatException ex) {
                    ex.printStackTrace();
                }
                updateListener.onUpdate(remoteVersion, localVersion);
            }
        };
                                                                                                                                                                                     
        String url = IVideoURL.TvieURL.VERSION_URL;
                                                                                                                                                                                     
        Map<String, String> params = new HashMap<String, String>();
        params.put("version", getVersion());
        params.put("productId", context.getPackageName());
        params.put("platform", "android");
        params.put("os", Build.VERSION.CODENAME);
                                                                                                                                                                                     
        IVideoFetcher.doGet(VersionResult.class, callback, url, params);
    }
                                                                                                                                                                                 
    public void confirmUpdate() {
        AlertDialog.Builder builder = new Builder(context);
        builder.setMessage("亲,有更新版本的软件包哦,请快下载更新吧");
        builder.setTitle("更新提示");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                updateManager.beginUpdate();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }
                                                                                                                                                                                 
    public void alertNeedUpdate() {
        AlertDialog.Builder builder = new Builder(context);
        builder.setMessage("亲,有更新版本的软件包哦,请快下载更新吧");
        builder.setTitle("更新提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                updateManager.beginUpdate();
            }
        });
        builder.create().show();
    }
                                                                                                                                                                                 
    public void alertNoUpdate() {
        AlertDialog.Builder builder = new Builder(context);
        builder.setMessage("亲,该版本已是最新版本,无需升级");
        builder.setTitle("更新提示");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }
                                                                                                                                                                                 
    /**
     * 获取版本号
     * @return 当前应用的版本号
     */
    public String getVersion() {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "0.0";
        }
    }
                                                                                                                                                                                 
    public void update() {
        switch(mUpdateRole) {
        case 10:
            confirmUpdate();
            break;
        case 11:
            alertNeedUpdate();
            break;
        case 9:
        case 12:
            alertNoUpdate();
            break;
        }
    }
}

2. UpdateManager用于从服务端下载新的apk文件,下载完成提示用户安装。

public class UpdateManager {
    private Context mContext;
                                                                                                                                                                              
    //提示语
    private String updateMsg = "有最新的软件包哦,亲快下载吧~";
                                                                                                                                                                              
    //返回的安装包url
    private String apkUrl;
                                                                                                                                                                              
    private Dialog noticeDialog;
                                                                                                                                                                              
    private Dialog downloadDialog;
     /* 下载包安装路径 */
//    private static final String savePath = "/sdcard/com.tvie.xj.ivideo/";
    private static final String savePath = TvieApplication.getInstance().getCacheDirPath();
    private static final String saveFileName = savePath + "/com.tvie.xj.ivideo.apk";
    /* 进度条与通知ui刷新的handler和msg常量 */
    private ProgressBar mProgress;
    private TextView mProgressHint;
                                                                                                                                                                              
    private static final int DOWN_UPDATE = 1;
                                                                                                                                                                              
    private static final int DOWN_OVER = 2;
                                                                                                                                                                              
    private int progress;
    private int current;
    private int total;
                                                                                                                                                                              
    private Thread downLoadThread;
                                                                                                                                                                              
    private boolean interceptFlag = false;
                                                                                                                                                                              
    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case DOWN_UPDATE:
                mProgress.setProgress(progress);
                mProgressHint.setText(DigitalUtil.toFileSizeFormat(mContext, current)
                        +"/"+DigitalUtil.toFileSizeFormat(mContext, total));
                break;
            case DOWN_OVER:
                if(downloadDialog != null) {
                    downloadDialog.dismiss();
                }
                installApk();
                break;
            default:
                break;
            }
        };
    };
                                                                                                                                                                              
    public UpdateManager(Context context) {
        this.mContext = context;
    }
                                                                                                                                                                              
    public void setApkUrl(String apkUrl) {
        this.apkUrl = apkUrl;
    }
                                                                                                                                                                              
    //外部接口让主Activity调用
    public void checkUpdateInfo(){
        showNoticeDialog();
    }
                                                                                                                                                                              
                                                                                                                                                                              
    private void showNoticeDialog(){
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("软件版本更新");
        builder.setMessage(updateMsg);
        builder.setPositiveButton("下载", new OnClickListener() {        
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                showDownloadDialog();          
            }
        });
        builder.setNegativeButton("以后再说", new OnClickListener() {          
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();              
            }
        });
        noticeDialog = builder.create();
        noticeDialog.show();
    }
                                                                                                                                                                              
    public void beginUpdate(String apkUrl) {
        this.apkUrl = apkUrl;
        showDownloadDialog();
    }
                                                                                                                                                                              
    public void beginUpdate() {
        showDownloadDialog();
    }
                                                                                                                                                                              
    private void showDownloadDialog(){
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("正在下载新版本");
                                                                                                                                                                                  
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.update_progress, null);
        mProgress = (ProgressBar)v.findViewById(R.id.progress);
        mProgressHint = (TextView)v.findViewById(R.id.progressHint);
                                                                                                                                                                                  
        builder.setView(v);
        builder.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                interceptFlag = true;
                mHandler.removeMessages(DOWN_UPDATE);
                mHandler.removeMessages(DOWN_OVER);
            }
        });
        downloadDialog = builder.create();
        downloadDialog.show();
                                                                                                                                                                                  
        downloadApk();
    }
                                                                                                                                                                              
    private Runnable mdownApkRunnable = new Runnable() {   
        @Override
        public void run() {
            try {
                URL url = new URL(apkUrl);
                                                                                                                                                                                      
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();
                                                                                                                                                                                          
                File file = new File(savePath);
                if(!file.exists()){
                    file.mkdir();
                }
                File apkFile = new File(saveFileName);
                if(apkFile.exists()) {
                    apkFile.delete();
                }
                FileOutputStream fos = new FileOutputStream(apkFile);
                                                                                                                                                                                          
                int count = 0;
                byte buf[] = new byte[1024];
                                                                                                                                                                                          
                do{                
                    int numread = is.read(buf);
                    count += numread;
                    progress =(int)(((float)count / length) * 100);
                    current = count;
                    total = length;
                    //更新进度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if(numread <= 0){   
                        //下载完成通知安装
                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf,0,numread);
                }while(!interceptFlag);//点击取消就停止下载.
                if(interceptFlag && apkFile.exists()) {
                    apkFile.delete();
                }
                fos.close();
                is.close();
                conn.disconnect();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch(IOException e){
                e.printStackTrace();
            }
        }
    };
                                                                                                                                                                              
     /**
     * 下载apk
     * @param url
     */
                                                                                                                                                                              
    private void downloadApk(){
        interceptFlag = false;
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }
     /**
     * 安装apk
     * @param url
     */
    private void installApk(){
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }   
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(i);
                                                                                                                                                                              
    }
}

3. 以上两个类经过验证,可以直接利用,只需检测新版本的代码。下面给出版本更新的用法。

(1)在刚启动应用时,检测新版本,并提示用户更新。

在MainActivity的onCreate方法中创建VersionUpdate对象,并检测更新。

mVersionUpdate = new VersionUpdate(this);
mVersionUpdate.setUpdateListener(updateListener);
mVersionUpdate.checkUpdate();

其中UpdateListener定义为

VersionUpdate.UpdateListener updateListener = new VersionUpdate.UpdateListener() {
                                           
    @Override
    public void onUpdate(double remoteVersion, double localVersion) {
        if (remoteVersion > localVersion) {
            mVersionUpdate.update();
        }
    }
};

(2)在设置界面,检测新版本,用户点击时提示用户更新。

设置界面是一个Fragment,同样也是在onCreate方法中创建VersionUpdate对象

mVersionUpdate = new VersionUpdate(getActivity());
mVersionUpdate.setUpdateListener(updateListener);

定义UpdateListener实例对象

VersionUpdate.UpdateListener updateListener = new VersionUpdate.UpdateListener() {
        
    @Override
    public void onUpdate(double remoteVersion, double localVersion) {
        if (remoteVersion > localVersion) {
            mNewFlag.setVisibility(View.VISIBLE);
        } else {
            mNewFlag.setVisibility(View.INVISIBLE);
        }
    }
};


推荐阅读:
  1. grafana版本更新
  2. 类的应用场景(重要运用补充)类的组合继承

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

版本更新 重要类

上一篇:Apache - AH00451

下一篇:浅析laravel门面原理与实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》