Commit b0afcea9 authored by fallenstardust's avatar fallenstardust

修正下载

parent 233b3027
......@@ -6,9 +6,6 @@ import static cn.garymb.ygomobile.Constants.ID3;
import static cn.garymb.ygomobile.Constants.URL_GENESYS_LFLIST_DOWNLOAD_LINK;
import static cn.garymb.ygomobile.Constants.URL_HOME_VERSION;
import static cn.garymb.ygomobile.Constants.URL_HOME_VERSION_ALT;
import static cn.garymb.ygomobile.ui.cards.CardDetail.TYPE_DOWNLOAD_CARD_IMAGE_EXCEPTION;
import static cn.garymb.ygomobile.ui.cards.CardDetail.TYPE_DOWNLOAD_CARD_IMAGE_ING;
import static cn.garymb.ygomobile.ui.cards.CardDetail.TYPE_DOWNLOAD_CARD_IMAGE_OK;
import android.annotation.SuppressLint;
import android.content.Intent;
......@@ -58,6 +55,7 @@ import cn.garymb.ygomobile.ui.plus.DialogPlus;
import cn.garymb.ygomobile.ui.settings.SettingFragment;
import cn.garymb.ygomobile.utils.DownloadUtil;
import cn.garymb.ygomobile.utils.FileUtils;
import cn.garymb.ygomobile.utils.LogUtil;
import cn.garymb.ygomobile.utils.OkhttpUtil;
import cn.garymb.ygomobile.utils.ScreenUtil;
import cn.garymb.ygomobile.utils.ServerUtil;
......@@ -71,9 +69,12 @@ import okhttp3.Callback;
import okhttp3.Response;
public abstract class HomeActivity extends BaseActivity implements BottomNavigationBar.OnTabSelectedListener {
private static final String TAG = "HomeActivity";
private static final int TYPE_GET_VERSION_OK = 0;
private static final int TYPE_GET_VERSION_FAILED = 1;
private static final int TYPE_DOWNLOAD_GENESYS_LFLIST_OK = 2;
private static final int TYPE_DOWNLOAD_GENESYS_LFLIST_ING = 3;
private static final int TYPE_DOWNLOAD_GENESYS_LFLIST_FAILED = 4;
public static String Version;
public static String Cache_link;
public static String Cache_pre_release_code;
......@@ -112,6 +113,7 @@ public abstract class HomeActivity extends BaseActivity implements BottomNavigat
//
checkNotch();
checkUpgrade(URL_HOME_VERSION);
downloadGeneSysLflist();
//showNewbieGuide("homePage");
initBottomNavigationBar();
onNewIntent(getIntent());
......@@ -196,10 +198,11 @@ public abstract class HomeActivity extends BaseActivity implements BottomNavigat
super.handleMessage(msg);
switch (msg.what) {
case TYPE_GET_VERSION_OK:
if (msg.obj.toString().contains(ID1) && msg.obj.toString().contains(ID2) && msg.obj.toString().contains(ID3)) {
Version = msg.obj.toString().substring(msg.obj.toString().indexOf(ID1) + ID1.length(), msg.obj.toString().indexOf(";"));//截取版本号
Cache_link = msg.obj.toString().substring(msg.obj.toString().indexOf(ID2) + ID2.length(), msg.obj.toString().indexOf("$"));//截取下载地址
Cache_pre_release_code = msg.obj.toString().substring(msg.obj.toString().indexOf(ID3) + ID3.length() + 1);//截取先行-正式对照文本
String verCodeTxt = msg.obj.toString();
if (verCodeTxt.contains(ID1) && verCodeTxt.contains(ID2) && verCodeTxt.contains(ID3)) {
Version = verCodeTxt.substring(verCodeTxt.indexOf(ID1) + ID1.length(), verCodeTxt.indexOf(";"));//截取版本号
Cache_link = verCodeTxt.substring(verCodeTxt.indexOf(ID2) + ID2.length(), verCodeTxt.indexOf("$"));//截取下载地址
Cache_pre_release_code = verCodeTxt.substring(verCodeTxt.indexOf(ID3) + ID3.length() + 1);//截取先行-正式对照文本
if (!TextUtils.isEmpty(Cache_pre_release_code)) {
arrangeCodeList(Cache_pre_release_code);//转换成两个数组
}
......@@ -223,6 +226,15 @@ public abstract class HomeActivity extends BaseActivity implements BottomNavigat
checkUpgrade(URL_HOME_VERSION_ALT);
}
break;
case TYPE_DOWNLOAD_GENESYS_LFLIST_OK:
LogUtil.d(TAG, "download_genesys_lflist_OK");
break;
case TYPE_DOWNLOAD_GENESYS_LFLIST_ING:
break;
case TYPE_DOWNLOAD_GENESYS_LFLIST_FAILED:
LogUtil.d(TAG, "download_genesys_lflist_FAILED");
break;
}
}
......@@ -405,7 +417,8 @@ public abstract class HomeActivity extends BaseActivity implements BottomNavigat
super.onBackPressed();
} else {
exitLasttime = System.currentTimeMillis();
if (fragment_home.isVisible() || fragment_settings.isVisible()) YGOUtil.showTextToast(R.string.back_tip);
if (fragment_home.isVisible() || fragment_settings.isVisible())
YGOUtil.showTextToast(R.string.back_tip);
}
}
......@@ -456,31 +469,27 @@ public abstract class HomeActivity extends BaseActivity implements BottomNavigat
@Override
public void onDownloadSuccess(File file) {
Message message = new Message();
message.what = TYPE_DOWNLOAD_CARD_IMAGE_OK;
message.arg1 = code;
handler.sendMessage(message);
message.what = TYPE_DOWNLOAD_GENESYS_LFLIST_OK;
message.arg1 = geneSysLflist.hashCode();
handlerHome.sendMessage(message);
}
@Override
public void onDownloading(int progress) {
Message message = new Message();
message.what = TYPE_DOWNLOAD_CARD_IMAGE_ING;
message.what = TYPE_DOWNLOAD_GENESYS_LFLIST_ING;
message.arg1 = progress;
handler.sendMessage(message);
handlerHome.sendMessage(message);
}
@Override
public void onDownloadFailed(Exception e) {
Log.w(IrrlichtBridge.TAG, "download image error:" + e.getMessage());
//下载失败后删除下载的文件
FileUtils.deleteFile(tmp);
// downloadCardImage(code, file);
Log.w(TAG, "download image error:" + e.getMessage());
Message message = new Message();
message.what = TYPE_DOWNLOAD_CARD_IMAGE_EXCEPTION;
message.what = TYPE_DOWNLOAD_GENESYS_LFLIST_FAILED;
message.obj = e.toString();
handler.sendMessage(message);
handlerHome.sendMessage(message);
}
});
}
......
package cn.garymb.ygomobile.utils;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
......@@ -38,15 +39,34 @@ public class DownloadUtil {
okHttpClient = new OkHttpClient();
}
// 添加 ETag 存储工具方法
private String getSavedETag(String url) {
return SharedPreferenceUtil.getString("etag_" + url, "");
}
private void saveETag(String url, String etag) {
SharedPreferenceUtil.putString("etag_" + url, etag);
}
/**
* @param url 下载连接
* @param destFileDir 下载的文件储存目录
* @param destFileName 下载文件名称
* @param listener 下载监听
* 执行文件下载任务,支持断点续传检测与进度回调。
*
* @param url 要下载文件的网络地址
* @param destFileDir 文件保存的目标目录路径
* @param destFileName 保存到本地的文件名
* @param listener 下载过程的监听器,用于接收下载成功、失败和进度更新等事件
*/
public void download(final String url, final String destFileDir, final String destFileName, final OnDownloadListener listener) {
// 构建带 ETag 的请求
Request.Builder builder = new Request.Builder().url(url);
// 添加 If-None-Match 头部(如果有保存的 ETag)
String savedETag = getSavedETag(url);
if (!TextUtils.isEmpty(savedETag)) {
builder.addHeader("If-None-Match", savedETag);
}
// 若启用缓存机制,则检查是否已有相同的下载任务正在进行
if (ENABLE_CACHE) {
synchronized (cache) {
Call old = cache.get(url);
......@@ -56,24 +76,16 @@ public class DownloadUtil {
}
}
}
// 构建HTTP请求对象
Request request = new Request.Builder()
.url(url)
.build();
/* OkHttpClient client = new OkHttpClient();
try {
Response response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}*/
//异步请求
// 异步执行网络请求
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 下载失败监听回调
// 请求失败时通知监听器并清理缓存记录(如已开启)
listener.onDownloadFailed(e);
if (ENABLE_CACHE) {
synchronized (cache) {
......@@ -84,18 +96,32 @@ public class DownloadUtil {
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.e("DownloadUtil", "onResponse:" + response.code() + " eTag:" + response.header("ETag"));
if (response.code() == 304) {
// 内容未修改,无需重新下载
listener.onDownloadSuccess(new File(destFileDir, destFileName));
return;
}
// 响应无效则直接回调失败
if (!response.isSuccessful()) {
listener.onDownloadFailed(new Exception("error:" + response.code()));
return;
}
// 保存新的 ETag
String newETag = response.header("ETag");
if (!TextUtils.isEmpty(newETag)) {
saveETag(url, newETag);
}
// 获取响应头中的文件长度信息
String contentLen = response.header("Content-Length");
final long contentLength = (contentLen == null || contentLen.length() == 0) ? 0 : Long.parseLong(contentLen);
final long contentLength = (contentLen == null || contentLen.isEmpty()) ? 0 : Long.parseLong(contentLen);
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream out = null;
//储存下载文件的目录
// 创建目标文件夹(如果不存在)
File dir = new File(destFileDir);
if (!dir.exists()) {
dir.mkdirs();
......@@ -105,35 +131,37 @@ public class DownloadUtil {
try {
is = response.body().byteStream();
long total = response.body().contentLength();
// 检查实际内容长度是否匹配头部声明长度
if (contentLength > 0 && total != contentLength) {
listener.onDownloadFailed(new Exception("file length[" + total + "] < " + contentLen));
} else {
/* 入参为false时,向file覆盖写入 */
out = new FileOutputStream(file, false);
// 开始写入文件数据,并实时更新下载进度
out = new FileOutputStream(file, false); // 覆盖模式写入
long sum = 0;
while ((len = is.read(buf)) != -1) {
out.write(buf, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / total * 100);
//下载中更新进度条
listener.onDownloading(progress);
listener.onDownloading(progress); // 回调当前下载进度
}
out.flush();
saved = true;
}
} catch (Exception ex) {
listener.onDownloadFailed(ex);
listener.onDownloadFailed(ex); // 出现异常时回调失败接口
} finally {
IOUtils.close(out);
IOUtils.close(is);
IOUtils.close(out); // 安全关闭输出流
IOUtils.close(is); // 安全关闭输入流
}
// 根据最终结果判断是成功还是失败回调
if (saved) {
if (contentLength > 0 && file.length() < contentLength) {
listener.onDownloadFailed(new Exception("file length[" + file.length() + "] < " + contentLen));
} else {
listener.onDownloadSuccess(file);
listener.onDownloadSuccess(file); // 成功完成下载
}
}
// 清理缓存中对应的URL记录(如有启用)
if (ENABLE_CACHE) {
synchronized (cache) {
cache.remove(url);
......
......@@ -210,6 +210,14 @@ public class SharedPreferenceUtil {
getShareType().edit().putInt("server_user_id", userId).apply();
}
public static void putString(String key, String value){
getShareRecord().edit().putString(key, value).commit();
}
public static String getString(String key, String defValue){
return getShareRecord().getString(key, defValue);
}
public static boolean deleteServerToken() {
// Get SharedPreferences instance
SharedPreferences sharedPreferences = getShareRecord();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment