应用程序检测到版本不一致时会跳更新页面,让用户点击更新操作,但是有些机器总是出现下载对话框是进度条不动,然后自动关闭进度条的现象。代码中使用简单的下载,代码如下:
public class UpdateService {
private static OkHttpClient okHttpClient;
public static void download(final String fileName,String url, final UpdateCallback callback) {
Request request = new Request.Builder()
.addHeader("Accept-Encoding", "identity")
.url(url).build();
if (okHttpClient == null) {
okHttpClient = new OkHttpClient();
}
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.onFailure();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.body() == null) {
callback.onFailure();
return;
}
File filePath = new File(CommonConstants.DOWNLOAD_PATH);
if (!filePath.exists()) {
filePath.mkdirs();
}
long contentLength = response.body().contentLength();
byte[] buffer = new byte[1024];
File file = new File(filePath.getCanonicalPath(), fileName);
try (InputStream is = response.body().byteStream();
FileOutputStream fos = new FileOutputStream(file)) {
//Log.d("保存路径:" , file.getAbsolutePath());
int length;
long sum = 0;
while ((length = is.read(buffer)) != -1) {
fos.write(buffer, 0, length);
sum += length;
int progress = (int) (sum * 1.0f / contentLength * 100);
callback.onProgress(progress);
}
fos.flush();
callback.onSuccess();
} catch (Exception e) {
callback.onFailure();
}
}
});
}
public interface UpdateCallback {
void onSuccess();
void onProgress(int progress);
void onFailure();
}
}
业务中检测到不一致时执行如下代码:
UpdateService.download(fileName,apkUpdateUrl, new UpdateService.UpdateCallback() {
@Override
public void onSuccess() {
dialog.dismiss();
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
File file = new File(CommonConstants.DOWNLOAD_PATH + fileName);
try {
//下载成功好调用安装
installApk(file);
} catch (Exception e) {
Log.e("获取打开方式错误", e.getMessage());
}
}
@Override
public void onProgress(int progress) {
dialog.setProgress(progress);
}
@Override
public void onFailure() {
dialog.dismiss();
}
});