Forráskód Böngészése

文件上传功能优化

guilin 1 hónapja
szülő
commit
1015dbf0b3

+ 2 - 0
app/src/main/AndroidManifest.xml

@@ -2,6 +2,8 @@
 
           xmlns:tools="http://schemas.android.com/tools" package="com.fxy">
 
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.CHANGE_CONFIGURATION"
                      tools:ignore="ProtectedPermissions"/>
     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

+ 42 - 13
app/src/main/java/com/fxy/common/AsyncFileUpload.java

@@ -25,6 +25,7 @@ import com.lzy.okgo.model.Response;
 import org.greenrobot.eventbus.EventBus;
 import org.json.JSONObject;
 
+import java.io.File;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -66,15 +67,12 @@ public class AsyncFileUpload {
     }
 
 
-
     public void setUploadType(String fileKey) {
         this.fileKey = fileKey;
     }
 
 
 
-
-
     @SuppressLint("HandlerLeak")
     private Handler uploadHandler = new Handler() {
         @Override
@@ -165,10 +163,6 @@ public class AsyncFileUpload {
         // 如果裁剪并压缩了,以取压缩路径为准,因为是先裁剪后压缩的
         LocalMedia localMedia = awaitUploadList.get(num).getLocalMedia();
         String urlPath =localMedia.getPath();
-        if (localMedia.isCompressed() && localMedia.getCompressPath()!=null){
-            urlPath = localMedia.getCompressPath();
-        }
-
         if (urlPath.isEmpty()){
             Message msg = new Message();
             msg.obj = "文件路径不存在";
@@ -177,6 +171,13 @@ public class AsyncFileUpload {
             return;
         }
 
+        if (localMedia.isCompressed() && localMedia.getCompressPath()!=null){
+            if (new File(localMedia.getCompressPath()).exists()){
+                urlPath = localMedia.getCompressPath();
+            }
+        }
+
+
 
         String fileName = "";
         String path_prefix = "";
@@ -186,8 +187,12 @@ public class AsyncFileUpload {
 
         //目录为空
         if (ossUrl.isEmpty()){
-            resultUpload( awaitUploadList.get(num).getId(),0,"");
-            awaitUploadList.remove(num);
+            setPushStatus(awaitUploadList.get(num).getId(),1,1);
+            if (awaitUploadList.size()>0){
+                resultUpload(awaitUploadList.get(num).getId(),0,"");
+            }
+
+
             return;
         }
 
@@ -200,7 +205,9 @@ public class AsyncFileUpload {
         if (ossService ==null){
             ossService = new OssService(mContext,path_prefix);
         }
-        ossService.ossUpload(urlPath, fileName , num,uploadHandler);
+
+        ossService.ossUpload(urlPath, fileName , num,uploadHandler,path_prefix);
+        //ossService.ossUpload(urlPath, fileName , num,uploadHandler);
         setIsFinish(awaitUploadList.get(num).getId(),1);
     }
 
@@ -227,6 +234,7 @@ public class AsyncFileUpload {
     }
 
     public int getAllAwaitNum(){
+
         RealmResults<AsyncUploadRealm> realmResults  = mRealm.where(AsyncUploadRealm.class)
                 .equalTo("isDelete",0)
                 .equalTo("pushStatus",0)
@@ -247,6 +255,8 @@ public class AsyncFileUpload {
             awaitUploadList.addAll(realmResults);
         }
 
+
+
         if (awaitUploadList.size()>0){
             filedUpload(0);
         }else{
@@ -329,9 +339,18 @@ public class AsyncFileUpload {
             mRealm.beginTransaction();
             AsyncUploadRealm myObject = mRealm.where(AsyncUploadRealm.class).equalTo("id",tmpRealmId).findFirst();
             assert myObject != null;
-            myObject.setPushStatus(pushStatus);
-            myObject.setIsFinish( pushStatus == 1 ? 3 : 2);
-            myObject.setOssUrl(photoPath);
+            if (myObject.getPushStatus()!=3){
+                myObject.setPushStatus(pushStatus);
+            }
+            //已完成则不需要再更新
+            if (myObject.getIsFinish() != 3){
+                myObject.setIsFinish( status == 1 ? 3 : 2);
+            }
+            if (status == 1){
+                myObject.setOssUrl(photoPath);
+            }
+
+
             mRealm.commitTransaction();
 
         }
@@ -343,6 +362,16 @@ public class AsyncFileUpload {
         }
 
     }
+    private void setPushStatus(String realmId,Integer pushStatus,int isDelete){
+        //更新值
+        mRealm.beginTransaction();
+        AsyncUploadRealm myObject = mRealm.where(AsyncUploadRealm.class).equalTo("id",realmId).findFirst();
+        assert myObject != null;
+        myObject.setPushStatus(pushStatus);
+        myObject.setIsDelete(isDelete);
+
+        mRealm.commitTransaction();
+    }
 
     //销毁
     public void removeHandler(){

+ 49 - 35
app/src/main/java/com/fxy/common/AsyncPictureSelector.java

@@ -215,15 +215,13 @@ public class AsyncPictureSelector {
     public void getSelectImg (Intent data){
         List<LocalMedia>  fileList = PictureSelector.obtainMultipleResult(data);
         for (int i = 0; i < fileList.size(); i++) {
-            addUploadFile(fileList.get(i));
-            selectList.add(fileList.get(i));
+            if (addUploadFile(fileList.get(i))){
+                selectList.add(fileList.get(i));
+            }
         }
 
         adapter.setList(selectList);
         adapter.notifyDataSetChanged();
-
-
-
     }
 
     public String getUniqueTag(){
@@ -482,37 +480,53 @@ public class AsyncPictureSelector {
 
 
 
-    private void addUploadFile(LocalMedia localMedia){
+    private boolean addUploadFile(LocalMedia localMedia){
         String realmId = UUID.randomUUID().toString();
         String scan_date = DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS);
-        //同步操作写法一:
-        mRealm.beginTransaction();
-        //会创建对象和user表
-        AsyncUploadRealm takePhotosRealm = mRealm.createObject(AsyncUploadRealm.class,realmId);
-        Gson gson = new Gson();
-        String localMediaStr = gson.toJson(localMedia);
-        takePhotosRealm.setLocalMediaStr(localMediaStr);
-        takePhotosRealm.setOssUrl("");
-        takePhotosRealm.setScanDate(scan_date);
-        takePhotosRealm.setUploadType(uploadType);
-        takePhotosRealm.setNotifyKey(fileKey);
-        takePhotosRealm.setNotifyParam(gson.toJson(notifyParam));
-        takePhotosRealm.setNotifyUrl(notifyUrl);
-        takePhotosRealm.setUniqueTag(uniqueTag);
-
-
-        String path_prefix = resourcePrefix+"/android/"+mPrefix+"/"+RxTimeTool.getYestoryDate("yyyyMMd")+"/";
-        String urlPath = isCompress && localMedia.getCompressPath()!=null ? localMedia.getCompressPath() :  localMedia.getPath();
-        String fileSuffix = urlPath.lastIndexOf(".")>-1 ? urlPath.substring(urlPath.lastIndexOf(".")) : "";
-        String fileName = UUID.randomUUID().toString() + fileSuffix;
-        takePhotosRealm.setOssUrl(path_prefix+fileName);
-        ossPhotoList.add("/"+path_prefix+fileName);
-        //
-
-        Date date = new Date();
-        takePhotosRealm.setCreateTime(date.getTime());
-        takePhotosRealm.setPushStatus(0);
-        //提交事务,操作就被执行
-        mRealm.commitTransaction();
+        try {
+            //同步操作写法一:
+            mRealm.beginTransaction();
+            //会创建对象和user表
+            AsyncUploadRealm takePhotosRealm = mRealm.createObject(AsyncUploadRealm.class,realmId);
+            Gson gson = new Gson();
+            String localMediaStr = gson.toJson(localMedia);
+            takePhotosRealm.setLocalMediaStr(localMediaStr);
+            takePhotosRealm.setOssUrl("");
+            takePhotosRealm.setScanDate(scan_date);
+            takePhotosRealm.setUploadType(uploadType);
+            takePhotosRealm.setNotifyKey(fileKey);
+            takePhotosRealm.setNotifyParam(gson.toJson(notifyParam));
+            takePhotosRealm.setNotifyUrl(notifyUrl);
+            takePhotosRealm.setUniqueTag(uniqueTag);
+
+
+            String path_prefix = resourcePrefix+"/android/"+mPrefix+"/"+RxTimeTool.getYestoryDate("yyyyMMd")+"/";
+            String urlPath = isCompress && localMedia.getCompressPath()!=null ? localMedia.getCompressPath() :  localMedia.getPath();
+            String fileSuffix = urlPath.lastIndexOf(".")>-1 ? urlPath.substring(urlPath.lastIndexOf(".")) : "";
+            String fileName = UUID.randomUUID().toString() + fileSuffix;
+            takePhotosRealm.setOssUrl(path_prefix+fileName);
+            ossPhotoList.add("/"+path_prefix+fileName);
+            //
+
+            Date date = new Date();
+            takePhotosRealm.setCreateTime(date.getTime());
+            takePhotosRealm.setPushStatus(0);
+            //提交事务,操作就被执行
+            mRealm.commitTransaction();
+
+        }catch (Exception e) {
+            // 如果事务不能提交,则在这里处理错误
+            e.printStackTrace();
+            // 如果需要的话,可以回滚事务
+        }
+        return checkDataExists(realmId);
+
+    }
+
+    public  boolean checkDataExists(String fieldValue) {
+        RealmResults<AsyncUploadRealm> results  = mRealm.where(AsyncUploadRealm.class)
+                .equalTo("id", fieldValue)
+                .findAll();
+        return results.size() > 0;
     }
 }

+ 37 - 25
app/src/main/java/com/fxy/common/AsyncPictureUpload.java

@@ -48,6 +48,7 @@ import org.json.JSONObject;
 
 import java.io.File;
 import java.util.ArrayList;
+import java.util.Calendar;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
@@ -106,7 +107,10 @@ public class AsyncPictureUpload {
     //
     private boolean isAllRe =false;
 
-
+    private boolean debug = false;
+    public void setDebug(boolean debug) {
+        this.debug = debug;
+    }
     public AsyncPictureUpload(Activity activity){
         mActivity = activity;
         mContext  = activity.getBaseContext();
@@ -172,6 +176,7 @@ public class AsyncPictureUpload {
      * @return
      */
     public int getAllAwaitNum(){
+
         if (isAllRe){
             Integer[] pushStatus = {0,1};
             RealmResults<AsyncUploadRealm> realmResults  = mRealm.where(AsyncUploadRealm.class)
@@ -296,30 +301,29 @@ public class AsyncPictureUpload {
         // 如果裁剪并压缩了,以取压缩路径为准,因为是先裁剪后压缩的
         LocalMedia localMedia = awaitUploadList.get(num).getLocalMedia();
         String urlPath =localMedia.getPath();
-        if (localMedia.isCompressed() && localMedia.getCompressPath()!=null){
-            if (new File(localMedia.getCompressPath()).exists()){
-                urlPath = localMedia.getCompressPath();
-            }
-
-        }
-
         if (urlPath.isEmpty()){
+            setPushStatus(awaitUploadList.get(num).getId(),1,1);
             Message msg = new Message();
             msg.obj = "文件路径不为空";
             msg.what = 1;
             uploadHandler.sendMessage(msg);
+
             return;
         }
 
-        File file = new File(urlPath);
-        if (!file.exists()){
+        if (localMedia.isCompressed() && localMedia.getCompressPath()!=null){
+            if (new File(localMedia.getCompressPath()).exists()){
+                urlPath = localMedia.getCompressPath();
+            }
+        }
+
+        if (!new File(urlPath).exists()){
             XLog.d("文件不存在本地路径"+urlPath+",拍照时间:"+awaitUploadList.get(num).getCreateTime());
             setPushStatus(awaitUploadList.get(num).getId(),1,1);
             Message msg = new Message();
             msg.obj = "文件路径不存在";
             msg.what = 1;
             uploadHandler.sendMessage(msg);
-
             return;
         }
 
@@ -348,17 +352,15 @@ public class AsyncPictureUpload {
                 cosService  = new CosService(mActivity.getBaseContext(),path_prefix);
             }
             //new cosThread(urlPath, fileName , num).start();
-            cosService.cosUpload(urlPath, fileName , num,uploadHandler);
+            cosService.cosUpload(urlPath, fileName , num,uploadHandler,path_prefix);
 
         }else{
             if (ossService ==null){
                 ossService = new OssService(mActivity,path_prefix);
-
             }
+            ossService.ossUpload(urlPath, fileName , num,uploadHandler,path_prefix);
+            //ossService.ossUpload(urlPath, fileName , num,uploadHandler);
 
-
-            ossService.ossUpload(urlPath, fileName , num,uploadHandler);
-            //new ossThread(urlPath, fileName , num).start();
         }
         // task.cancel(); // 可以取消任务
         // task.waitUntilFinished(); // 可以等待直到任务完成
@@ -383,11 +385,19 @@ public class AsyncPictureUpload {
             RealmResults<AsyncUploadRealm> realmResults  = getBatchUploadRealm();
             awaitUploadList.addAll(realmResults);
         }
-
         if (awaitUploadList.size()>0){
             filedUpload(0);
         }
     }
+    public static long getNextTimestamp(int day) {
+        Calendar calendar = Calendar.getInstance();
+        calendar.set(Calendar.HOUR_OF_DAY, 0);
+        calendar.add(Calendar.DAY_OF_MONTH, day);
+        calendar.set(Calendar.MINUTE, 0);
+        calendar.set(Calendar.SECOND, 0);
+        calendar.set(Calendar.MILLISECOND, 0);
+        return calendar.getTimeInMillis();
+    }
 
     //取消任务
     public void taskCancel(){
@@ -442,8 +452,7 @@ public class AsyncPictureUpload {
         Integer[] isFinish = {0,1,2};
         RealmResults<AsyncUploadRealm> realmResults ;
         RealmQuery<AsyncUploadRealm> queryRealm =  mRealm.where(AsyncUploadRealm.class)
-                .equalTo("isDelete",0)
-                .in("isFinish",isFinish);
+                .equalTo("isDelete",0);
         if (isAllRe){
             Integer[] pushStatus = {0,1};
             queryRealm.in("pushStatus",pushStatus)
@@ -498,13 +507,16 @@ public class AsyncPictureUpload {
             mRealm.beginTransaction();
             AsyncUploadRealm myObject = mRealm.where(AsyncUploadRealm.class).equalTo("id",tmpRealmId).findFirst();
             assert myObject != null;
-            myObject.setPushStatus(pushStatus);
-            myObject.setIsFinish( pushStatus == 1 ? 3 : 2);
-            //失败更新
-            if (status==0){
-                myObject.setRePush(myObject.getRePush()+1);
+            if (myObject.getPushStatus()!=3){
+                myObject.setPushStatus(pushStatus);
+            }
+            //已完成则不需要再更新
+            if (myObject.getIsFinish() != 3){
+                myObject.setIsFinish( status == 1 ? 3 : 2);
+            }
+            if (status == 1){
+                myObject.setOssUrl(photoPath);
             }
-            myObject.setOssUrl(photoPath);
             mRealm.commitTransaction();
 
         }

+ 0 - 878
app/src/main/java/com/fxy/common/AsyncUpload.java

@@ -1,878 +0,0 @@
-package com.fxy.common;
-
-import android.Manifest;
-import android.annotation.SuppressLint;
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.app.ProgressDialog;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.graphics.Color;
-import android.graphics.drawable.ColorDrawable;
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import android.os.Handler;
-import android.os.Message;
-import android.support.v7.widget.GridLayoutManager;
-import android.support.v7.widget.RecyclerView;
-import android.view.Gravity;
-import android.view.View;
-import android.view.WindowManager;
-import android.widget.PopupWindow;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
-import com.elvishew.xlog.XLog;
-import com.fxy.R;
-import com.fxy.adapter.GridImageAdapter;
-import com.fxy.baselibrary.util.DateUtil;
-import com.fxy.baselibrary.util.JsonUtil;
-import com.fxy.baselibrary.util.RxTimeTool;
-import com.fxy.bean.ActionBean;
-import com.fxy.constant.SPCache;
-import com.fxy.net.MyDialogCallback;
-import com.fxy.net.Urls;
-import com.fxy.realm.AsyncUploadRealm;
-import com.fxy.view.FullyGridLayoutManager;
-import com.google.gson.Gson;
-import com.google.gson.reflect.TypeToken;
-import com.luck.picture.lib.PictureSelector;
-import com.luck.picture.lib.config.PictureConfig;
-import com.luck.picture.lib.config.PictureMimeType;
-import com.luck.picture.lib.entity.LocalMedia;
-import com.luck.picture.lib.permissions.Permission;
-import com.luck.picture.lib.permissions.RxPermissions;
-import com.lzy.okgo.OkGo;
-import com.lzy.okgo.model.Response;
-
-import org.greenrobot.eventbus.EventBus;
-import org.json.JSONObject;
-
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import io.reactivex.functions.Consumer;
-import io.realm.Realm;
-import io.realm.RealmResults;
-
-public class AsyncUpload {
-    private final Activity mActivity;
-    private final Context mContext;
-    private int maxSelectNum = 9;
-    private GridImageAdapter adapter;
-    private final RecyclerView mRecyclerView;
-    private PopupWindow pop;
-
-    private boolean onlyCamera = false;
-    private boolean isCompress = false;
-    private int compressQuality = 100;//默认值
-    private int minimumCompressSize = 100;//最小压缩
-
-
-    //资源类型
-    private int pictureType=1;
-
-
-
-    private String uploadType = "";
-    //文件上传类型
-    protected String fileKey = "";
-
-    //通知地址
-    private String notifyUrl = "";
-
-    //唯一标识
-    private String uniqueTag = "";
-
-    //通知地址
-    private HashMap<String, Object> notifyParam  = new HashMap<>();
-
-
-    private HashMap<String, Object> limitOperate  = new HashMap<>();
-
-    protected Realm mRealm;
-    private List<AsyncUploadRealm> awaitUploadList=new ArrayList<>();
-
-
-    //
-    private List<LocalMedia> selectList = new ArrayList<>();
-    //上传图片路径
-    private ArrayList<String> ossPhotoList =new ArrayList<>();
-
-    private String mPrefix="tally";
-
-    //是否停止上传
-    private String resourceUrl = "";
-
-    private String resourceType = "";
-
-    private String resourcePrefix = "/fxy";
-
-    private OssService ossService;
-
-    private CosService cosService;
-
-    //是自动上传
-    private boolean isAutoUpload = true;
-
-    private boolean allowUpload = false;
-
-
-    public AsyncUpload(Activity activity, RecyclerView rvShowImg, String prefix,String fileKey, String notifyUrl,boolean isAutoUpload){
-
-        mActivity = activity;
-        mContext  = activity.getBaseContext();
-        mRecyclerView = rvShowImg;
-        this.fileKey = fileKey;
-        this.mPrefix = prefix;
-        this.notifyUrl = notifyUrl;
-        this.isAutoUpload = isAutoUpload;
-
-        //自动上传则允许继续上次
-        this.allowUpload  = isAutoUpload;
-        initAdapter();
-        initData();
-    }
-
-
-
-    private void initData() {
-        SPCache spCache = SPCache.getInstance(mContext);
-        resourceUrl    = spCache.getResourceHost()+"/";
-        resourceType   = spCache.getResourceType();
-        resourcePrefix = spCache.getResourcePrefix();
-        mRealm = Realm.getDefaultInstance();
-        uploadType = mActivity.getClass().getSimpleName();
-        limitOperate = new HashMap<>();
-        uniqueTag =  this.fileKey+UUID.randomUUID().toString();
-    }
-
-    public void setCompress(Boolean isCompress) {
-        this.isCompress = isCompress;
-    }
-    public void setCompress(Boolean isCompress,int compressQuality,int minimumCompressSize) {
-        this.isCompress = isCompress;
-        this.compressQuality = compressQuality;
-        this.minimumCompressSize = minimumCompressSize;
-    }
-
-
-    public void setUploadType(String fileKey) {
-        this.fileKey = fileKey;
-    }
-
-    public void setPictureType(int pictureType){
-        this.pictureType = pictureType;
-    }
-
-    public void setOnlyCamera(boolean onlyCamera){
-        this.onlyCamera = onlyCamera;
-    }
-
-    public void  setMaxSelectNum(int num){
-        this.maxSelectNum = num;
-    }
-
-    public void  setNotifyParam( HashMap<String, Object> map){
-        this.notifyParam = map;
-    }
-
-    //操作限制
-    public void setLimitOperate(HashMap<String, Object> map){
-        this.limitOperate = map;
-    }
-
-    /**
-     * 设置操作类型
-     * @return
-     */
-    public String getUploadType() {
-       return fileKey;
-    }
-
-
-    public int getAwaitNum(){
-        RealmResults<AsyncUploadRealm> realmResults  = mRealm.where(AsyncUploadRealm.class)
-                .equalTo("isDelete",0)
-                .equalTo("pushStatus",0)
-                .equalTo("uploadType",uploadType)
-                .sort("pushStatus").findAll();
-        realmResults.load();
-        return  realmResults.size();
-    }
-
-    public List<LocalMedia> getSelectList (){
-        return  selectList;
-    }
-
-
-    public List<String> getOssPhotoList (){
-        return  ossPhotoList;
-    }
-
-
-
-    public void emptyRemake(){
-        selectList.clear();
-        ossPhotoList.clear();
-        adapter.clearData();
-        uniqueTag =  this.fileKey+UUID.randomUUID().toString();
-    }
-
-
-    //销毁
-    public void removeHandler(){
-        if (uploadHandler!=null){
-            uploadHandler.removeCallbacksAndMessages(null);
-        }
-    }
-
-    /**
-     * 获取选中图片
-     * @param data
-     */
-    public void getSelectImg (Intent data){
-        List<LocalMedia>  fileList = PictureSelector.obtainMultipleResult(data);
-        for (int i = 0; i < fileList.size(); i++) {
-            addUploadFile(fileList.get(i));
-            selectList.add(fileList.get(i));
-        }
-
-        adapter.setList(selectList);
-        adapter.notifyDataSetChanged();
-
-        //设置自动
-        if (isAutoUpload){
-            asyncUpload();
-        }
-
-    }
-
-    public String getUniqueTag(){
-        return  this.uniqueTag;
-    }
-
-
-
-    @SuppressLint("HandlerLeak")
-    private Handler uploadHandler = new Handler() {
-        @Override
-        public void handleMessage(Message msg) {
-            try {
-                //XLog.e(msg);
-                int current = (Integer) msg.arg1;
-                switch (msg.what){
-                    case 0:
-                        Toast.makeText(mActivity, "error", Toast.LENGTH_SHORT).show();
-                        break;
-                    case 1://失败
-
-                        if (awaitUploadList.size()>0){
-
-                            AsyncUploadRealm asyncUploadRealm = awaitUploadList.get(current);
-                            awaitUploadList.remove(current);
-                            resultUpload(asyncUploadRealm.getId(),0,"");
-                            String message = (String) msg.obj;
-                            if (!message.isEmpty() && mActivity!=null){
-                                Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
-                            }
-
-                        }
-
-                        break;
-                    case 2://成功
-
-                        //表示数据存在
-                        if (awaitUploadList.size()>0){
-                            AsyncUploadRealm asyncUploadRealm = awaitUploadList.get(current);
-                            awaitUploadList.remove(current);
-                            resultUpload(asyncUploadRealm.getId(),1,(String) msg.obj);
-                        }
-                        break;
-                    case 3:
-                        //设置进度条
-                        EventBus.getDefault().post(new UploadProgressEvent(msg.arg2));
-                        //progressDialog.show();
-                        return;
-                    case 4:
-                        //获取上传状态
-
-                        return;
-                    default:
-                        break;
-                }
-
-
-
-
-
-                // 通过接口对象传上传状态
-                if (uploadChangeListener!=null){
-                    uploadChangeListener.uploadResult(true,fileKey);
-                }
-
-            } catch (Exception e) {
-                XLog.e(e.getMessage());
-                e.printStackTrace();
-                // 通过接口对象传上传状态
-                if (uploadChangeListener!=null){
-                    uploadChangeListener.uploadResult(false,fileKey);
-                }
-
-            }
-        }
-    };
-
-
-
-    // 持有一个接口对象
-    UploadChangeListener uploadChangeListener;
-    // 状态变化监听
-    public interface UploadChangeListener {
-        // 回调方法 可以多个
-        void uploadResult(boolean State, String actionType);
-        void uploadFileKey(String actionType);
-    }
-    // 提供注册事件监听的方法
-    public void setOnChangeListener(UploadChangeListener uploadChangeListener) {
-        this.uploadChangeListener = uploadChangeListener;
-    }
-
-
-
-    // 调用回调方法
-    //uploadChangeListener.uploadResult(false);
-
-    public void filedUpload(int num){
-
-
-        // 例如 LocalMedia 里面返回三种path
-        // 1.media.getPath(); 为原图path
-        // 2.media.getCutPath();为裁剪后path,需判断media.isCut();是否为true
-        // 3.media.getCompressPath();为压缩后path,需判断media.isCompressed();是否为true
-        // 如果裁剪并压缩了,以取压缩路径为准,因为是先裁剪后压缩的
-        LocalMedia localMedia = awaitUploadList.get(num).getLocalMedia();
-        String urlPath =localMedia.getPath();
-        if (isCompress && localMedia.getCompressPath()!=null){
-            urlPath = localMedia.getCompressPath();
-        }
-
-        if (urlPath.isEmpty()){
-            Message msg = new Message();
-            msg.obj = "文件路径不存在";
-            msg.what = 1;
-            uploadHandler.sendMessage(msg);
-            return;
-        }
-
-
-        String fileName = "";
-        String path_prefix = "";
-
-        String ossUrl = awaitUploadList.get(num).getOssUrl();
-        if (!ossUrl.isEmpty()){
-            // 找到最后一个斜杠的位置
-            int lastSlashIndex = ossUrl.lastIndexOf('/');
-            // 如果找到了斜杠,则从斜杠之后的位置开始切割
-            fileName = ossUrl.substring(lastSlashIndex + 1);
-            path_prefix = ossUrl.substring(0,lastSlashIndex+ 1);
-
-        }else{
-            path_prefix = resourcePrefix+"/android/"+mPrefix+"/"+RxTimeTool.getYestoryDate("yyyyMMd")+"/";
-            String fileSuffix = urlPath.lastIndexOf(".")>-1 ? urlPath.substring(urlPath.lastIndexOf(".")) : "";
-            fileName = UUID.randomUUID().toString() + fileSuffix;
-        }
-
-
-        if (resourceType.equals("tencent")){
-            if (cosService==null){
-                cosService  = new CosService(mActivity.getBaseContext(),path_prefix);
-            }
-            //new cosThread(urlPath, fileName , num).start();
-            cosService.cosUpload(urlPath, fileName , num,uploadHandler);
-
-        }else{
-            if (ossService ==null){
-                ossService = new OssService(mActivity,path_prefix);
-
-            }
-
-
-            ossService.ossUpload(urlPath, fileName , num,uploadHandler);
-            //new ossThread(urlPath, fileName , num).start();
-        }
-        // task.cancel(); // 可以取消任务
-        // task.waitUntilFinished(); // 可以等待直到任务完成
-
-        EventBus.getDefault().post(new UploadProgressEvent(0));
-    }
-
-
-    private void initAdapter() {
-        FullyGridLayoutManager manager = new FullyGridLayoutManager(mActivity, 3, GridLayoutManager.VERTICAL, false);
-        mRecyclerView.setLayoutManager(manager);
-        adapter = new GridImageAdapter(mActivity,mActivity, onAddPicClickListener,pictureType);
-        adapter.setList(selectList);
-        adapter.setSelectMax(maxSelectNum);
-        mRecyclerView.setAdapter(adapter);
-        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
-            @Override
-            public void onItemClick(int position, View v) {
-                if (selectList.size() > 0) {
-                    LocalMedia media = selectList.get(position);
-                    String pictureType = media.getPictureType();
-                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
-                    switch (mediaType) {
-                        case 1:
-                            // 预览图片 可自定长按保存路径
-                            //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
-                            PictureSelector.create(mActivity).externalPicturePreview(position, selectList);
-                            break;
-                        case 2:
-                            // 预览视频
-                            PictureSelector.create(mActivity).externalPictureVideo(media.getPath());
-                            break;
-                        case 3:
-                            // 预览音频
-                            PictureSelector.create(mActivity).externalPictureAudio(media.getPath());
-                            break;
-                    }
-                }
-            }
-        });
-
-        //回调语音
-        adapter.setOnAudioListener(new GridImageAdapter.OnAudioListener() {
-            @Override
-            public void onSaveResult(Intent data) {
-                getSelectImg(data);
-            }
-        });
-    }
-
-
-
-    public GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
-
-        @SuppressLint("CheckResult")
-        @Override
-        public void onAddPicClick() {
-            //获取写的权限
-            RxPermissions rxPermission = new RxPermissions(mActivity);
-            rxPermission.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
-                    .subscribe(new Consumer<Permission>() {
-                        @Override
-                        public void accept(Permission permission) {
-                            if (permission.granted) {// 用户已经同意该权限
-                                //第一种方式,弹出选择和拍照的dialog
-
-                                if (limitOperate.containsKey("disabled")){
-                                    String message = "暂时无法拍照";
-
-                                    if(limitOperate.containsKey("error")){
-                                        message = limitOperate.get("error").toString();
-                                    }
-                                    if ( mActivity!=null){
-                                        Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
-                                    }
-                                    return;
-                                }
-
-                                if (pictureType==PictureConfig.TYPE_AUDIO){
-                                    authAudio();
-                                }else {
-                                    if (onlyCamera){
-                                        //第二种方式,直接进入相册,但是 是有拍照得按钮的
-                                        authCamera();
-                                    }else{
-                                        showPop();
-                                    }
-                                }
-
-
-
-                            } else {
-                                Toast.makeText(mContext, "拒绝", Toast.LENGTH_SHORT).show();
-                            }
-                        }
-                    });
-            //监听返回当前某个上传类型
-            if (uploadChangeListener!=null){
-                uploadChangeListener.uploadFileKey(fileKey);
-            }
-        }
-    };
-
-    private void showAlbum() {
-        //参数很多,根据需要添加
-        PictureSelector.create(mActivity)
-                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
-                .maxSelectNum(maxSelectNum)// 最大图片选择数量
-                .minSelectNum(1)// 最小选择数量
-                .imageSpanCount(4)// 每行显示个数
-                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选PictureConfig.MULTIPLE : PictureConfig.SINGLE
-                .previewImage(true)// 是否可预览图片
-                .isCamera(true)// 是否显示拍照按钮
-                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
-                //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
-                .enableCrop(true)// 是否裁剪
-                .compress(true)// 是否压缩
-                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
-                .glideOverride(160, 160)// glide 加载宽高,越小图片列表越流畅,但会影响列表图片浏览的清晰度
-                .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
-                //.selectionMedia(selectList)// 是否传入已选图片
-                //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
-                //.cropCompressQuality(90)// 裁剪压缩质量 默认100
-                //.compressMaxKB()//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
-                //.compressWH() // 压缩宽高比 compressGrade()为Luban.CUSTOM_GEAR有效
-                //.cropWH()// 裁剪宽高比,设置如果大于图片本身宽高则无效
-                .rotateEnabled(false) // 裁剪是否可旋转图片
-                //.scaleEnabled()// 裁剪是否可放大缩小图片
-                //.recordVideoSecond()//录制视频秒数 默认60s
-                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
-    }
-
-    private void showPop() {
-        View bottomView = View.inflate(mContext, R.layout.layout_bottom_dialog, null);
-        TextView mAlbum = bottomView.findViewById(R.id.tv_album);
-        TextView mCamera = bottomView.findViewById(R.id.tv_camera);
-        TextView mCancel = bottomView.findViewById(R.id.tv_cancel);
-
-        pop = new PopupWindow(bottomView, -1, -2);
-        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
-        pop.setOutsideTouchable(true);
-        pop.setFocusable(true);
-        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
-        lp.alpha = 0.5f;
-        mActivity.getWindow().setAttributes(lp);
-        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
-
-            @Override
-            public void onDismiss() {
-                WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
-                lp.alpha = 1f;
-                mActivity.getWindow().setAttributes(lp);
-            }
-        });
-        pop.setAnimationStyle(R.style.main_menu_photo_anim);
-        pop.showAtLocation(mActivity.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
-
-        View.OnClickListener clickListener = new View.OnClickListener() {
-            @Override
-            public void onClick(View view) {
-                switch (view.getId()) {
-                    case R.id.tv_album:
-                        //相册
-                        PictureSelector.create(mActivity)
-                                .openGallery(PictureMimeType.ofImage())
-                                .maxSelectNum(maxSelectNum)
-                                .minSelectNum(1)
-                                .imageSpanCount(4)
-                                .selectionMode(PictureConfig.MULTIPLE)
-                                .compress(isCompress) // 压缩
-                                .cropCompressQuality(compressQuality)// 裁剪压缩质量 默认100
-                                .minimumCompressSize(minimumCompressSize) //最新压缩图片
-
-                                .forResult(PictureConfig.CHOOSE_REQUEST);
-                        break;
-                    case R.id.tv_camera:
-                        //拍照
-                        PictureSelector.create(mActivity)
-                                .openCamera(PictureMimeType.ofImage())
-                                //只需要拍照
-                                //.selectionMode(PictureConfig.SINGLE)
-                                //.isCamera(true)
-                                .compress(isCompress) // 压缩
-                                .cropCompressQuality(compressQuality)// 裁剪压缩质量 默认100
-                                .minimumCompressSize(minimumCompressSize) //最新压缩图片
-                                .forResult(PictureConfig.CHOOSE_REQUEST);
-
-                        break;
-                    case R.id.tv_cancel:
-                        //取消
-                        //closePopupWindow();
-
-                        break;
-                }
-                closePopupWindow();
-            }
-        };
-
-        mAlbum.setOnClickListener(clickListener);
-        mCamera.setOnClickListener(clickListener);
-        mCancel.setOnClickListener(clickListener);
-
-
-    }
-
-    /**
-     * 外部直接调取拍照接口
-     */
-    public void authCamera(){
-        //拍照
-        PictureSelector.create(mActivity)
-                .openCamera(PictureMimeType.ofImage())
-                //只需要拍照
-                //.selectionMode(PictureConfig.SINGLE)
-                //.isCamera(true)
-                //.compressMaxKB()//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
-                .compress(isCompress) // 压缩
-                .cropCompressQuality(compressQuality)// 裁剪压缩质量 默认100
-                .minimumCompressSize(minimumCompressSize) //最新压缩图片
-                .forResult(PictureConfig.CHOOSE_REQUEST);
-
-        //监听返回当前某个上传类型
-        if (uploadChangeListener!=null){
-            uploadChangeListener.uploadFileKey(fileKey);
-        }
-    }
-
-    /**
-     * 自动打开录音
-     */
-    public void authAudio(){
-        // 自带音频
-        PictureSelector.create(mActivity)
-                .openCamera(PictureMimeType.ofAudio())
-                //只需要音频
-                .selectionMode(PictureConfig.TYPE_AUDIO)
-                .compress(isCompress) // 压缩
-                .forResult(PictureConfig.CHOOSE_REQUEST);
-
-
-
-        //监听返回当前某个上传类型
-        if (uploadChangeListener!=null){
-            uploadChangeListener.uploadFileKey(fileKey);
-        }
-    }
-
-
-    /**
-     * 关闭弹窗
-     */
-    public void closePopupWindow() {
-        if (pop != null && pop.isShowing()) {
-            pop.dismiss();
-            pop = null;
-        }
-    }
-
-
-
-
-
-
-    //存储数据问题
-    private void asyncUpload(){
-
-        if (!getIsNetwork()){
-            //无网络时在请求检查是否有网络
-            return;
-        }
-
-        if (awaitUploadList==null || awaitUploadList.size()==0){
-            RealmResults<AsyncUploadRealm> realmResults  = mRealm.where(AsyncUploadRealm.class)
-                    .equalTo("isDelete",0)
-                    .equalTo("pushStatus",0)
-//                    .equalTo("notifyKey",fileKey)
-                    .equalTo("uploadType",uploadType)
-                    .sort("pushStatus").findAll();
-            realmResults.load();
-            awaitUploadList.addAll(realmResults);
-
-        }
-
-        if (awaitUploadList.size()>0){
-            filedUpload(0);
-        }
-    }
-
-    //取消任务
-    public void taskCancel(){
-
-    }
-
-    public void setStartUpload(){
-        allowUpload = true;
-        asyncUpload();
-    }
-
-    public void setStopUpload(){
-        if(ossService !=null){
-            ossService.taskCancel();
-        }
-        allowUpload = false;
-        EventBus.getDefault().post(new UploadProgressEvent(0));
-    }
-
-    private void addUploadFile(LocalMedia localMedia){
-        String realmId = UUID.randomUUID().toString();
-        String scan_date = DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS);
-        //同步操作写法一:
-        mRealm.beginTransaction();
-        //会创建对象和user表
-        AsyncUploadRealm takePhotosRealm = mRealm.createObject(AsyncUploadRealm.class,realmId);
-        Gson gson = new Gson();
-        String localMediaStr = gson.toJson(localMedia);
-        takePhotosRealm.setLocalMediaStr(localMediaStr);
-        takePhotosRealm.setOssUrl("");
-        takePhotosRealm.setScanDate(scan_date);
-        takePhotosRealm.setUploadType(uploadType);
-        takePhotosRealm.setNotifyKey(fileKey);
-        takePhotosRealm.setNotifyParam(gson.toJson(notifyParam));
-        takePhotosRealm.setNotifyUrl(notifyUrl);
-        takePhotosRealm.setUniqueTag(uniqueTag);
-
-
-        String path_prefix = resourcePrefix+"/android/"+mPrefix+"/"+RxTimeTool.getYestoryDate("yyyyMMd")+"/";
-        String urlPath = isCompress && localMedia.getCompressPath()!=null ? localMedia.getCompressPath() :  localMedia.getPath();
-        String fileSuffix = urlPath.lastIndexOf(".")>-1 ? urlPath.substring(urlPath.lastIndexOf(".")) : "";
-        String fileName = UUID.randomUUID().toString() + fileSuffix;
-        takePhotosRealm.setOssUrl(path_prefix+fileName);
-        ossPhotoList.add("/"+path_prefix+fileName);
-        //
-
-        Date date = new Date();
-        takePhotosRealm.setCreateTime(date.getTime());
-        takePhotosRealm.setPushStatus(0);
-        //提交事务,操作就被执行
-        mRealm.commitTransaction();
-    }
-
-    /**
-     * 设置是否完成
-     * @param realmId
-     * @param isFinish
-     */
-    private void setIsFinish(String realmId,Integer isFinish){
-        //更新值
-        mRealm.beginTransaction();
-        AsyncUploadRealm myObject = mRealm.where(AsyncUploadRealm.class).equalTo("id",realmId).findFirst();
-        myObject.setIsFinish(isFinish);
-        mRealm.commitTransaction();
-    }
-
-
-
-    /**
-     * 上传结果
-     * @param tmpRealmId String
-     * @param status Integer
-     * @param photoPath String
-     */
-    private void resultUpload(String tmpRealmId,Integer status,String photoPath){
-        if (tmpRealmId!=null && !tmpRealmId.isEmpty()){
-            int rePush = 0;
-            //遍历删除
-            if (awaitUploadList.size()>0){
-                for (int i=0;i<awaitUploadList.size();i++){
-                    if (awaitUploadList.get(i).getId().equals(tmpRealmId)){
-                        rePush = awaitUploadList.get(i).getRePush();
-                        awaitUploadList.remove(i);
-                        break;
-                    }
-                }
-            }
-
-            int pushStatus = 2;
-            if (status==0){
-                pushStatus = rePush>4 ? 1 : 0;
-            }
-            //更新值
-            mRealm.beginTransaction();
-            AsyncUploadRealm myObject = mRealm.where(AsyncUploadRealm.class).equalTo("id",tmpRealmId).findFirst();
-            assert myObject != null;
-            myObject.setPushStatus(pushStatus);
-            if (pushStatus == 1){
-                myObject.setIsFinish(pushStatus);
-            }
-            myObject.setOssUrl(photoPath);
-            if (getIsNetwork() && status==0 ){
-                myObject.setRePush(myObject.getRePush()+1);
-            }
-            mRealm.commitTransaction();
-
-        }
-
-        //可以允许上传
-        if (allowUpload){
-            //上传完,继续执行
-            asyncUpload();
-        }
-
-    }
-
-    //异步通知结果
-    private void  asyncNotify(AsyncUploadRealm myObject){
-        try {
-            JSONObject jsonObject = new JSONObject(myObject.getNotifyParam());
-            jsonObject.put(myObject.getNotifyKey(),myObject.getOssUrl());
-            jsonObject.put("realm_id",myObject.getId());
-            jsonObject.put("unique_tag",myObject.getUniqueTag());
-            final String tmpRealmId1 = myObject.getId();
-            OkGo.<String>post(myObject.getNotifyUrl()).upJson(jsonObject)
-                    .execute(new MyDialogCallback(mContext, true, false) {
-                        @Override
-                        public void onSuccess(Response<String> response) {
-                            super.onSuccess(response);
-                            try {
-                                ActionBean bean = JsonUtil.getObject(response.body(), ActionBean.class);
-                                if(bean.code == 1){
-                                    setIsFinish(tmpRealmId1,1);
-                                }
-                            } catch (Exception e) {
-                                e.printStackTrace();
-                                XLog.e("回传图片地址错误",e.getMessage());
-                                setIsFinish(tmpRealmId1,2);
-                            }
-                        }
-                    });
-        } catch (Exception e) {
-            e.printStackTrace();
-            XLog.e("异步通知"+e.getMessage());
-
-        }
-    }
-
-    /**
-     * 获取当前网络
-     * @return Boolean
-     */
-    private Boolean getIsNetwork(){
-        boolean isNetwork = false;
-
-        try {
-            if (mActivity==null){
-                return  isNetwork;
-            }
-
-            ConnectivityManager connectivityManager = (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
-            if (connectivityManager == null) {
-                XLog.d( "无法获取ConnectivityManager实例");
-                return  isNetwork;
-            }
-            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
-            if (networkInfo != null) {
-                XLog.d( "当前网络状态:" + networkInfo.getState());
-                isNetwork = true;
-            } else {
-                XLog.d( "当前无网络连接");
-                isNetwork = false;
-            }
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-
-        return  isNetwork;
-    }
-
-
-}

+ 5 - 0
app/src/main/java/com/fxy/common/CosService.java

@@ -91,6 +91,11 @@ public class CosService {
     public void cosUpload(String filePath, String uploadName , int num, Handler handler){
         new CosThread(filePath, uploadName , num,handler).start();
     }
+
+    public void cosUpload(String filePath, String uploadName , int num, Handler handler,String uploadPath){
+        path_prefix = uploadPath;
+        cosUpload(filePath,uploadName,num,handler);
+    }
     //取消上传
     public void taskCancel(){
         if (cosxmlUploadTask!=null){

+ 16 - 8
app/src/main/java/com/fxy/common/OssService.java

@@ -157,6 +157,11 @@ public class OssService {
         // task.waitUntilFinished(); // 可以等待直到任务完成
     }
 
+    public void ossUpload(String filePath, String uploadName , int num, Handler handler,String uploadPath){
+        this.filePath = uploadPath;
+        ossUpload(filePath,uploadName,num,handler);
+    }
+
     //取消上传
     public void taskCancel(){
         if (taskId!=null && !taskId.isCanceled()){
@@ -191,7 +196,7 @@ public class OssService {
 //                }
 //            });
 
-            //XLog.e("开始执行上传"+objectKey+"上传的目录是:"+urlPath);
+            XLog.e("开始执行上传"+getFilePath()+objectKey+"上传的目录是:"+urlPath);
 
             // 设置进度回调
             put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
@@ -231,24 +236,27 @@ public class OssService {
                     Message msg = new Message();
                     msg.what = 1;
                     msg.arg1 = current;
+
+                    XLog.e("上传失败,本地文件"+request.getUploadFilePath()+"上传目录"+request.getObjectKey());
+
                     if (clientExcepion != null) {
                         // 本地异常,如网络异常等。
                         msg.obj = "网络异常,请稍后...";
                         msg.arg2 = 1;
                         uploadHandler.sendMessage(msg);
                         XLog.e("RawMessage", clientExcepion.getMessage());
+
                     }
                     if (serviceException != null) {
                         msg.obj = "服务异常,请稍后...";
                         msg.arg2 = 2;
                         uploadHandler.sendMessage(msg);
-                        if (BuildConfig.DEBUG){
-                            // 服务异常。
-                            XLog.e("ErrorCode", serviceException.getErrorCode());
-                            XLog.e("RequestId", serviceException.getRequestId());
-                            XLog.e("HostId", serviceException.getHostId());
-                            XLog.e("RawMessage", serviceException.getRawMessage());
-                        }
+
+                        // 服务异常。
+                        XLog.e("ErrorCode", serviceException.getErrorCode());
+                        XLog.e("RequestId", serviceException.getRequestId());
+                        XLog.e("HostId", serviceException.getHostId());
+                        XLog.e("RawMessage", serviceException.getRawMessage());
                     }
                 }
             });

+ 3 - 1
app/src/main/java/com/fxy/common/UploadDialog.java

@@ -117,7 +117,9 @@ public class UploadDialog {
     public interface OnEventCallback {
         void onUploadStatus(String message);
     }
-
+    public void setDebug(boolean debug) {
+        asyncPictureUpload.setDebug(true);
+    }
 
 }
 

+ 66 - 2
app/src/main/java/com/fxy/main/fragment/MineFragment.java

@@ -24,6 +24,7 @@ import com.fxy.baselibrary.bean.BaseEventBusBean;
 import com.fxy.common.AsyncPictureUpload;
 import com.fxy.common.UploadDialog;
 import com.fxy.constant.EventCode;
+import com.fxy.utils.CompressUtil;
 import com.fxy.utils.JobUtils;
 import com.lzy.okgo.OkGo;
 import com.lzy.okgo.model.Response;
@@ -63,6 +64,9 @@ import org.greenrobot.eventbus.ThreadMode;
 import org.json.JSONObject;
 
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -74,6 +78,8 @@ import butterknife.BindView;
 import butterknife.ButterKnife;
 import butterknife.OnClick;
 import butterknife.Unbinder;
+import io.realm.Realm;
+import io.realm.RealmConfiguration;
 
 /**
  * 首页个人中心页
@@ -241,7 +247,7 @@ public class MineFragment extends BaseFragment {
 
     @OnClick({R.id.iv_avatar,R.id.rl_account_feedback,R.id.rl_blue_setting,R.id.rl_scan_setting,R.id.rl_account_wipeCache,
             R.id.rl_account_versionUpdate,R.id.rl_language_change, R.id.tv_exit,R.id.rl_electronic_scale,R.id.rl_upload_files,
-            R.id.rl_picture_selector,R.id.rl_upload_async_files})
+            R.id.rl_picture_selector,R.id.rl_upload_async_files,R.id.rl_upload_realm_files})
     public void onViewClicked(View view) {
         switch (view.getId()) {
             case R.id.iv_avatar:
@@ -326,14 +332,72 @@ public class MineFragment extends BaseFragment {
                 if (total>0){
                     uploadDialog.pictureStartUpload();
                 }else{
-                    showToast("已全部上传");
+
+                    uploadDialog.setDebug(true);
+                    uploadDialog.pictureStartUpload();
+
+                    //showToast("已全部上传");
                 }
 
 
+                break;
+            case R.id.rl_upload_realm_files:
+                backupRealmDatabase(getContext(),"backup.realm");
                 break;
         }
     }
 
+
+    public   void backupRealmDatabase(Context context, String backupFileName) {
+
+        // 获取Realm数据库文件路径
+        Realm realm = Realm.getDefaultInstance();
+        String realmPath = realm.getPath();
+        realm.close();
+
+
+        File backupFileOld = new File(context.getFilesDir(), backupFileName);
+
+        if (backupFileOld.exists()) { // 判断是否存在
+            backupFileOld.delete();
+        }
+
+
+        // 目标备份文件路径
+        File backupFile = new File(context.getFilesDir(), backupFileName);
+
+        try {
+            // 复制文件
+            FileInputStream inStream = new FileInputStream(new File(realmPath));
+            FileOutputStream outStream = new FileOutputStream(backupFile);
+
+            byte[] buffer = new byte[1024];
+            int length;
+
+            while ((length = inStream.read(buffer)) > 0) {
+                outStream.write(buffer, 0, length);
+            }
+
+            inStream.close();
+            outStream.close();
+
+            XLog.i( "Realm database backed up successfully.");
+
+        } catch (IOException e) {
+            XLog.e("Error backing up Realm database.", e);
+
+        }
+
+
+        SPCache sp = SPCache.getInstance(getActivity());
+        String newsFileName = RxTimeTool.getYestoryDate("MMddHHmmss")+"-"+sp.getUserName()+backupFileName;
+        String path_prefix = sp.getResourcePrefix()+"/android/realm/"+ RxTimeTool.getYestoryDate("yyyyMMdd")+"/";
+
+        FiledUpload filedUpload = new FiledUpload(getActivity(),"");
+        filedUpload.filedUpload(backupFile.toString(),path_prefix+newsFileName);
+
+    }
+
     //删除文件日志
     private void deleteLogFiles() {
         String fileName = RxTimeTool.simpleDateFormat("yyyy-MM-dd",RxTimeTool.getCurTimeDate());

+ 40 - 0
app/src/main/java/com/fxy/utils/CompressUtil.java

@@ -0,0 +1,40 @@
+package com.fxy.utils;
+import android.util.Log;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+public class CompressUtil {
+
+    private static final String TAG = "CompressUtil";
+
+    public static void compressFile(File sourceFile, File targetFile) {
+        try {
+            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(targetFile));
+            FileInputStream fileInput = new FileInputStream(sourceFile);
+
+            ZipEntry zipEntry = new ZipEntry(sourceFile.getName());
+            zipOut.putNextEntry(zipEntry);
+
+            byte[] bytes = new byte[1024];
+            int length;
+
+            while ((length = fileInput.read(bytes)) >= 0) {
+                zipOut.write(bytes, 0, length);
+            }
+
+            zipOut.closeEntry();
+            fileInput.close();
+            zipOut.close();
+
+            Log.i(TAG, "File compressed successfully.");
+
+        } catch (IOException e) {
+            Log.e(TAG, "Error compressing file.", e);
+        }
+    }
+}

+ 17 - 0
app/src/main/res/layout/fragment_homemine.xml

@@ -238,9 +238,26 @@
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:src="@drawable/ic_right_arrow_gray" />
+            </LinearLayout>
 
+            <LinearLayout
+                android:id="@+id/rl_upload_realm_files"
+                android:layout_width="match_parent"
+                android:layout_height="55dp"
+                android:layout_marginLeft="15dp"
+                android:layout_marginRight="15dp"
+                android:gravity="center_vertical"
+                android:orientation="horizontal">
 
+                <TextView
+                    style="@style/tvPersonalStyle"
+                    android:drawableLeft="@drawable/ic_upload"
+                    android:text="上传数据" />
 
+                <ImageView
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:src="@drawable/ic_right_arrow_gray" />
             </LinearLayout>
 
             <LinearLayout

+ 1 - 1
config.gradle

@@ -8,7 +8,7 @@ ext {
             minSdkVersion    : 21,
             targetSdkVersion : 23,
             versionCode      : 1,
-            versionName      : "2.9.8",
+            versionName      : "2.9.9",
             versionApi       : "2.9",
             versionRealm     : 2,
     ]