lmw
2023-04-03 16ea883d3c03fd8b910f9282aa1bc08378d40d54
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package com.zhaoyang.driver.utils.download;
 
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
 
 
/**
 * Created by ts_xiaoA on 2019/12/2 14:35
 * E-Mail Address:443502578@qq.com
 * Desc:
 */
public class DownloadUtil {
 
    //下载器
    private DownloadManager downloadManager;
    //上下文
    private Context mContext;
    //下载的ID
    private long downloadId;
    //进度变化监听
    private OnProgressListener onProgressChanged;
    //下载进度观察者
    private DownloadObserver downloadObserver;
 
    public DownloadUtil(Context context) {
        this(context, null);
    }
 
    public DownloadUtil(Context mContext, OnProgressListener onChangedCallback) {
        this.mContext = mContext;
        this.onProgressChanged = onChangedCallback;
    }
 
    //下载apk
    public void downloadAPK(String url, String name) {
        //创建下载任务
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        //移动网络情况下是否允许漫游
        request.setAllowedOverRoaming(false);
 
        //在通知栏中显示,默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle(name);
        request.setDescription(name);
        request.setVisibleInDownloadsUi(true);
        //设置下载的路径
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, name);
 
        //获取DownloadManager
        downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        //将下载请求加入下载队列,加入下载队列后会给该任务返回一个long型的id,通过该id可以取消任务,重启任务、获取下载的文件等等
        downloadId = downloadManager.enqueue(request);
        //注册广播接收者,监听下载状态
        mContext.registerReceiver(receiver,
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        //添加监听
        if (onProgressChanged != null) {
            Uri uriForDownloadedFile = Uri.parse("content://downloads/");
            downloadObserver = new DownloadObserver();
            downloadObserver.setOnChangedCallback((selfChange, uri) -> {
                DownloadManager.Query query = new DownloadManager.Query();
                Cursor cursor = downloadManager.query(query);
                cursor.moveToFirst();
                int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                double progress = ((double) bytes_downloaded * 100) / (double) bytes_total;
                Log.i("TAG", "bytes_downloaded: DX"+bytes_downloaded);
                Log.i("TAG", "bytes_total: DX"+bytes_total);
                Log.i("TAG", "progress: DX"+progress);
                cursor.close();
                onProgressChanged.onProgressChanged((int) progress);
            });
            mContext.getContentResolver().registerContentObserver(uriForDownloadedFile, true, downloadObserver);
        }
    }
 
    //广播监听下载的各个状态
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkStatus();
            Log.e("onReceive", "onReceive: >>>>>>>>>>>>下载中");
        }
    };
 
 
    //检查下载状态
    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:
                    if (onProgressChanged != null) {
                        onProgressChanged.onFinish();
                    }
                    //下载完成安装APK
                    if (downloadObserver != null) {
                        mContext.getContentResolver().unregisterContentObserver(downloadObserver);
                    }
                    installAPK();
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
                    if (downloadObserver != null) {
                        mContext.getContentResolver().unregisterContentObserver(downloadObserver);
                    }
                    break;
            }
        }
        c.close();
 
    }
 
 
 
    //下载到本地后执行安装
    private void installAPK() {
        //获取下载文件的Uri
        Uri downloadFileUri = downloadManager.getUriForDownloadedFile(downloadId);
        if (downloadFileUri != null) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            mContext.startActivity(intent);
            mContext.unregisterReceiver(receiver);
        }
    }
 
    //获取当前下载进度
    private int getDownloadPercent(long downloadId) {
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            int downloadBytesIdx = c.getColumnIndexOrThrow(
                    DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
            int totalBytesIdx = c.getColumnIndexOrThrow(
                    DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
            long totalBytes = c.getLong(totalBytesIdx);
            long downloadBytes = c.getLong(downloadBytesIdx);
            return (int) (downloadBytes * 100 / totalBytes);
        }
        return 0;
    }
 
    //进度监听
    public interface OnProgressListener {
        void onProgressChanged(int progress);
 
        void onFinish();
    }
 
    //下载apk
    public void download(String url, String name) {
        //创建下载任务
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        //移动网络情况下是否允许漫游
        request.setAllowedOverRoaming(false);
        //在通知栏中显示,默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle(name);
        request.setDescription(name);
        request.setVisibleInDownloadsUi(true);
        //设置下载的路径
        request.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory().getAbsolutePath(), name);
        //获取DownloadManager
        downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        //将下载请求加入下载队列,加入下载队列后会给该任务返回一个long型的id,通过该id可以取消任务,重启任务、获取下载的文件等等
        downloadId = downloadManager.enqueue(request);
        //注册广播接收者,监听下载状态
//        mContext.registerReceiver(receiver,
//                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
//        //添加监听
//        if (onProgressChanged != null) {
//            Uri uriForDownloadedFile = Uri.parse("content://downloads/");
//            downloadObserver = new DownloadObserver();
//            downloadObserver.setOnChangedCallback((selfChange, uri) -> {
//                DownloadManager.Query query = new DownloadManager.Query();
//                Cursor cursor = downloadManager.query(query);
//                cursor.moveToFirst();
//                int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
//                int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
//                double progress = ((double) bytes_downloaded * 100) / (double) bytes_total;
//                Log.i("TAG", "bytes_downloaded: DX"+bytes_downloaded);
//                Log.i("TAG", "bytes_total: DX"+bytes_total);
//                Log.i("TAG", "progress: DX"+progress);
//                cursor.close();
//                onProgressChanged.onProgressChanged((int) progress);
//            });
//            mContext.getContentResolver().registerContentObserver(uriForDownloadedFile, true, downloadObserver);
//        }
    }
}