DownloadUtils【文件下载工具类】

/**
 * 下载的工具类
 * Created by zhuzi on 2019/12/04.
 */

public class DownloadUtils {
    private static final String TAG = "DownloadUtils";
    private DownloadManager mDownloadManager;
    private static Context mContext;
    private long downloadId;
    private File apkFile;
    private Notification mNotification;
    private NotificationManager mNotificationManager;
    public static final String UPDATE = "UPDATE";

    public DownloadUtils(Context context) {
        mContext = context;
    }

    public void download(String url, String name, String file_size) {
        try {
            apkFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), name);
            Log_Ma.e(TAG, "download: 下载的工具类/" + apkFile.toString() + "/" + GetFileSize(apkFile) + "/" + file_size);
            if (apkFile.exists()) {
                boolean upda = (boolean) SPUtils.get(mContext, UPDATE, false);
                if (upda) {
                    installAPK(apkFile);
                } else {
                    ToastUtils.showToast("正在下载中");
                }
            } else {
                downAPK(url, name);
            }
        } catch (Exception e) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            mContext.startActivity(intent);
            Log_Ma.e("更新", e.getMessage());
        }
    }

    private String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);
        //判断sd卡是否存在
        if (sdCardExist) {
            //获取跟目录
            sdDir = Environment.getExternalStorageDirectory();
        }
        return sdDir.toString();
    }

    private void downAPK(String url, String name) {
        final String packageName = "com.anrongtec.zcpt";
        int state = mContext.getPackageManager().getApplicationEnabledSetting(packageName);
        //检测下载管理器是否被禁用
        if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext).setTitle("温馨提示").setMessage
                    ("系统下载管理器被禁止,需手动打开").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    try {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.parse("package:" + packageName));
                        mContext.startActivity(intent);
                    } catch (Exception e) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
                        mContext.startActivity(intent);
                    }
                }
            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        } else {
            //正常下载流程
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setAllowedOverRoaming(false);
            //通知栏显示
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setTitle("新版本安装");
            request.setDescription("正在下载中...");
            request.setVisibleInDownloadsUi(true);
            //设置下载的路径
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, name);
            //获取DownloadManager
            mDownloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
            downloadId = mDownloadManager.enqueue(request);
            mContext.registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkStatus();
        }
    };

    /**
     * 检查下载状态
     */
    private void checkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadId);
        Cursor cursor = mDownloadManager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                case DownloadManager.STATUS_PAUSED:
                    //下载暂停
                    SPUtils.put(mContext, UPDATE, false);
                    break;
                case DownloadManager.STATUS_PENDING:
                    //当下载等待开始时。
                    SPUtils.put(mContext, UPDATE, false);
                    break;
                case DownloadManager.STATUS_RUNNING:
                    //正在下载
                    SPUtils.put(mContext, UPDATE, false);
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    //下载完成
                    SPUtils.put(mContext, UPDATE, true);
                    installAPK(apkFile);
                    break;
                case DownloadManager.STATUS_FAILED:
                    //下载失败
                    ToastUtils.showToast("下载失败");
                    break;
            }
        }
        cursor.close();
    }

    /**
     * 7.0兼容
     */
    public static void installAPK(File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //7.0以上权限问题
            Uri apkUri = FileProvider.getUriForFile(BaseApplication.getContext(), "com.jiada.selection.fileprovider", apkFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        BaseApplication.getContext().startActivity(intent);
    }

    public String GetFileSize(File file) {
        String size = "";
        if (file.isFile()) {
            long fileS = file.length();
            DecimalFormat df = new DecimalFormat("#.00");
            if (fileS < 1024) {
                size = df.format((double) fileS);
            } else if (fileS < 1048576) {
                size = df.format((double) fileS / 1024);
            } else if (fileS < 1073741824) {
                size = df.format((double) fileS / 1048576);
            } else {
                size = df.format((double) fileS / 1073741824);
            }
        } else if (file.exists() && file.isDirectory()) {
            size = "";
        } else {
            size = "";
        }
        Log_Ma.e(TAG, "GetFileSize: 下载的工具类/" + size);
        return size;
    }

    /**
     * 安装apk文件
     *
     * @return
     */
    private PendingIntent getInstallIntent() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //7.0以上权限问题
            Uri apkUri = FileProvider.getUriForFile(mContext, "com.anrongtec.zcpt.fileprovider", apkFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        return pendingIntent;
    }

    private void notifyMsg(String title, String content, int progress) {
        mNotificationManager = (NotificationManager) mContext.getSystemService(Service.NOTIFICATION_SERVICE);
        //为了向下兼容,这里采用了v7包下的NotificationCompat来构造
        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
        builder.setSmallIcon(R.mipmap.app_logo).setContentTitle(title);
        if (progress > 0 && progress < 100) {
            //下载进行中
            builder.setProgress(100, progress, false);
        } else {
            builder.setProgress(0, 0, false);
        }
        builder.setAutoCancel(true);
        builder.setWhen(System.currentTimeMillis());
        builder.setContentText(content);
        if (progress >= 100) {
            //下载完成
            builder.setContentIntent(getInstallIntent());
        }
        mNotification = builder.build();
        mNotificationManager.notify(0, mNotification);
    }

    public static void update(final Bean_Update update, final String token, final Context context, final OnUpdate onUpdate) {
        new XPopup.Builder(context)
                .dismissOnTouchOutside(false)
                .asCustom(new CenterPopupView(context) {
                    @Override
                    protected int getImplLayoutId() {
                        return R.layout.dialog_update;
                    }

                    @Override
                    protected void onCreate() {
                        super.onCreate();
                        final String down_URL = update.getData().getExpFileId();
                        Log_Ma.e(TAG, "onCreate: " + down_URL);
                        ImageView down_Imag = findViewById(R.id.umeng_wifi_indicator1);
                        TextView update_content = findViewById(R.id.update_content);
                        TextView btn_update_id_cancel = findViewById(R.id.btn_update_id_cancel);
                        if (update.getData().force) {
                            btn_update_id_cancel.setVisibility(GONE);
                        } else {
                            btn_update_id_cancel.setVisibility(VISIBLE);
                        }
                        final TextView btn_update_id_ok = findViewById(R.id.btn_update_id_ok);
                        final NumberProgressView numberProgressBar = findViewById(R.id.numberProgressBar);
                        update_content.setText(update.data.getVersionDesc());
                        btn_update_id_ok.setText("立即更新");
                        down_Imag.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Uri uri = Uri.parse(down_URL);
                                Intent viewIntent = new Intent(Intent.ACTION_VIEW, uri);
                                context.startActivity(viewIntent);
                            }
                        });
                        btn_update_id_cancel.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                onUpdate.btnUpdateIdCancel(token);
                            }
                        });
                        btn_update_id_ok.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                numberProgressBar.setVisibility(VISIBLE);
                                btn_update_id_ok.setText("正在下载");
                                OkGo.<File>get(down_URL)
                                        .tag(this)
                                        .execute(new FileCallback(FileUtils.path, FileUtils.StoreName) {
                                            @Override
                                            public void onSuccess(Response<File> response) {
                                                btn_update_id_ok.setText("正在安装");
                                                numberProgressBar.setVisibility(GONE);
                                                installAPK(response.body());
                                                numberProgressBar.setProgress(0);
                                            }

                                            @Override
                                            public void downloadProgress(Progress progress) {
                                                try {
                                                    int dou = (int) ((float) progress.currentSize / Long.parseLong(update.getData().getExpSize()) * 100);
                                                    Log_Ma.e(TAG, "downloadProgress: " + "/" + dou + "/" + progress.currentSize + "/" + update.getData().getExpSize());
                                                    numberProgressBar.setProgress(dou);
                                                } catch (Exception e) {
                                                    numberProgressBar.setVisibility(GONE);
                                                }
                                            }
                                        });
                                onUpdate.btnUpdateIdOk(token);
                            }
                        });
                    }
                }).show();
    }

    public interface OnUpdate {
        void btnUpdateIdCancel(String token);

        void btnUpdateIdOk(String string);
    }
}

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值