android 开发 App下载更新

最近在项目中做了App 根据后台返回的版本值,提示更新下载安装新的版本;做之前看了几篇文章,实现起来不是特难,主要是使用了自带的一个类 DownloadManager下载,通过广播进行安装;

一、获取当前的版本号

/**
     * 获取版本号
     */
    public static int getAppVersionCode(Context context) {
        int versioncode = -1;
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versioncode = pi.versionCode;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versioncode;
    }

二、请求后台,获取新的版本号,进行对比提示更新(新的版本号本地模拟的)

 /**
     * 检测版本更新
     *
     * @param context
     * @param isForceCheck 是否强制检测更新
     *                     true强制 - 无论什么网络环境都会提示更新
     *                     false非强制 - WiFi情况下才提示更新
     *                     newVersionCode- 后台请求的版本号
     *                     updataInfo- 更新的内容
     */
    public static void checkUpdate(final Context context, final boolean isForceCheck,int newVersionCode,String updataInfo) {
        if (!NetUtils.isConnected(context)) {
            // 无网络时
            if (isForceCheck) {
                // 手动强制检测更新时,提示文字
                Toasts.show(context, "请检查网络连接");
            } else {
                // 非强制不做操作
            }
            return;
        }
        // 开始检测更新

        if(newVersionCode>Tools.getAppVersionCode(context)){
            showUpdateConfirmDialog(context,updataInfo);
        }

    }

    /**
     * 显示更新对话框,包含版本相关信息
     */
    private static void showUpdateConfirmDialog(final Context context, final String updateInfo) {
        new AlertDialog.Builder(context)
                .setTitle("发现新版本")
                .setMessage(updateInfo)
                .setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (NetUtils.isWifi(context)) {
                            downLoadApp(context);
                        } else {
                            DialogUtils.showCommonDialog(context, "您当前使用的移动网络,是否继续更新。", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    downLoadApp(context);
                                }
                            }).show();
                        }
                    }
                })
                .setNegativeButton("以后再说", null)
                .show();
    }
    /**
     * 下载文件
     * @param context
     */
    public static void downLoadApp(Context context){

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downurl));
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle("app更新");
        request.setDescription("app正在下载");
        request.setAllowedOverRoaming(false);
        //设置文件存放目录
        //判断文件是否存在,保证其唯一性
        File file = context.getExternalFilesDir("Download/ccyj");
        if(file.exists()){
            file.delete();
        }
        request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, "downapp");
        DownloadManager downManager = (DownloadManager)context.getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE);
        long id = downManager.enqueue(request);
     // 存储下载Key
        SharedPreferences sharedPreferences = context.getSharedPreferences("downloadapp", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putLong("downloadid",id);
        editor.commit();
    }

判断手机是否是wifi连接

  /**
     * 判断是否是wifi连接
     */
    public static boolean isWifi(Context context) {
        ConnectivityManager cm = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (null == cm) {
            return false;
        }

        NetworkInfo info = cm.getActiveNetworkInfo();
        if (null != info) {
            if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                return true;
            }
        }
        return false;

    }

三、注册广播接收器, 接收消息ACTION_DOWNLOAD_COMPLETE
, 下载完成会发送广播. 获取下载文件的Uri, 进行匹配, 发送安装消息, 自动安装.

 /**
     * 初始化app更新广播
     */
    private void initUpdata() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
        filter.addCategory("android.intent.category.DEFAULT");
        receiver = new DownLoadCompleteReceiver();
        registerReceiver(receiver, filter);
    }
/**

 * Created by zzj on 2016/11/22.
 */
public class DownLoadCompleteReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            installApk(context, id);
        } else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
        }
    }

    /**
     * 下载完后安装apk
     *
     * @param
     */

    // 安装Apk
    private void installApk(Context context, long downloadApkId) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("downloadapp", Activity.MODE_PRIVATE);
        long id = sharedPreferences.getLong("downloadid", 0);

        // 获取存储ID
        if (downloadApkId == id) {
            DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

            Uri downloadFileUri = dManager.getUriForDownloadedFile(downloadApkId);
            if (downloadFileUri != null) {
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setDataAndType(Uri.fromFile(context.getExternalFilesDir("Download/downapp")), "application/vnd.android.package-archive");
                install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(install);
            } else {
                Toasts.show(context,"下载失败");
            }
        }
    }
}


文/zzj丶(简书作者)
原文链接:http://www.jianshu.com/p/27b263540e15
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值