Browse Source

断点续传备份

raomeng 8 years ago
parent
commit
f43d1ebcef

+ 150 - 22
WeiChat/src/main/java/com/xzjmyk/pm/activity/ui/erp/activity/datainquiry/activity/PDFDownloadActivity.java

@@ -5,6 +5,7 @@ import android.graphics.Canvas;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
+import android.text.TextUtils;
 import android.util.Log;
 import android.view.View;
 import android.widget.LinearLayout;
@@ -12,7 +13,10 @@ import android.widget.ProgressBar;
 import android.widget.RelativeLayout;
 import android.widget.TextView;
 
+import com.core.net.ProgressDownloader;
+import com.core.net.ProgressResponseBody;
 import com.core.utils.CommonUtil;
+import com.core.utils.ToastUtil;
 import com.github.barteksc.pdfviewer.PDFView;
 import com.github.barteksc.pdfviewer.listener.OnDrawListener;
 import com.github.barteksc.pdfviewer.listener.OnErrorListener;
@@ -23,22 +27,39 @@ import com.github.barteksc.pdfviewer.listener.OnRenderListener;
 import com.xzjmyk.pm.activity.R;
 import com.xzjmyk.pm.activity.ui.base.BaseActivity;
 import com.xzjmyk.pm.activity.ui.erp.activity.datainquiry.Constants;
-import com.xzjmyk.pm.activity.ui.erp.activity.datainquiry.PDFUtils;
+import com.xzjmyk.pm.activity.ui.erp.net.ViewUtil;
+
+import org.json.JSONException;
+import org.json.JSONObject;
 
 import java.io.File;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import static com.xzjmyk.pm.activity.ui.erp.activity.datainquiry.Constants.CONSTANT.PDF_FILE_NAME;
+import static com.xzjmyk.pm.activity.ui.erp.activity.datainquiry.Constants.CONSTANT.PDF_FILE_PATH;
 
 /**
  * Created by RaoMeng on 2017/8/17.
  * 报表统计PDF文件下载并展示页面
  */
