mac
2023-11-29 a289e59fdbbd3678c9904b99b5712410b2698414
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package com.hdl.photovoltaic.widget.apkwgtupload;
 
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
 
import androidx.core.content.FileProvider;
 
import com.hdl.photovoltaic.HDLApp;
import com.hdl.photovoltaic.R;
import com.hdl.photovoltaic.other.HdlAppUpdateLogic;
import com.hdl.photovoltaic.other.HdlThreadLogic;
import com.hdl.photovoltaic.uni.HDLUniMP;
import com.hdl.photovoltaic.uni.HDLUniMPSDKManager;
 
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.Objects;
 
/**
 * Author: zoro
 * Date: 2021/05/25
 * Description: 需要更改FileProvider.getUriForFile
 */
 
public class AppDownloadManager {
    public static final String TAG = "AppDownloadManager";
    private WeakReference<Context> weakReference;
    private DownloadManager mDownloadManager;
    private DownloadChangeObserver mDownLoadChangeObserver;
    private DownloadReceiver mDownloadReceiver;
    private long mReqId;
    private OnUpdateListener mUpdateListener;
 
    private boolean downloading = false;//正在下载
 
    private boolean downSuccess = false;//下载成功
 
    private String downLoadType;
 
 
    public AppDownloadManager(Context context) {
        weakReference = new WeakReference<Context>(context);
        mDownloadManager = (DownloadManager) weakReference.get().getSystemService(Context.DOWNLOAD_SERVICE);
        mDownLoadChangeObserver = new DownloadChangeObserver(new Handler());
        mDownloadReceiver = new DownloadReceiver();
    }
 
    public void setUpdateListener(OnUpdateListener mUpdateListener) {
        this.mUpdateListener = mUpdateListener;
    }
 
