android app 自动更新功能 局域网IIS 和互联网访问

//调用 
DownloadUtil.checkToUpdate(MainMenu.this, true);


public class DownloadUtil {

    //下载器
    private DownloadManager downloadManager;
    //上下文
    private Context mContext;
    //下载的ID
    private long downloadId;

    private String mName;

    private static boolean checkIsSameVersion(String curVersion, String serverApkFileName) {
        String serverVersion = serverApkFileName.substring(serverApkFileName.indexOf("-") + 1).replace(".apk", "");
        return curVersion.equals(serverVersion);
    }

    public static void checkToUpdate(final Activity activity, final boolean autoUpdate) {
        new LoginCalls().getRFUpdateAPKFile(
                new SoapCallback<GetRFUpdateAPKFileResult>() {

                    @Override
                    public void onSuccess(GetRFUpdateAPKFileResult response) {
                        if (response.getSoapResult() != 0) {
                            onFailure(response.getPoErrMsg());
                            return;
                        }

                        final String fileName = response.getPoAPKFileName(); //Update/xxx.apk
                        if (TextUtils.isEmpty(fileName)) {
                            if (!autoUpdate) {
                                UIUtil.showMsgDialog(activity, activity.getString(R.string.hint), "服务器上未找到更新文件");
                            }
                            return;
                        }

                        final String apkName = fileName.substring(fileName.indexOf("/") + 1);
                        if (!checkIsSameVersion(BuildConfig.VERSION_NAME, apkName)) {
                            UIUtil.showConfirm(true, activity, activity.getString(R.string.kindly_reminder),
                                    activity.getString(R.string.want_to_update), activity.getString(R.string.update), new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            //检查权限
                                            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                                UIUtil.toastLong(activity, "无法获取存储权限,请查看应用权限设置");
                                            }
                                            // IIS模式   需要具体到文件名    
											String fileFullName = "http://" + PreferenceUtils.getString(ConstValues.KEY_IPADDRESS) + "/" + PreferenceUtils.getString(ConstValues.KEY_PREFIX) + "/" + fileName;

                                            //http模式 只需要具体到路径即可
                                            String fileFullName = "http://" + PreferenceUtils.getString(ConstValues.KEY_IPADDRESS) + "/" + PreferenceUtils.getString(ConstValues.KEY_PREFIX) ;
                                            
                                            getDownLoadInstance(activity).downloadAPK(apkName, fileFullName);
                                        }
                                    }, activity.getString(R.string.cancel), new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                        }
                                    }, null);
                        } else {
                            if (!autoUpdate) {
                                UIUtil.toastShort(activity, "已是最新版本无需更新");
                            }
                        }
                    }
                });
    }

    public static DownloadUtil getDownLoadInstance(Context context) {
        return new DownloadUtil(context);
    }

    public DownloadUtil(Context context){
        this.mContext = context;
    }

    //下载apk
    public void downloadAPK(String appName, String appUpdateFieldPath) {
        mName = appName;
        //创建下载任务
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(appUpdateFieldPath));

        //移动网络情况下是否允许漫游
        request.setAllowedOverRoaming(true);

        //在通知栏中显示,默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle("下载");
        request.setDescription("正在下载 " + appName);
        request.setVisibleInDownloadsUi(true);

        //设置下载的路径
        File file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), appName);
        request.setDestinationUri(Uri.fromFile(file));
        //获取DownloadManager
        if (downloadManager == null)
            downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        //将下载请求加入下载队列,加入下载队列后会给该任务返回一个long型的id,通过该id可以取消任务,重启任务、获取下载的文件等等
        if (downloadManager != null) {
            downloadId = downloadManager.enqueue(request);
        }
        //注册广播接收者,监听下载状态
        mContext.registerReceiver(receiver,
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    //广播监听下载的各个状态
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkStatus();
        }
    };

    //检查下载状态
    private void checkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        //通过下载的id查找
        query.setFilterById(downloadId);
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //下载暂停
                case DownloadManager.STATUS_PAUSED:
                    break;
                //下载延迟
                case DownloadManager.STATUS_PENDING:
                    break;
                //正在下载
                case DownloadManager.STATUS_RUNNING:
                    break;
                //下载完成
                case DownloadManager.STATUS_SUCCESSFUL:
                    //下载完成安装APK
                    installAPK();
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    UIUtil.toastShort(mContext, "下载失败");
                    break;
            }
        }
        c.close();
    }

    //下载到本地后执行安装
    private void installAPK() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // 6.0以下
            uri = downloadManager.getUriForDownloadedFile(downloadId);
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { // 6.0
            File apkFile = queryDownloadedApk(mContext, downloadId);
            uri = Uri.fromFile(apkFile);
        } else { // Android 7.0 以上
            File file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), mName);
            uri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileProvider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        mContext.startActivity(intent);
        mContext.unregisterReceiver(receiver);
    }

    //通过downLoadId查询下载的apk,解决6.0以后安装的问题
    private static File queryDownloadedApk(Context context, long downloadId) {
        File targetApkFile = null;
        DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

        if (downloadId != -1) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
            Cursor cur = downloader.query(query);
            if (cur != null) {
                if (cur.moveToFirst()) {
                    String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    if (!TextUtils.isEmpty(uriString)) {
                        targetApkFile = new File(Uri.parse(uriString).getPath());
                    }
                }
                cur.close();
            }
        }
        return targetApkFile;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值