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 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); 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); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE); // 注册广播,监听APK是否下载完成 weakReference.get().registerReceiver(mDownloadReceiver, intentFilter); } /** * */ 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, "下载进度:完成"); } long value = bytesAndStatus[0]* 100L / bytesAndStatus[1]; Log.i(TAG, "下载进度:" + value + ""); } 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.photovoltaic.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(); } }