    /**
     * @param apkUrl       下载文件路径
     * @param title        下载标题
     * @param desc         下载描述
     * @param fileName     下载文件名
     * @param downLoadType 下载类型 1:wgt   0:apk
     */
    public void downloadApk(String apkUrl, String title, String desc, String fileName, String downLoadType) {
        if (downloading) {
            return;
        }
        downloading = true;
        this.downLoadType = downLoadType;
        // fix bug : 装不了新版本,在下载之前应该删除已有文件
        File apkFile = new File(weakReference.get().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), fileName);
        if (apkFile.exists()) {
            apkFile.delete();
        }
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));
        if ("0".equals(downLoadType)) {
            //设置title
            request.setTitle(title);
            // 设置描述
            request.setDescription(desc);
            // 完成后显示通知栏
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setDestinationInExternalFilesDir(weakReference.get(), Environment.DIRECTORY_DOWNLOADS, HdlAppUpdateLogic.getInstance().getApkFileName());
            request.setMimeType("application/vnd.android.package-archive");
        } else {
            request.setDestinationInExternalFilesDir(weakReference.get(), Environment.DIRECTORY_DOWNLOADS, HDLUniMP.UNI_APP_ID + ".wgt");
            request.setMimeType("application/vnd.android.package-archive");
        }
        mReqId = mDownloadManager.enqueue(request);
    }
 
    /**
     * 取消下载
     */
    public void cancel() {
        mDownloadManager.remove(mReqId);
    }
 
    /**
     * 对应 {@link Activity }
     */
    public void resume() {
        //设置监听Uri.parse("content://downloads/my_downloads")
        weakReference.get().getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true,
                mDownLoadChangeObserver);
        // 注册广播,监听APK是否下载完成
        weakReference.get().registerReceiver(mDownloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
 
    /**
     *
     */
    public void onPause() {
        weakReference.get().getContentResolver().unregisterContentObserver(mDownLoadChangeObserver);
        weakReference.get().unregisterReceiver(mDownloadReceiver);
    }
 
    private void updateView() {
        int[] bytesAndStatus = new int[]{0, 0, 0};
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(mReqId);
        Cursor c = null;
        try {
            c = mDownloadManager.query(query);
            if (c != null && c.moveToFirst()) {
                //已经下载的字节数
                bytesAndStatus[0] = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                //总需下载的字节数
                bytesAndStatus[1] = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                //状态所在的列索引
                bytesAndStatus[2] = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
        if (mUpdateListener != null) {
            mUpdateListener.update(bytesAndStatus[0], bytesAndStatus[1]);
        }
        if (bytesAndStatus[0] == bytesAndStatus[1]) {
            downSuccess = true;
            Log.i(TAG, "下载进度:完成");
        }
        Log.i(TAG, "下载进度:" + bytesAndStatus[0] + "/" + bytesAndStatus[1] + "");
    }
 
    class DownloadChangeObserver extends ContentObserver {
 
        /**
         * Creates a content observer.
         *
         * @param handler The handler to run {@link #onChange} on, or null if none.
         */
        public DownloadChangeObserver(Handler handler) {
            super(handler);
        }
 
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            updateView();
        }
    }
 
    class DownloadReceiver extends BroadcastReceiver {
 
        @Override
        public void onReceive(final Context context, final Intent intent) {
            if (downSuccess) {
                if ("0".equals(downLoadType)) {
                    //下载成功了开始安装
                    downloading = false;
                    boolean haveInstallPermission;
                    // 兼容Android 8.0
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        //先获取是否有安装未知来源应用的权限
                        haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();
                        if (!haveInstallPermission) {//没有权限
                            // 弹窗,并去设置页面授权
                            final AndroidOInstallPermissionListener listener = new AndroidOInstallPermissionListener() {
                                @Override
                                public void permissionSuccess() {
                                    installApk(context, intent);
                                }
 
                                @Override
                                public void permissionFail() {
                                    HdlThreadLogic.toast(HDLApp.getInstance(), HDLApp.getInstance().getResources().getString(R.string.app_update_fail));
                                }
                            };
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    AndroidPermissionActivity.sListener = listener;
                                    Intent intentPermission = new Intent(context, AndroidPermissionActivity.class);
                                    intentPermission.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    context.startActivity(intentPermission);
                                }
                            }, 2000);
 
                        } else {
                            installApk(context, intent);
                        }
                    } else {
                        installApk(context, intent);
                    }
                } else {
                    //释放下载的wgt包
                    HDLUniMPSDKManager.getInstance().hdlReleaseAppResourceToRunPathWithAppid(HDLUniMP.UNI_APP_ID);
                }
            }
        }
    }
 
 
    /**
     * @param context -
     * @param intent  -
     */
    private void installApk(Context context, Intent intent) {
        long completeDownLoadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
        Uri uri;
        Intent intentInstall = new Intent();
        intentInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intentInstall.setAction(Intent.ACTION_VIEW);
 
        if (completeDownLoadId == mReqId) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // 6.0以下
                uri = mDownloadManager.getUriForDownloadedFile(completeDownLoadId);
                if (null == uri) {
                    File apkFile = new File(weakReference.get().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), HdlAppUpdateLogic.getInstance().getApkFileName());
                    if (apkFile.exists()) {
                        uri = Uri.fromFile(apkFile);
                    }
                }
            } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { // 6.0 - 7.0
                File apkFile = queryDownloadedApk(context, completeDownLoadId);
                uri = Uri.fromFile(apkFile);
            } else { // Android 7.0 以上
                uri = FileProvider.getUriForFile(context,
                        "com.hdl.debugtreasure.dc.fileprovider",
                        new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), HdlAppUpdateLogic.getInstance().getApkFileName()));
                intentInstall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
            // 安装应用
            if (null != uri) {
                intentInstall.setDataAndType(uri, "application/vnd.android.package-archive");
                context.startActivity(intentInstall);
            }
        }
    }
 
    //通过downLoadId查询下载的apk,解决6.0以后安装的问题
    public 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(Objects.requireNonNull(Uri.parse(uriString).getPath()));
                    }
                }
                cur.close();
            }
        }
        return targetApkFile;
    }
 
    public interface OnUpdateListener {
        void update(int currentByte, int totalByte);
    }
 
    public interface AndroidOInstallPermissionListener {
        void permissionSuccess();
 
        void permissionFail();
    }
}