代码修改自开源项目 FileDownloader,用来实现android自动更新功能
github下载地址 FileDownloader地址(非本人项目)
public class Downloadutils {
private static final String TAG = "Downloadutils";
private Context mContext;
private static Downloadutils instance = new Downloadutils();
private Downloadutils() {
}
public static Downloadutils getInstance() {
return instance;
}
private BaseDownloadTask fileDownloaderTask;
private void setContext(Context ctx) {
this.mContext = ctx;
}
/**
* 创建下载
*/
public void crateFileDownloader(Context mContext, String updateApkUrl) {
FileDownloader.setup(mContext);
this.mContext = mContext;
FileDownloader.getImpl().create(updateApkUrl)
.setPath(Constant.APP_DIR + File.separator + "update/business.apk")
.setListener(fileDownloader).start();
}
/**
* 下载监听
*/
private FileDownloadListener fileDownloader = new FileDownloadLargeFileListener() {
@Override
protected void pending(BaseDownloadTask task, long soFarBytes, long totalBytes) {
Log.e(TAG, "pending---已经进入下载队列----总大小:" + (totalBytes / 1024 / 1024) + "-----剩余----" + (soFarBytes / 1024 / 1024) + "M");
fileDownloaderTask = task;
}
@Override
protected void progress(BaseDownloadTask task, long soFarBytes, long totalBytes) {
Log.e(TAG, "progress--下载进度回调--总大小:" + (totalBytes / 1024 / 1024) + "-----剩余----" + (soFarBytes / 1024 / 1024) + "M");
fileDownloaderTask = task;
}
@Override
protected void paused(BaseDownloadTask task, long soFarBytes, long totalBytes) {
Log.e(TAG, "paused---暂停下载----总大小:" + (totalBytes / 1024 / 1024) + "-----剩余----" + (soFarBytes / 1024 / 1024) + "M");
fileDownloaderTask = task;
}
@Override
protected void completed(BaseDownloadTask task) {
Log.e(TAG, "completed------下载完成-----apk路径---" + task.getPath());
fileDownloaderTask = task;
// downloadUpdateTvContext.setText("下载完成,保存路径为:" + task.getPath());
installAPK(task.getPath());
}
/**
* 安装APK
*
* @param path
*/
private void installAPK(String path) {
File fileApk = new File(path);
if (!fileApk.exists()) {
ToastUtil.showToast(mContext, "找不到APK路径");
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri apkUri = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
apkUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", fileApk);
//添加这一句表示对目标应用临时授权该Uri所代表的文件
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
apkUri = Uri.fromFile(fileApk);
}
intent.setDataAndType(apkUri,
"application/vnd.android.package-archive");
mContext.startActivity(intent);
}
@Override
protected void error(BaseDownloadTask task, Throwable e) {
Log.e(TAG, "error----下载错误---" + e.getMessage());
fileDownloaderTask = task;
}
@Override
protected void warn(BaseDownloadTask task) {
Log.e(TAG, "warn----在下载队列中(正在等待/正在下载)已经存在相同下载连接与相同存储路径的任务");
ToastUtil.showToast(mContext, "已经存在相同下载连接与相同存储路径的任务请清空重新下载");
}
};
}