From 67fab86f35eb4490e2858017d84242b28bc1e812 Mon Sep 17 00:00:00 2001 From: haomingming Date: Tue, 3 Nov 2026 15:05:57 +0800 Subject: [PATCH] 2 --- .../activity/BindNumberActivity.java | 6 +- .../activity/BookDetailActivity.java | 93 +++-- .../shangyu/gdxzExpert/base/BaseFragment.java | 29 +- .../netease/config/LogoutHelper.java | 4 +- .../VideoDetailPolyvPlayerActivity.java | 20 +- .../shangyu/gdxzExpert/report/CommUtil.java | 111 ++++-- .../gdxzExpert/report/ReportService.java | 330 +++++++++++------- 7 files changed, 352 insertions(+), 241 deletions(-) diff --git a/app/src/main/java/cn/shangyu/gdxzExpert/activity/BindNumberActivity.java b/app/src/main/java/cn/shangyu/gdxzExpert/activity/BindNumberActivity.java index 91a5bd7..4421b09 100644 --- a/app/src/main/java/cn/shangyu/gdxzExpert/activity/BindNumberActivity.java +++ b/app/src/main/java/cn/shangyu/gdxzExpert/activity/BindNumberActivity.java @@ -366,9 +366,9 @@ public class BindNumberActivity extends BaseActivity implements OnCallBackFromNe SharePrefUtil.saveString(ct, "provId", provId);// 省id SharePrefUtil.saveInt(ct, "isStar", isStar);// 是否是肝胆名医 0否 1是 SharePrefUtil.saveInt(ct, "sex", sex);// 性别(0.男 1.女) - SharePrefUtil.saveInt(ct, "state", state);// 审核状态( 1.待审核 - - + SharePrefUtil.saveInt(ct, "state", state);// 审核状态( 1.待审核 + + needreportSimple("login"); addUMToken(PushAgent.getInstance(this).getRegistrationId()); // 2.审核中3.需要补充修改资料 // 4.再次提交审核5.拒绝 6.已通过) diff --git a/app/src/main/java/cn/shangyu/gdxzExpert/activity/BookDetailActivity.java b/app/src/main/java/cn/shangyu/gdxzExpert/activity/BookDetailActivity.java index b7afb60..e30233d 100644 --- a/app/src/main/java/cn/shangyu/gdxzExpert/activity/BookDetailActivity.java +++ b/app/src/main/java/cn/shangyu/gdxzExpert/activity/BookDetailActivity.java @@ -1318,54 +1318,51 @@ public class BookDetailActivity extends BaseActivity implements R.color.top_title)); buildAlert.show(); } - //先判断是否网络下载 - private void isNetWorkDown(){ - String message = null; - if (CommonUtil.isNetworkAvailable(mActivity) == 1){ - message = "当前为Wifi网络,您确定下载该篇文章?"; - }else if (CommonUtil.isNetworkAvailable(mActivity) == 0){ - ToastUtil.showMessage("无网络,请检查网络连接!"); - }else { - message = "当前为移动网络,您确定下载该篇文章?"; - - } - buildAlert = ECAlertDialog.buildAlert(mActivity, message, "取消", "确定", - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - // TODO Auto-generated method stub - buildAlert.dismiss(); - } - }, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - - // TODO Auto-generated method stub - if(mPath!=null&&mPath.contains(Constant.OldfilePath)) - { - new Thread(networkTask3new).start(); - } - else if (hasDownload>0){ - new Thread(networkTask3).start(); - buildAlert.dismiss(); - }else { - if (welfareNum>0){ - useWelfareNum(); - buildAlert.dismiss(); - }else { - isJifenDown(); - } - } - - - } - - - }); - buildAlert.setTitle("提示"); - buildAlert.setTitleColor(mActivity.getResources().getColor( - R.color.top_title)); - buildAlert.show(); + //先判断是否网络下载 + private void isNetWorkDown(){ + int netType = CommonUtil.isNetworkAvailable(mActivity); + if (netType == 0){ + ToastUtil.showMessage("无网络,请检查网络连接!"); + return; + } + if (netType == 1){ + startBookDownload(); + return; + } + String message = "当前为移动网络,您确定下载该篇文章?"; + buildAlert = ECAlertDialog.buildAlert(mActivity, message, "取消", "确定", + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + buildAlert.dismiss(); + } + }, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + buildAlert.dismiss(); + startBookDownload(); + } + }); + buildAlert.setTitle("提示"); + buildAlert.setTitleColor(mActivity.getResources().getColor( + R.color.top_title)); + buildAlert.show(); + } + + private void startBookDownload() { + if(mPath!=null&&mPath.contains(Constant.OldfilePath)) + { + new Thread(networkTask3new).start(); + } + else if (hasDownload>0){ + new Thread(networkTask3).start(); + }else { + if (welfareNum>0){ + useWelfareNum(); + }else { + isJifenDown(); + } + } } //使用福利操作 private void useWelfareNum() { diff --git a/app/src/main/java/cn/shangyu/gdxzExpert/base/BaseFragment.java b/app/src/main/java/cn/shangyu/gdxzExpert/base/BaseFragment.java index b770862..173d0aa 100644 --- a/app/src/main/java/cn/shangyu/gdxzExpert/base/BaseFragment.java +++ b/app/src/main/java/cn/shangyu/gdxzExpert/base/BaseFragment.java @@ -1,7 +1,8 @@ package cn.shangyu.gdxzExpert.base; -import android.app.Activity; -import android.app.ProgressDialog; +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; @@ -606,16 +607,20 @@ public abstract class BaseFragment extends Fragment { reportBeans.add(rbens); startReport(reportBeans); } - public void startReport(List list) - { - Intent intent = new Intent(getActivity(), ReportService.class); - if(list!=null) - { - intent.putExtra("report_list", (Serializable) list); - - } - intent.putExtra("report_token", Constant.Repotr_token); - getActivity().startService(intent); + public void startReport(List list) + { + Context targetContext = getActivity() != null ? getActivity() : UIUtils.getContext(); + if (targetContext == null) { + return; + } + Intent intent = new Intent(targetContext, ReportService.class); + if(list!=null) + { + intent.putExtra("report_list", (Serializable) list); + + } + intent.putExtra("report_token", Constant.Repotr_token); + targetContext.startService(intent); } public void needreportSimple(String name) { diff --git a/app/src/main/java/cn/shangyu/gdxzExpert/netease/config/LogoutHelper.java b/app/src/main/java/cn/shangyu/gdxzExpert/netease/config/LogoutHelper.java index 1e052a8..718c14f 100644 --- a/app/src/main/java/cn/shangyu/gdxzExpert/netease/config/LogoutHelper.java +++ b/app/src/main/java/cn/shangyu/gdxzExpert/netease/config/LogoutHelper.java @@ -40,7 +40,9 @@ public class LogoutHelper { SharePrefUtil.clear(UIUtils.getContext(), "isLogin"); startReport(null); -// Constant.Repotr_token=""; + Constant.Repotr_token = ""; + Constant.Report_userId = ""; + Constant.Repotr_app_key = ""; // SharePrefUtil.clear(UIUtils.getContext(), SharePrefUtil.getString(UIUtils.getContext(), Constant.SP_IS_FIRST_NAME, // Constant.mobile, "") + "my_provinceId"); // SharePrefUtil.clear(UIUtils.getContext(), SharePrefUtil.getString(UIUtils.getContext(), Constant.SP_IS_FIRST_NAME, diff --git a/app/src/main/java/cn/shangyu/gdxzExpert/polyvplayer/VideoDetailPolyvPlayerActivity.java b/app/src/main/java/cn/shangyu/gdxzExpert/polyvplayer/VideoDetailPolyvPlayerActivity.java index 7c2ba1a..5804aa9 100644 --- a/app/src/main/java/cn/shangyu/gdxzExpert/polyvplayer/VideoDetailPolyvPlayerActivity.java +++ b/app/src/main/java/cn/shangyu/gdxzExpert/polyvplayer/VideoDetailPolyvPlayerActivity.java @@ -1808,23 +1808,9 @@ public class VideoDetailPolyvPlayerActivity extends FragmentActivity implements case R.id.tv_exchange: if (!UIUtils.checkLoginAndJump(VideoDetailPolyvPlayerActivity.this)) return; String netWorkTypeName = getNetWorkTypeName(VideoDetailPolyvPlayerActivity.this); - if ("NETWORK_WIFI".equals(netWorkTypeName)){ - if ("点击下载".equals(tv_exchange.getText().toString())){ - buildAlert = ECAlertDialog.buildAlert(VideoDetailPolyvPlayerActivity.this,"当前为Wifi网络,确定下载?", "取消", "确定", - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - // TODO Auto-generated method stub - buildAlert.dismiss(); - } - }, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - videoDown(); - } - }); - buildAlert.setTitle("温馨提示"); - buildAlert.show(); + if ("NETWORK_WIFI".equals(netWorkTypeName)){ + if ("点击下载".equals(tv_exchange.getText().toString())){ + videoDown(); }else if("视频缓存中".equals(tv_exchange.getText().toString())){ Intent intent1 = new Intent(VideoDetailPolyvPlayerActivity.this, PolyvDownloadActivity.class); intent1.putExtra("isStarting",true); diff --git a/app/src/main/java/cn/shangyu/gdxzExpert/report/CommUtil.java b/app/src/main/java/cn/shangyu/gdxzExpert/report/CommUtil.java index 60eaee8..fd37b27 100644 --- a/app/src/main/java/cn/shangyu/gdxzExpert/report/CommUtil.java +++ b/app/src/main/java/cn/shangyu/gdxzExpert/report/CommUtil.java @@ -21,7 +21,9 @@ import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import cn.shangyu.gdxzExpert.BuildConfig; +import cn.shangyu.gdxzExpert.BuildConfig; +import cn.shangyu.gdxzExpert.utils.Constant; +import cn.shangyu.gdxzExpert.utils.StringUtil; public class CommUtil { // public static String userId=""; @@ -79,10 +81,22 @@ public class CommUtil { Log.d("saveListToFile",file.getAbsolutePath()); try { FileOutputStream fos=new FileOutputStream(file,true);//设置为true,继续原文件写入 - try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos))) { - for (reportBean item : list) { - writer.write(gson.toJson(item)); - writer.newLine(); // 每个布尔值后写入一个新行 + try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"))) { + for (reportBean item : list) { + if (item == null) { + continue; + } + if (StringUtil.isEmpty(item.getUser_id()) && !StringUtil.isEmpty(Constant.Report_userId)) { + item.setUser_id(Constant.Report_userId); + } + if (StringUtil.isEmpty(item.getApp_key()) && !StringUtil.isEmpty(Constant.Repotr_app_key)) { + item.setApp_key(Constant.Repotr_app_key); + } + if (StringUtil.isEmpty(item.getNetwork_carrier()) && !StringUtil.isEmpty(CommUtil.getCarrierName)) { + item.setNetwork_carrier(CommUtil.getCarrierName); + } + writer.write(gson.toJson(item)); + writer.newLine(); // 每个布尔值后写入一个新行 } writer.close(); fos.close(); @@ -104,35 +118,64 @@ public class CommUtil { basePath += "/"; } - try (FileOutputStream fos = new FileOutputStream(zipFile); - ZipOutputStream zos = new ZipOutputStream(fos)) { - - File[] files = folderToZip.listFiles(); - if (files != null) { - for (File file : files) { - String filePath = file.getPath().replace("\\", "/"); - String entryName = filePath.substring(basePath.length()); - if (file.isDirectory()) { - // 添加文件夹条目 - zos.putNextEntry(new ZipEntry(entryName + "/")); - zos.closeEntry(); - // 递归地压缩子文件夹 - zipFolderCorrected(file, zipFile, basePath); - } else { - // 添加文件条目并写入文件内容 - zos.putNextEntry(new ZipEntry(entryName)); - try (FileInputStream fis = new FileInputStream(file)) { - byte[] buffer = new byte[1024]; - int length; - while ((length = fis.read(buffer)) >= 0) { - zos.write(buffer, 0, length); - } - } - zos.closeEntry(); - } - } - } - } + try (FileOutputStream fos = new FileOutputStream(zipFile); + ZipOutputStream zos = new ZipOutputStream(fos)) { + zipFolderInternal(folderToZip, zos, basePath); + } + } + + private static void zipFolderInternal(File currentFolder, ZipOutputStream zos, String basePath) throws IOException { + File[] files = currentFolder.listFiles(); + if (files != null) { + for (File file : files) { + String filePath = file.getPath().replace("\\", "/"); + String entryName = filePath.substring(basePath.length()); + if (file.isDirectory()) { + zos.putNextEntry(new ZipEntry(entryName + "/")); + zos.closeEntry(); + zipFolderInternal(file, zos, basePath); + } else { + zos.putNextEntry(new ZipEntry(entryName)); + try (FileInputStream fis = new FileInputStream(file)) { + byte[] buffer = new byte[1024]; + int length; + while ((length = fis.read(buffer)) >= 0) { + zos.write(buffer, 0, length); + } + } + zos.closeEntry(); + } + } + } + } + + /** + * 将待打包的 upload.txt 合并移动到 uploading/upload.txt 快照目录中, + * 避免上传期间产生的新埋点丢失或上传成功后被误删。 + */ + public static void mergeFileToUploading(File srcFile, File destFile) throws IOException { + if (srcFile == null || !srcFile.exists() || srcFile.length() == 0) { + return; + } + File parentDir = destFile.getParentFile(); + if (parentDir != null && !parentDir.exists()) { + parentDir.mkdirs(); + } + if (!destFile.exists()) { + if (srcFile.renameTo(destFile)) { + return; + } + } + try (FileInputStream fis = new FileInputStream(srcFile); + FileOutputStream fos = new FileOutputStream(destFile, true)) { + byte[] buffer = new byte[4096]; + int length; + while ((length = fis.read(buffer)) >= 0) { + fos.write(buffer, 0, length); + } + fos.flush(); + } + srcFile.delete(); } public static void deleteFile( String ReportFileZip,String name,String folderPath) { diff --git a/app/src/main/java/cn/shangyu/gdxzExpert/report/ReportService.java b/app/src/main/java/cn/shangyu/gdxzExpert/report/ReportService.java index 90d2937..8bd2359 100644 --- a/app/src/main/java/cn/shangyu/gdxzExpert/report/ReportService.java +++ b/app/src/main/java/cn/shangyu/gdxzExpert/report/ReportService.java @@ -24,9 +24,12 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import cn.shangyu.gdxzExpert.bean.TimestampBean; import cn.shangyu.gdxzExpert.http.HttpHelper; @@ -47,17 +50,24 @@ public class ReportService extends Service { public ReportService() { } + private static final ExecutorService REPORT_EXECUTOR = Executors.newSingleThreadExecutor(); + private static final List PENDING_BEFORE_TOKEN_LIST = new ArrayList<>(); + public String ReportFile; + public String ReportUploadingDir; public String ReportFileZip; - public String report_token=""; - List list; + public volatile String report_token = ""; + private volatile boolean isFetchingToken = false; + // public String FileUrl="https://dev-event.igandan.com/v1/eventLog/upload";//测试环境 // public String FileUrl="https://event.igandan.com/v1/eventLog/upload";//正式环境 @Override public void onCreate() { super.onCreate(); - ReportFile=getBaseContext().getExternalFilesDir("").getAbsolutePath()+"/gdxz/report/zip"; - ReportFileZip=getBaseContext().getExternalFilesDir("").getAbsolutePath()+"/gdxz/report/"; + String basePath = getBaseContext().getExternalFilesDir("").getAbsolutePath(); + ReportFile = basePath + "/gdxz/report/zip"; + ReportUploadingDir = basePath + "/gdxz/report/uploading"; + ReportFileZip = basePath + "/gdxz/report/"; // if("true".equals(CommUtil.isFirstRun)) // { // CommUtil.isFirstRun="false"; @@ -102,160 +112,212 @@ public class ReportService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { - report_token=intent.getStringExtra("report_token"); - if(report_token==""||report_token==null) - { + if (intent == null) { return START_NOT_STICKY; } - else if(intent.getSerializableExtra("report_list")==null) - { - if(checkReport()) - { - new Thread(new Runnable() { - @Override - public void run() { - zipFile(); - } - }).start(); - } - return START_NOT_STICKY; + final String incomingToken = intent.getStringExtra("report_token"); + if (!StringUtil.isEmpty(incomingToken)) { + report_token = incomingToken; + } else if (!StringUtil.isEmpty(Constant.Repotr_token)) { + report_token = Constant.Repotr_token; } - list = (List) intent.getSerializableExtra("report_list"); - CommUtil.totalreport+= list.size(); + final List incomingList = (List) intent.getSerializableExtra("report_list"); - // 在新线程或异步任务中执行文件上传 - new Thread(new Runnable() { + REPORT_EXECUTOR.execute(new Runnable() { @Override public void run() { - writeReport(); -// uploadFile(filePath); -// // 上传完成后,可以停止服务或发送广播通知其他组件 -// stopSelf(); // 或者使用广播通知 + handleReportCommand(incomingList); } - }).start(); + }); return START_NOT_STICKY; } - public void writeReport() - { -// if(2>1) -// { -// CommUtil.deleteFile(ReportFileZip,"output.zip",ReportFile); -// return; -// } - if( "true".equals(CommUtil.isReoprtingNow)) - { - return; - } - Log.d("okhttp","CommUtil.totalreport "+ CommUtil.totalreport); - if(CommUtil.totalreport>99&&checkReport()) - { + private String getActiveUuid() { + String uuid = SharePrefUtil.getString(UIUtils.getContext(), Constant.uuid, ""); + if (StringUtil.isEmpty(uuid)) { + uuid = LogoutHelper.addUMTokenuuid; + } + return uuid; + } + + private void handleReportCommand(List incomingList) { + if (!StringUtil.isEmpty(Constant.Repotr_token)) { + report_token = Constant.Repotr_token; + } + + // Token 尚未就绪时:若用户已登录,先暂存到内存队列并自动请求 Token,避免刚登录/冷启动的埋点丢失 + if (StringUtil.isEmpty(report_token)) { + if (incomingList != null && !incomingList.isEmpty() && !StringUtil.isEmpty(getActiveUuid())) { + PENDING_BEFORE_TOKEN_LIST.addAll(incomingList); + initReport(false); + } + return; + } + + // Token 已就绪:先把之前暂存的埋点补齐 user_id/app_key 并落盘 + flushPendingBeforeTokenList(); + + if (incomingList == null) { + if (checkReport()) { + zipFile(); + } + return; + } + + if (!incomingList.isEmpty()) { + writeReport(incomingList); + } + } + + private void flushPendingBeforeTokenList() { + if (!PENDING_BEFORE_TOKEN_LIST.isEmpty()) { + CommUtil.saveListToFile(PENDING_BEFORE_TOKEN_LIST, ReportFile, "upload", ReportFileZip); + CommUtil.totalreport += PENDING_BEFORE_TOKEN_LIST.size(); + PENDING_BEFORE_TOKEN_LIST.clear(); + } + } + + public void writeReport(List currentList) { + // 始终先把当前批次写入本地 upload.txt,避免第 100 条埋点丢失或上传期间新埋点丢失 + CommUtil.saveListToFile(currentList, ReportFile, "upload", ReportFileZip); + CommUtil.totalreport += currentList.size(); + Log.d("okhttp", "CommUtil.totalreport " + CommUtil.totalreport); + + if (CommUtil.totalreport >= 100 && checkReport()) { zipFile(); } - else{ - CommUtil.saveListToFile(list,ReportFile,"upload",ReportFileZip); - } - } - public void zipFile() - { - CommUtil.isReoprtingNow="true"; - File folderToZip = new File(ReportFile); - File zipFile = new File(ReportFileZip,"outputandroid.zip"); + + public void zipFile() { + if ("true".equals(CommUtil.isReoprtingNow)) { + return; + } try { + File pendingFile = new File(ReportFile, "upload.txt"); + File uploadingFile = new File(ReportUploadingDir, "upload.txt"); + // 将待上传的 upload.txt 合并迁移至隔离目录 uploading/upload.txt,避免上传期间新写入的数据被混入或误删 + CommUtil.mergeFileToUploading(pendingFile, uploadingFile); + CommUtil.totalreport = 0; + + if (!uploadingFile.exists() || uploadingFile.length() == 0) { + return; + } + + CommUtil.isReoprtingNow = "true"; + File folderToZip = new File(ReportUploadingDir); + File zipFile = new File(ReportFileZip, "outputandroid.zip"); CommUtil.zipFolderCorrected(folderToZip, zipFile, folderToZip.getPath()); uploadFile(); - } catch (IOException e) { + } catch (Exception e) { + CommUtil.isReoprtingNow = "false"; e.printStackTrace(); } } - public void uploadFile() { - Map headers=new HashMap<>(); - headers.put("Content-Type","multipart/form-data"); - headers.put("Tag-Access",report_token); -// Log.d("okhttp","report_token"+report_token); - File zipFile = new File(ReportFileZip,"outputandroid.zip"); + public void uploadFile() { + Map headers = new HashMap<>(); + headers.put("Content-Type", "multipart/form-data"); + headers.put("Tag-Access", report_token); + File zipFile = new File(ReportFileZip, "outputandroid.zip"); + if (!zipFile.exists() || zipFile.length() == 0) { + CommUtil.isReoprtingNow = "false"; + return; + } OkHttpUtils .post() .url(Url.FileUrl) .headers(headers) - .addFile("file", "outputandroid.zip", zipFile)// - -// .file(zipFile) - + .addFile("file", "outputandroid.zip", zipFile) .build() .execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { - Log.d("okhttp",e+"e"); - CommUtil.isReoprtingNow="false"; - CommUtil.totalreport=0; + Log.d("okhttp", e + "e"); + CommUtil.isReoprtingNow = "false"; } @Override public void onResponse(String response, int id) { - Log.d("okhttp",response+"responseoutput"); - CommUtil.isReoprtingNow="false"; - - JSONObject jsonObject= null; + Log.d("okhttp", response + "responseoutput"); try { - jsonObject = new JSONObject(response); - if("30007".equals(jsonObject.optString("code"))) - { - initReport(); - } - else if("200".equals(jsonObject.optString("code"))) - { - CommUtil.deleteFile(ReportFileZip,"outputandroid.zip",ReportFile); -// CommUtil.isReoprtingNow="false"; - CommUtil.totalreport=0; - } - else - { -// CommUtil.isReoprtingNow="false"; - CommUtil.totalreport=0; + JSONObject jsonObject = new JSONObject(response); + String code = jsonObject.optString("code"); + if ("30007".equals(code)) { + initReport(true); + } else if ("200".equals(code)) { + REPORT_EXECUTOR.execute(new Runnable() { + @Override + public void run() { + // 仅清理已上传成功的快照目录 ReportUploadingDir,保留上传期间新写入 ReportFile 的数据 + CommUtil.deleteFile(ReportFileZip, "outputandroid.zip", ReportUploadingDir); + CommUtil.isReoprtingNow = "false"; + if (CommUtil.totalreport >= 100 && checkReport()) { + zipFile(); + } + } + }); + } else { + CommUtil.isReoprtingNow = "false"; } } catch (JSONException e) { + CommUtil.isReoprtingNow = "false"; e.printStackTrace(); } - - - } }); } - public Boolean checkReport() - { - File folderToZip = new File(ReportFile); - if(folderToZip.exists()) - { - return true; + + public Boolean checkReport() { + File pendingFile = new File(ReportFile, "upload.txt"); + File uploadingFile = new File(ReportUploadingDir, "upload.txt"); + return (pendingFile.exists() && pendingFile.length() > 0) + || (uploadingFile.exists() && uploadingFile.length() > 0); + } + + public void initReport() { + initReport(true); + } + + public void initReport(final boolean retryUploadAfterToken) { + if (isFetchingToken) { + return; } - return false; + String uuid = getActiveUuid(); + if (StringUtil.isEmpty(uuid)) { + if (retryUploadAfterToken) { + CommUtil.isReoprtingNow = "false"; + } + return; + } + isFetchingToken = true; + Map map = new HashMap<>(); + sendJsonPostParamtoNetSignMD5(Url.getTagToken, map, retryUploadAfterToken); } - public void initReport() - { - Map map = new HashMap<>(); - sendJsonPostParamtoNetSignMD5(Url.getTagToken,map); + public void sendJsonPostParamtoNetSignMD5(final String postUrl, final Map param, final boolean retryUploadAfterToken) { - - } - public void sendJsonPostParamtoNetSignMD5(final String postUrl, final Map param) { - - HttpHelper.loadData(HttpRequest.HttpMethod.GET, Url.getTimestamp,null, new RequestCallBack() { + HttpHelper.loadData(HttpRequest.HttpMethod.GET, Url.getTimestamp, null, new RequestCallBack() { @Override public void onSuccess(ResponseInfo info) { - String uuid = SharePrefUtil.getString(UIUtils.getContext(), Constant.uuid, ""); - if(StringUtil.isEmpty(uuid)) - { - uuid= LogoutHelper.addUMTokenuuid; + String uuid = getActiveUuid(); + if (StringUtil.isEmpty(uuid)) { + isFetchingToken = false; + if (retryUploadAfterToken) { + CommUtil.isReoprtingNow = "false"; + } + return; } param.put("user_uuid", uuid); TimestampBean bean = GsonTools.fromGsonToBean(info.result, TimestampBean.class); + if (bean == null) { + isFetchingToken = false; + if (retryUploadAfterToken) { + CommUtil.isReoprtingNow = "false"; + } + return; + } param.put("timestamp", bean.getTimestamp()); param.put("client_type", "A"); param.put("version", UpdateVersionUtils.getVersionName()); @@ -265,45 +327,58 @@ public class ReportService extends Service { Gson gson = new Gson(); String params = gson.toJson(param); byte[] data; + boolean tokenRefreshed = false; try { String sign = SignUtil.getSign(param); - LogUtil.i("params = "+params.toString()); + LogUtil.i("params = " + params.toString()); data = params.getBytes(encoding); URL url = new URL(postUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); - conn.setRequestProperty("Content-Type","application/json"); - conn.setRequestProperty("sign",sign); - conn.setRequestProperty("Content-Length",String.valueOf(data.length)); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setRequestProperty("sign", sign); + conn.setRequestProperty("Content-Length", String.valueOf(data.length)); conn.setConnectTimeout(5 * 1000); OutputStream outStream = conn.getOutputStream(); outStream.write(data); outStream.flush(); outStream.close(); - int ssss=conn.getResponseCode() ; + int ssss = conn.getResponseCode(); if (ssss == 200) { InputStream inStream = conn.getInputStream(); String result = new String(StreamTool.readInputStream(inStream), "UTF-8"); - String string = new String(result); LogUtil.i("result = " + result); - JSONObject jsonObject111 = new JSONObject(string); - if ("200".equals(jsonObject111.optString("code"))&&!jsonObject111.isNull("data")) { - Constant.Report_userId= jsonObject111.optJSONObject("data").optString("userId"); - Constant.Repotr_token=jsonObject111.optJSONObject("data").optString("token"); - Constant.Repotr_app_key=jsonObject111.optJSONObject("data").optString("appKey"); - report_token=Constant.Repotr_token; -// Log.d("okhttp","report_token666"+report_token); - uploadFile(); + JSONObject jsonObject111 = new JSONObject(result); + if ("200".equals(jsonObject111.optString("code")) && !jsonObject111.isNull("data")) { + Constant.Report_userId = jsonObject111.optJSONObject("data").optString("userId"); + Constant.Repotr_token = jsonObject111.optJSONObject("data").optString("token"); + Constant.Repotr_app_key = jsonObject111.optJSONObject("data").optString("appKey"); + report_token = Constant.Repotr_token; + tokenRefreshed = true; } } } catch (Exception e) { - LogUtil.e("提交失败,请重试 = "+e.getMessage()); - - // TODO Auto-generated catch block + LogUtil.e("提交失败,请重试 = " + e.getMessage()); e.printStackTrace(); } finally { - + isFetchingToken = false; + if (tokenRefreshed) { + if (retryUploadAfterToken) { + uploadFile(); + } + REPORT_EXECUTOR.execute(new Runnable() { + @Override + public void run() { + flushPendingBeforeTokenList(); + if (!retryUploadAfterToken && CommUtil.totalreport >= 100 && checkReport()) { + zipFile(); + } + } + }); + } else if (retryUploadAfterToken) { + CommUtil.isReoprtingNow = "false"; + } } } }.start(); @@ -312,7 +387,10 @@ public class ReportService extends Service { @Override public void onFailure(HttpException arg0, String arg1) { - + isFetchingToken = false; + if (retryUploadAfterToken) { + CommUtil.isReoprtingNow = "false"; + } } });