下载app

1.下载工具类

/**
 * 下载app
 */
public class DownloadUtils {
    //下载器
    private DownloadManager downloadManager;
    private Context mContext;
    //下载的ID
    private long DOWNLOAD_ID;
    private String name;
    private String apkPath;

    public DownloadUtils(Context context, String url, String name) {
        this.mContext = context;
        this.name = name;
        downloadAPK(url, name);
    }

    //下载apk
    private void downloadAPK(String url, String name) {
        //创建下载任务
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        //移动网络情况下是否允许漫游
        request.setAllowedOverRoaming(false);
        //在通知栏中显示,默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setTitle("VIPKID Parent App");
        request.setDescription(mContext.getString(R.string.down_loading));
        request.setShowRunningNotification(true);//是否显示下载进度提示
        request.setVisibleInDownloadsUi(true);
        //设置下载的路径
        File file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), name);
        request.setDestinationUri(Uri.fromFile(file));
        apkPath = file.getAbsolutePath();
        Log.d("TAGAAA", "downloadAPK: " + apkPath);
        //获取DownloadManager
        if (downloadManager == null)
            downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        //将下载请求加入下载队列,加入下载队列后会给该任务返回一个long型的id,通过该id可以取消任务,重启任务、获取下载的文件等等
        if (downloadManager != null) {
            DOWNLOAD_ID = downloadManager.enqueue(request);
        }
        //注册广播接收者,监听下载状态
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        mContext.registerReceiver(receiver,intentFilter);
    }

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

    //检查下载状态
    public void checkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        //通过下载的id查找
        query.setFilterById(DOWNLOAD_ID);
        Cursor cursor = downloadManager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //下载暂停
                case DownloadManager.STATUS_PAUSED:
                    Log.d("TAGAAA", "checkStatus: 下载暂停");
                    Message paused = new Message();
                    paused.what = 0x101;
                    paused.obj="下载暂停";
                    EventBus.getDefault().post(paused);
                    break;
                //下载延迟
                case DownloadManager.STATUS_PENDING:
                    Log.d("TAGAAA", "checkStatus: 下载延迟");
                    Message pending = new Message();
                    pending.what = 0x101;
                    pending.obj="下载延迟";
                    EventBus.getDefault().post(pending);
                    break;
                //正在下载
                case DownloadManager.STATUS_RUNNING:
                    Log.d("TAGAAA", "checkStatus: 正在下载");
                    Message running = new Message();
                    running.what = 0x101;
                    running.obj=mContext.getString(R.string.down_loading);
                    EventBus.getDefault().post(running);
                    break;
                //下载完成
                case DownloadManager.STATUS_SUCCESSFUL:
                    //下载完成安装APK
                    installAPK();
                    cursor.close();
                    Message message = new Message();
                    message.what = 0x100;
                    message.obj=mContext.getString(R.string.download_complete);
                    EventBus.getDefault().post(message);
                    Log.d("TAGAAA", "checkStatus: 下载完成");
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    cursor.close();
                    Message failed = new Message();
                    failed.what = 0x100;
                    failed.obj="下载失败";
                    EventBus.getDefault().post(failed);
                    mContext.unregisterReceiver(receiver);
                    Log.d("TAGAAA", "checkStatus: 下载失败");
                    break;
                default:
                    Message msg = new Message();
                    msg.what = 0x101;
                    msg.obj="取消下载";
                    EventBus.getDefault().post(msg);
            }
        }
    }

    private void installAPK() {
        setPermission(apkPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //Android 7.0以上要使用FileProvider
        if (Build.VERSION.SDK_INT >= 24) {
            File file = (new File(apkPath));
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(mContext, "com.lxtwsw.weather.fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(Environment.DIRECTORY_DOWNLOADS, name)), "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);
    }

    //修改文件权限
    private void setPermission(String absolutePath) {
        String command = "chmod " + "777" + " " + absolutePath;
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec(command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //判断任务下载状态
    private boolean isDownloading(String url) {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterByStatus(DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_PENDING);
        Cursor cursor = downloadManager.query(query);
        if (cursor.moveToFirst()) {
            if (cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI)).equals(url)) {
                Toast.makeText(mContext, "任务已经存在", Toast.LENGTH_SHORT).show();
                cursor.close();
                return true;
            }
        }
        cursor.close();
        return false;
    }
}

2.在res 下创建xml



    
        
    

3.在清单文件AndroidManifest.xml 下声明

 
        
 
        
            
        
    

4.使用

   downloadUtils = new DownloadUtils(getContext(), url, "intl_parent.apk");

你可能感兴趣的:(下载app)