-public class PDFDownloadActivity extends BaseActivity implements View.OnClickListener, OnDrawListener, OnLoadCompleteListener, OnPageChangeListener, OnPageScrollListener, OnErrorListener, OnRenderListener {
+public class PDFDownloadActivity extends BaseActivity implements View.OnClickListener, OnDrawListener, OnLoadCompleteListener, OnPageChangeListener, OnPageScrollListener, OnErrorListener, OnRenderListener, ProgressResponseBody.ProgressListener {
+    private final int OBATIN_PDF_PATH = 100;
+
     private PDFView mPDFView;
-    private TextView mStateTextView, mRemainTextView, mReloadTextView, mExitTextView;
+    private TextView mStateTextView, mRemainTextView, mReloadTextView, mExitTextView, mPauseTextView;
     private ProgressBar mDownloadProgressBar;
     private RelativeLayout mDownloadRelativeLayout;
     private LinearLayout mErrorLinearLayout;
     private String downloadUrl = "", mReportName = "";
     private String mCondition, mTitle;
+    private ProgressDownloader mDownloader;
+    private long breakPoints;
+    private File file;
+    private long contentLength;
+    private long totalBytes;
 
     private Handler mHandler = new Handler() {
         @Override
@@ -47,17 +68,18 @@ public class PDFDownloadActivity extends BaseActivity implements View.OnClickLis
                 case Constants.CONSTANT.DOWNLOAD_PROGRESS:
                     try {
                         int progress = (int) msg.obj;
-                        Log.d("progress", progress + "");
+                        Log.d("progress", progress + ":" + contentLength);
                         mStateTextView.setText(R.string.str_loading);
                         mDownloadProgressBar.setProgress(progress);
-                        mRemainTextView.setText((100 - progress) + "");
+                        mRemainTextView.setText((100 - (((progress * 1024 * 100) / contentLength))) + "");
                     } catch (Exception e) {
 
                     }
                     break;
                 case Constants.CONSTANT.DOWNLOAD_SUCCESS:
+                    mPauseTextView.setVisibility(View.GONE);
                     mStateTextView.setText("报表文件下载成功!\n正在加载....");
-                    mDownloadProgressBar.setProgress(100);
+//                    mDownloadProgressBar.setProgress(100);
                     mRemainTextView.setText("0");
                     /*mDownloadRelativeLayout.postDelayed(new Runnable() {
                         @Override
@@ -65,15 +87,21 @@ public class PDFDownloadActivity extends BaseActivity implements View.OnClickLis
                             mDownloadRelativeLayout.setVisibility(View.GONE);
                         }
                     }, 1000);*/
-                    displayFromFile(new File(Constants.CONSTANT.PDF_FILE_PATH, Constants.CONSTANT.PDF_FILE_NAME));
+                    displayFromFile(new File(PDF_FILE_PATH, PDF_FILE_NAME));
                     break;
                 case Constants.CONSTANT.PDF_OVERLOAD:
+                    mPauseTextView.setVisibility(View.GONE);
                     mErrorLinearLayout.setVisibility(View.VISIBLE);
                     mStateTextView.setText("数据量过载,报表文件获取失败!");
                     mDownloadProgressBar.setProgress(0);
                     mRemainTextView.setText(100 + "");
                     break;
+                case OBATIN_PDF_PATH:
+                    String result = msg.getData().getString("result");
+                    analysisPdfPath(result);
+                    break;
                 case Constants.CONSTANT.DOWNLOAD_FAILED:
+                    mPauseTextView.setVisibility(View.GONE);
                     mErrorLinearLayout.setVisibility(View.VISIBLE);
                     String info = "";
                     if (msg.obj != null) {
@@ -83,10 +111,67 @@ public class PDFDownloadActivity extends BaseActivity implements View.OnClickLis
                     mDownloadProgressBar.setProgress(0);
                     mRemainTextView.setText(100 + "");
                     break;
+                case com.core.app.Constants.APP_SOCKETIMEOUTEXCEPTION:
+                    result = msg.getData().getString("response");
+                    analysisPdfPath(result);
+                    break;
             }
         }
     };
 
+    private void analysisPdfPath(String result) {
+        if (result != null) {
+            try {
+                JSONObject responseObject = new JSONObject(result);
+                if (!responseObject.isNull("success") && !responseObject.optBoolean("success")) {
+                    Message message = Message.obtain();
+                    message.what = Constants.CONSTANT.DOWNLOAD_FAILED;
+                    message.obj = responseObject.optString("message");
+                    mHandler.sendMessage(message);
+                } else {
+                    boolean overload = responseObject.optBoolean("overload");
+                    int pageSize = -1;
+                    if (!responseObject.isNull("pageSize")) {
+                        pageSize = responseObject.optInt("pageSize");
+                    }
+                    if (overload) {
+                        mHandler.sendEmptyMessage(Constants.CONSTANT.PDF_OVERLOAD);
+                    } else if (pageSize == 0) {
+                        Message message = Message.obtain();
+                        message.what = Constants.CONSTANT.DOWNLOAD_FAILED;
+                        message.obj = "报表文件内容为空";
+                        mHandler.sendMessage(message);
+                    } else {
+                        downloadUrl = responseObject.optString("path");
+                        if (!TextUtils.isEmpty(downloadUrl)) {
+                            downloadUrl = "http://print.ubtob.com/report/" + downloadUrl;
+                            mPauseTextView.setVisibility(View.VISIBLE);
+                            breakPoints = 0L;
+                            File directory = new File(PDF_FILE_PATH);
+                            if (!directory.exists() && !directory.isDirectory()) {
+                                boolean mkdirs = directory.mkdirs();
+
+                            } else {
+                                CommonUtil.delAllFile(PDF_FILE_PATH);
+                            }
+                            file = new File(PDF_FILE_PATH, PDF_FILE_NAME);
+                            try {
+                                file.createNewFile();
+                            } catch (IOException e) {
+                                e.printStackTrace();
+                            }
+                            mDownloader = new ProgressDownloader(downloadUrl, file, PDFDownloadActivity.this);
+                            mDownloader.download(0L);
+                        }
+                    }
+                }
+
+            } catch (JSONException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
     private void displayFromFile(File fileName) {
         try {
             mPDFView.fromFile(fileName)
@@ -95,9 +180,9 @@ public class PDFDownloadActivity extends BaseActivity implements View.OnClickLis
 //                .swipeHorizontal(true)
                     .enableDoubletap(true)
                     .defaultPage(0)
-                            // allows to draw something on the current page, usually visible in the middle of the screen
+                    // allows to draw something on the current page, usually visible in the middle of the screen
                     .onDraw(this)
-                            // allows to draw something on all pages, separately for every page. Called only for visible pages
+                    // allows to draw something on all pages, separately for every page. Called only for visible pages
                     .onDrawAll(this)
                     .onLoad(this) // called after document is loaded and starts to be rendered
                     .onPageChange(this)
@@ -108,10 +193,11 @@ public class PDFDownloadActivity extends BaseActivity implements View.OnClickLis
                     .password(null)
                     .scrollHandle(null)
                     .enableAntialiasing(true) // improve rendering a little bit on low-res screens
-                            // spacing between pages in dp. To define spacing color, set view background
+                    // spacing between pages in dp. To define spacing color, set view background
                     .spacing(10)
                     .load();
         } catch (Exception e) {
+            mPauseTextView.setVisibility(View.GONE);
             mErrorLinearLayout.setVisibility(View.VISIBLE);
             mStateTextView.setText("报表文件加载失败!");
             mDownloadProgressBar.setProgress(0);
@@ -126,11 +212,20 @@ public class PDFDownloadActivity extends BaseActivity implements View.OnClickLis
 
         initViews();
         initEvents();
-        downloadPDF();
+        obtainPdfPath();
     }
 
-    private void downloadPDF() {
-        PDFUtils.downloadPDF(downloadUrl, mHandler);
+    private void obtainPdfPath() {
+        String url = "http://print.ubtob.com/report/pdf/path";
+        Map<String, Object> params = new HashMap<>();
+        params.put("u", CommonUtil.getSharedPreferences(ct, "erp_master"));
+        params.put("pf", "phone");
+        params.put("r", mReportName);
+        params.put("w", "where " + mCondition);
+        LinkedHashMap<String, Object> headers = new LinkedHashMap<>();
+        headers.put("Cookie", "JSESSIONID=" + CommonUtil.getSharedPreferences(ct, "sessionId"));
+        ViewUtil.httpSendRequest(this, url, params, mHandler, headers, OBATIN_PDF_PATH, null, null, "get");
+//        PDFUtils.downloadPDF(downloadUrl, mHandler);
     }
 
     private void initViews() {
@@ -144,15 +239,8 @@ public class PDFDownloadActivity extends BaseActivity implements View.OnClickLis
         if (mTitle != null)
             getSupportActionBar().setTitle(mTitle);
 
-//        downloadUrl = com.xzjmyk.pm.activity.ui.erp.util.Constants.getAppBaseUrl(this)
-//                + "report/pdf/data?u=" + CommonUtil.getSharedPreferences(ct, "erp_master")
-//                + "&pf=phone&r=" + mReportName + "&w=" + mCondition;
-//        downloadUrl = "http://192.168.253.60:8090/report/pdf/data?u=" + CommonUtil.getSharedPreferences(ct, "erp_master")
+//        downloadUrl = "http://print.ubtob.com/report/pdf/data?u=" + CommonUtil.getSharedPreferences(ct, "erp_master")
 //                + "&pf=phone&r=" + mReportName + "&w=where " + mCondition;
-        downloadUrl = "http://print.ubtob.com/report/pdf/data?u=" + CommonUtil.getSharedPreferences(ct, "erp_master")
-                + "&pf=phone&r=" + mReportName + "&w=where " + mCondition;
-
-        Log.d("downloadUrl", downloadUrl);
 
         mPDFView = (PDFView) findViewById(R.id.pdf_download_pdfview);
         mPDFView.useBestQuality(true);
@@ -164,12 +252,14 @@ public class PDFDownloadActivity extends BaseActivity implements View.OnClickLis
         mReloadTextView = (TextView) findViewById(R.id.pdf_download_reload_tv);
         mExitTextView = (TextView) findViewById(R.id.pdf_download_exit_tv);
         mErrorLinearLayout = (LinearLayout) findViewById(R.id.pdf_download_error_menu_ll);
+        mPauseTextView = (TextView) findViewById(R.id.pdf_download_pause_tv);
     }
 
     private void initEvents() {
         mExitTextView.setOnClickListener(this);
         mReloadTextView.setOnClickListener(this);
         mDownloadRelativeLayout.setOnClickListener(this);
+        mPauseTextView.setOnClickListener(this);
     }
 
     @Override
@@ -181,7 +271,21 @@ public class PDFDownloadActivity extends BaseActivity implements View.OnClickLis
             case R.id.pdf_download_reload_tv:
                 mStateTextView.setText(R.string.str_loading);
                 mErrorLinearLayout.setVisibility(View.GONE);
-                PDFUtils.downloadPDF(downloadUrl, mHandler);
+//                PDFUtils.downloadPDF(downloadUrl, mHandler);
+                obtainPdfPath();
+                break;
+            case R.id.pdf_download_pause_tv:
+                if (getString(R.string.pause_download).equals(mPauseTextView.getText().toString())) {
+                    mPauseTextView.setText(R.string.continue_download);
+                    mDownloader.pause();
+                    ToastUtil.showToast(this, "下载暂停");
+                    // 存储此时的totalBytes,即断点位置。
+                    breakPoints = totalBytes;
+                } else if (getString(R.string.continue_download).equals(mPauseTextView.getText().toString())) {
+                    mPauseTextView.setText(R.string.pause_download);
+                    ToastUtil.showToast(this, "下载继续");
+                    mDownloader.download(breakPoints);
+                }
                 break;
         }
     }
@@ -214,6 +318,7 @@ public class PDFDownloadActivity extends BaseActivity implements View.OnClickLis
 
     @Override
     public void onError(Throwable t) {
+        mPauseTextView.setVisibility(View.GONE);
         mErrorLinearLayout.setVisibility(View.VISIBLE);
         mStateTextView.setText("报表文件加载失败!");
         mDownloadProgressBar.setProgress(0);
@@ -224,4 +329,27 @@ public class PDFDownloadActivity extends BaseActivity implements View.OnClickLis
     public void onInitiallyRendered(int nbPages, float pageWidth, float pageHeight) {
         mPDFView.fitToWidth();
     }
+
+    @Override
+    public void onPreExecute(long contentLength) {
+        // 文件总长只需记录一次,要注意断点续传后的contentLength只是剩余部分的长度
+        if (this.contentLength == 0L) {
+            this.contentLength = contentLength;
+            mDownloadProgressBar.setMax((int) (contentLength / 1024));
+        }
+    }
+
+    @Override
+    public void update(long totalBytes, boolean done) {
+        // 注意加上断点的长度
+        this.totalBytes = totalBytes + breakPoints;
+        int progress = (int) (totalBytes + breakPoints) / 1024;
+        Message message = Message.obtain();
+        message.what = Constants.CONSTANT.DOWNLOAD_PROGRESS;
+        message.obj = progress;
+        mHandler.sendMessage(message);
+        if (done) {
+            mHandler.sendEmptyMessage(Constants.CONSTANT.DOWNLOAD_SUCCESS);
+        }
+    }
 }

+ 15 - 19
WeiChat/src/main/java/com/xzjmyk/pm/activity/ui/erp/net/ViewUtil.java

@@ -48,7 +48,6 @@ import java.util.List;
 import java.util.Map;
 
 
-
 /**
  * @author :LiuJie 时间: 2015年4月27日 上午11:30:17
  * @注释:UI公共方法类 全局登录
@@ -69,8 +68,6 @@ public class ViewUtil {
     private static List<LoginEntity> erpEntities;
     private static boolean hasErp = true;//是否有erp
 
- 
-
 
     private static String oldMsg;
     private static long time;
@@ -78,7 +75,6 @@ public class ViewUtil {
     private static long time2;
 
 
-
     public static Crouton crouton;
 
     /**
@@ -307,17 +303,17 @@ public class ViewUtil {
 //                showDialogCompany(CommonUtil.getSharedPreferences(ct, "loginJson"), user_phone, user_password);
 //            }
 //        } else {
-            //登录界面过来,不走缓存
-            String url = Constants.BASE_URL_LOGIN;
-            Map<String, String> params = new HashMap<String, String>();
-            params.put("user", user_phone);
-            params.put("password", user_password);
-            Message message = new Message();
-            Bundle bundle = new Bundle();
-            bundle.putString("phone", user_phone);
-            bundle.putString("password", user_password);
-            startNetThread(url, params, handler, Constants.SUCCESS_LOGIN, message,
-                    bundle, "get");
+        //登录界面过来,不走缓存
+        String url = Constants.BASE_URL_LOGIN;
+        Map<String, String> params = new HashMap<String, String>();
+        params.put("user", user_phone);
+        params.put("password", user_password);
+        Message message = new Message();
+        Bundle bundle = new Bundle();
+        bundle.putString("phone", user_phone);
+        bundle.putString("password", user_password);
+        startNetThread(url, params, handler, Constants.SUCCESS_LOGIN, message,
+                bundle, "get");
 //        }
 
     }
@@ -474,7 +470,7 @@ public class ViewUtil {
         if (ct instanceof Activity) {
 //            if (!StringUtil.isEmpty(CommonUtil.getSharedPreferences(MyApplication.getInstance(),"erp_baseurl"))){
 //            }else{
-                ct.startActivity(new Intent("com.modular.main.DataDownloadActivity"));
+            ct.startActivity(new Intent("com.modular.main.DataDownloadActivity"));
 //            }
         }
         if (isBrodcast)
@@ -512,8 +508,8 @@ public class ViewUtil {
         }, 1500);
         if (!hasErp) {
             if (ct instanceof Activity) {
-                if (!StringUtil.isEmpty(CommonUtil.getSharedPreferences(MyApplication.getInstance(),"erp_baseurl"))){
-                }else{
+                if (!StringUtil.isEmpty(CommonUtil.getSharedPreferences(MyApplication.getInstance(), "erp_baseurl"))) {
+                } else {
                     ct.startActivity(new Intent("com.modular.main.DataDownloadActivity"));
                 }
             }
@@ -812,6 +808,7 @@ public class ViewUtil {
                             if (result.getStatusCode() == 404) {
                                 exception = "404系统错误";
                             }
+                            finalBundle.putString("response", result.getResponseText());
                             finalBundle.putString("result", exception);
                             finalBundle.putInt("what", what);
                             finalBundle.putInt("code", result.getStatusCode());
@@ -955,7 +952,6 @@ public class ViewUtil {
     }
 
 
-    
     public static void clearAccount(Context ct) {
         CommonUtil.clearSharedPreferences(ct, "erp_baseurl");
         CommonUtil.clearSharedPreferences(ct, "erp_master");

+ 25 - 10
WeiChat/src/main/res/layout/activity_pdf_download.xml

@@ -9,7 +9,7 @@
     <com.github.barteksc.pdfviewer.PDFView
         android:id="@+id/pdf_download_pdfview"
         android:layout_width="match_parent"
-        android:layout_height="match_parent"/>
+        android:layout_height="match_parent" />
 
     <RelativeLayout
         android:id="@+id/pdf_download_progress_rl"
@@ -27,11 +27,11 @@
                 android:id="@+id/pdf_download_state_tv"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
+                android:ellipsize="end"
                 android:gravity="center"
-                android:text="@string/str_loading"
                 android:maxLines="2"
-                android:ellipsize="end"
-                android:textSize="16sp"/>
+                android:text="@string/str_loading"
+                android:textSize="16sp" />
 
             <ProgressBar
                 android:id="@+id/pdf_download_progress_pb"
@@ -42,7 +42,6 @@
                 android:layout_marginLeft="40dp"
                 android:layout_marginRight="40dp"
                 android:layout_marginTop="10dp"
-                android:max="100"
                 android:progress="0"
                 />
 
@@ -56,7 +55,7 @@
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:text="剩余 "
-                    android:textSize="16sp"/>
+                    android:textSize="16sp" />
 
                 <TextView
                     android:id="@+id/pdf_download_remain_tv"
@@ -64,16 +63,32 @@
                     android:layout_height="wrap_content"
                     android:text="100"
                     android:textColor="@color/titleBlue"
-                    android:textSize="16sp"/>
+                    android:textSize="16sp" />
 
                 <TextView
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:text=" %"
-                    android:textSize="16sp"/>
+                    android:textSize="16sp" />
             </LinearLayout>
         </LinearLayout>
 
+
+        <TextView
+            android:id="@+id/pdf_download_pause_tv"
+            android:layout_width="match_parent"
+            android:layout_height="40dp"
+            android:layout_alignParentBottom="true"
+            android:layout_marginBottom="20dp"
+            android:layout_marginLeft="30dp"
+            android:layout_marginRight="30dp"
+            android:background="@drawable/selector_confirm_bg"
+            android:gravity="center"
+            android:text="@string/pause_download"
+            android:textColor="@color/white"
+            android:textSize="16sp"
+            android:visibility="gone" />
+
         <LinearLayout
             android:id="@+id/pdf_download_error_menu_ll"
             android:layout_width="match_parent"
@@ -94,7 +109,7 @@
                 android:gravity="center"
                 android:text="@string/re_download"
                 android:textColor="@color/white"
-                android:textSize="16sp"/>
+                android:textSize="16sp" />
 
             <TextView
                 android:id="@+id/pdf_download_exit_tv"
@@ -106,7 +121,7 @@
                 android:gravity="center"
                 android:text="@string/exit"
                 android:textColor="@color/selector_cancel_text_color"
-                android:textSize="16sp"/>
+                android:textSize="16sp" />
 
         </LinearLayout>
 

+ 2 - 0
WeiChat/src/main/res/values-en/strings.xml

@@ -1434,5 +1434,7 @@
     <string name="re_download">重新下载</string>
     <string name="search_history">搜索历史</string>
     <string name="str_clear">清空</string>
+    <string name="pause_download">暂停下载</string>
+    <string name="continue_download">继续下载</string>
 
 </resources>

+ 2 - 0
WeiChat/src/main/res/values-zh-rCN/strings.xml

@@ -1546,5 +1546,7 @@
     <string name="re_download">重新下载</string>
     <string name="search_history">搜索历史</string>
     <string name="str_clear">清空</string>
+    <string name="pause_download">暂停下载</string>
+    <string name="continue_download">继续下载</string>
 
 </resources>

+ 2 - 0
WeiChat/src/main/res/values-zh-rTW/strings.xml

@@ -1535,5 +1535,7 @@
     <string name="re_download">重新下载</string>
     <string name="search_history">搜索历史</string>
     <string name="str_clear">清空</string>
+    <string name="pause_download">暂停下载</string>
+    <string name="continue_download">继续下载</string>
 
 </resources>

+ 2 - 0
WeiChat/src/main/res/values/strings.xml

@@ -1878,4 +1878,6 @@
     <string name="re_download">重新下载</string>
     <string name="search_history">搜索历史</string>
     <string name="str_clear">清空</string>
+    <string name="pause_download">暂停下载</string>
+    <string name="continue_download">继续下载</string>
 </resources>

+ 1 - 0
app_core/common/build.gradle

@@ -38,6 +38,7 @@ dependencies {
     compile deps.photoView
     compile deps.stickyListHeaders
     compile deps.stickyGridHeaders
+    compile 'com.squareup.okhttp3:okhttp:3.9.0'
 
     compile project(':pullToRefershLibraryMy')
     compile project(':MPAndroidChart')

+ 120 - 0
app_core/common/src/main/java/com/core/net/ProgressDownloader.java

@@ -0,0 +1,120 @@
+package com.core.net;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.RandomAccessFile;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.FileChannel;
+
+import okhttp3.Call;
+import okhttp3.Callback;
+import okhttp3.Interceptor;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+import okhttp3.ResponseBody;
+
+/**
+ * Created by RaoMeng on 2017/9/25.
+ * okhttp实现的下载工具类
+ * 支持下载暂停以及断电续传
+ */
+
+public class ProgressDownloader {
+    private ProgressResponseBody.ProgressListener progressListener;
+    private String url;
+    private OkHttpClient client;
+    private File destination;
+    private Call call;
+
+    public ProgressDownloader(String url, File destination, ProgressResponseBody.ProgressListener progressListener) {
+        this.url = url;
+        this.destination = destination;
+        this.progressListener = progressListener;
+        //在下载、暂停后的继续下载中可复用同一个client对象
+        client = getProgressClient();
+    }
+
+    //每次下载需要新建新的Call对象
+    private Call newCall(long startPoints) {
+        Request request = new Request.Builder()
+                .url(url)
+                .header("RANGE", "bytes=" + startPoints + "-")//断点续传要用到的,指示下载的区间
+                .build();
+        return client.newCall(request);
+    }
+
+    public OkHttpClient getProgressClient() {
+        // 拦截器,用上ProgressResponseBody
+        Interceptor interceptor = new Interceptor() {
+            @Override
+            public Response intercept(Chain chain) throws IOException {
+                Response originalResponse = chain.proceed(chain.request());
+                return originalResponse.newBuilder()
+                        .body(new ProgressResponseBody(originalResponse.body(), progressListener))
+                        .build();
+            }
+        };
+
+        return new OkHttpClient.Builder()
+                .addNetworkInterceptor(interceptor)
+                .build();
+    }
+
+    // startsPoint指定开始下载的点
+    public void download(final long startsPoint) {
+        call = newCall(startsPoint);
+        call.enqueue(new Callback() {
+            @Override
+            public void onFailure(Call call, IOException e) {
+
+            }
+
+            @Override
+            public void onResponse(Call call, Response response) throws IOException {
+                save(response, startsPoint);
+            }
+        });
+    }
+
+    public void pause() {
+        if (call != null) {
+            call.cancel();
+        }
+    }
+
+    private void save(Response response, long startsPoint) {
+        ResponseBody body = response.body();
+        InputStream in = body.byteStream();
+        FileChannel channelOut = null;
+        // 随机访问文件,可以指定断点续传的起始位置
+        RandomAccessFile randomAccessFile = null;
+        try {
+            randomAccessFile = new RandomAccessFile(destination, "rwd");
+            //Chanel NIO中的用法,由于RandomAccessFile没有使用缓存策略,直接使用会使得下载速度变慢,亲测缓存下载3.3秒的文件,用普通的RandomAccessFile需要20多秒。
+            channelOut = randomAccessFile.getChannel();
+            // 内存映射,直接使用RandomAccessFile,是用其seek方法指定下载的起始位置,使用缓存下载,在这里指定下载位置。
+            MappedByteBuffer mappedBuffer = channelOut.map(FileChannel.MapMode.READ_WRITE, startsPoint, body.contentLength());
+            byte[] buffer = new byte[1024];
+            int len;
+            while ((len = in.read(buffer)) != -1) {
+                mappedBuffer.put(buffer, 0, len);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                in.close();
+                if (channelOut != null) {
+                    channelOut.close();
+                }
+                if (randomAccessFile != null) {
+                    randomAccessFile.close();
+                }
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+}

+ 72 - 0
app_core/common/src/main/java/com/core/net/ProgressResponseBody.java

@@ -0,0 +1,72 @@
+package com.core.net;
+
+import java.io.IOException;
+
+import okhttp3.MediaType;
+import okhttp3.ResponseBody;
+import okio.Buffer;
+import okio.BufferedSource;
+import okio.ForwardingSource;
+import okio.Okio;
+import okio.Source;
+
+/**
+ * Created by RaoMeng on 2017/9/25.
+ * okhttp下载返回体
+ */
+
+public class ProgressResponseBody extends ResponseBody {
+    public interface ProgressListener {
+        void onPreExecute(long contentLength);
+
+        void update(long totalBytes, boolean done);
+    }
+
+    private final ResponseBody responseBody;
+    private final ProgressListener progressListener;
+    private BufferedSource bufferedSource;
+
+    public ProgressResponseBody(ResponseBody responseBody,
+                                ProgressListener progressListener) {
+        this.responseBody = responseBody;
+        this.progressListener = progressListener;
+        if (progressListener != null) {
+            progressListener.onPreExecute(contentLength());
+        }
+    }
+
+    @Override
+    public MediaType contentType() {
+        return responseBody.contentType();
+    }
+
+    @Override
+    public long contentLength() {
+        return responseBody.contentLength();
+    }
+
+    @Override
+    public BufferedSource source() {
+        if (bufferedSource == null) {
+            bufferedSource = Okio.buffer(source(responseBody.source()));
+        }
+        return bufferedSource;
+    }
+
+    private Source source(Source source) {
+        return new ForwardingSource(source) {
+            long totalBytes = 0L;
+
+            @Override
+            public long read(Buffer sink, long byteCount) throws IOException {
+                long bytesRead = super.read(sink, byteCount);
+                // read() returns the number of bytes read, or -1 if this source is exhausted.
+                totalBytes += bytesRead != -1 ? bytesRead : 0;
+                if (null != progressListener) {
+                    progressListener.update(totalBytes, bytesRead == -1);
+                }
+                return bytesRead;
+            }
+        };
+    }
+}

+ 43 - 0
app_core/common/src/main/java/com/core/utils/CommonUtil.java

@@ -735,4 +735,47 @@ public class CommonUtil {
         }
         return sb.toString().trim();
     }
+
+    public static boolean delAllFile(String path) {
+        boolean flag = false;
+        File file = new File(path);
+        if (!file.exists()) {
+            return flag;
+        }
+        if (!file.isDirectory()) {
+            return flag;
+        }
+        String[] tempList = file.list();
+        File temp = null;
+        for (int i = 0; i < tempList.length; i++) {
+            if (path.endsWith(File.separator)) {
+                temp = new File(path + tempList[i]);
+            } else {
+                temp = new File(path + File.separator + tempList[i]);
+            }
+            if (temp.isFile()) {
+                temp.delete();
+            }
+            if (temp.isDirectory()) {
+                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
+                delFolder(path + "/" + tempList[i]);//再删除空文件夹
+                flag = true;
+            }
+        }
+        return flag;
+    }
+
+    //删除文件夹
+    //param folderPath 文件夹完整绝对路径
+    public static void delFolder(String folderPath) {
+        try {
+            delAllFile(folderPath); //删除完里面所有内容
+            String filePath = folderPath;
+            filePath = filePath.toString();
+            java.io.File myFilePath = new java.io.File(filePath);
+            myFilePath.delete(); //删除空文件夹
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
 }

+ 1 - 1
app_modular/applogin/src/main/java/com/modular/login/activity/AdminRegisterActivity.java

@@ -201,7 +201,7 @@ public class AdminRegisterActivity extends BaseActivity implements View.OnClickL
             }
 
             if (allValid) {
-                mFlag = 60;
+                mFlag = 10;
                 mTimer = new Timer();
                 mTimer.schedule(new TimerTask() {
                     @Override

+ 7 - 2
app_modular/applogin/src/main/java/com/modular/login/activity/EnterpriseRegisterActivity.java

@@ -102,6 +102,11 @@ public class EnterpriseRegisterActivity extends BaseActivity implements View.OnC
                         try {
                             JSONObject resultObject = new JSONObject(result);
                             if (resultObject.optBoolean("success")) {
+                                JSONObject contentObject = resultObject.optJSONObject("content");
+                                if (contentObject != null) {
+                                    String pageToken = contentObject.optString("pageToken");
+                                    CommonUtil.setSharedPreferences(ct, "pageToken", pageToken);
+                                }
                                 Intent intent = new Intent();
                                 intent.setClass(EnterpriseRegisterActivity.this, AdminRegisterActivity.class);
                                 startActivity(intent);
@@ -201,7 +206,7 @@ public class EnterpriseRegisterActivity extends BaseActivity implements View.OnC
                     Iterator<String> secondKeys = secondObject.keys();
                     while (secondKeys.hasNext()) {
                         ProfessionBean.ProfessionSecondBean professionSecond = new ProfessionBean.ProfessionSecondBean();
-                        String secondTitle = iterator.next().toString();
+                        String secondTitle = secondKeys.next().toString();
                         professionSecond.setProfessionSecondTitle(secondTitle);
 
                         List<String> thirdTitles = new ArrayList<>();
@@ -225,8 +230,8 @@ public class EnterpriseRegisterActivity extends BaseActivity implements View.OnC
                 professionBean.setProfessionSecondTitles(professionSecondList);
 
                 mProfessionList.add(professionBean);
-                Log.d("professionList", mProfessionList.toString());
             }
+            Log.d("professionList", mProfessionList.toString());
         } catch (JSONException e) {
             e.printStackTrace();
         }