import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
 * Created by haichuanzheng on 19-3-14.
 */

public class DeviceLogImpl implements DeviceLog {
    private static final String TAG = "XXX.XXLogImpl";
    private static final boolean DEBUG = true;
    private static final String copyDone="/sdcard/copydone";
    private static final String zipDone="/sdcard/zipdone";
    private final int SEND_FILENAME=1001;
    private String fileName;
    private IRequestCallback callBackSelf;
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case SEND_FILENAME:
                    String[] zipFileName={msg.obj.toString()};
                    Log.i(TAG, "handleMessage: "+msg.obj.toString());
                    callBackSelf.onLogUploadFilesReady(zipFileName);
                    break;
            }
        }
    };
    @Override
    public String[] getLogRootFolders() {
        return new String[0];
    }

    @Override
    public String[] getLogRootFolders(int type) {
        return new String[0];
    }

    @Override
    public void setLogcatLogLevel(int[] level) {

    }

    @Override
    public void requestLogUpload(IRequestCallback callback) {
        if(DEBUG){
            Log.i(TAG, "requestLogUpload:");
        }
        callBackSelf=callback;
        new Thread() {
            @Override
            public void run() {
                File copyFirst=new File(copyDone);
                if(copyFirst.exists()){
                    copyFirst.delete();
                }
                doCopy();
                while(true) {
                    File copySecond=new File(copyDone);
                    if(copySecond.exists()) {
                        try {
                            sleep(3 * 1000);// 强制等3秒,防止未copy完成。
                        } catch (Exception e2) {
                            // TODO: handle exception
                            return;
                        }
                        File zipFirst=new File(zipDone);
                        if(zipFirst.exists()){
                            zipFirst.delete();
                        }
                        fileName = doZip();
                        try {
                            sleep(3000);// 强制等3秒,防止未zip完成。
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                      //  String[] fN = {fileName};
                       // callback.onLogUploadFilesReady(fN);
                        while (true) {
                            File zipSecond=new File(zipDone);
                            if(zipSecond.exists()) {
                                Log.i(TAG, "zip file done");
                                Message message = mHandler.obtainMessage();
                                message.what = SEND_FILENAME;
                                message.obj = fileName;
                                mHandler.sendMessage(message);
                                break;
                            }
                        }
                        break;
                    }
                }
            }
        }.start();

    }

    @Override
    public void requestLogUpload(int[] types, IRequestCallback callback) {

    }

    @Override
    public void requestLogUpload(int[] types, long startTime, IRequestCallback callback) {

    }

    @Override
    public void releaseRequestCallback() {

    }

    private void doCopy(){
        String[] path={"/data/log","/data/anr/","/data/system/dropbox","/sdcard/test","/sdcard/a.txt"};
        if(DEBUG){
            Log.i(TAG, "doCopy: doCopy");
        }
        for(int i=0;i             File file=new File(path[i]);
            if(!file.exists()){
                continue;
            }else {
                if(file.isFile()){
                    if (DEBUG) {
                        Log.e(TAG,":doCopy:"+"当前文件是"+file.getAbsolutePath());
                    }
                    copyFile(path[i],"/sdcard/LOGS");
                }else {
                    if (DEBUG) {
                        Log.e(TAG, ":doCopy:" + "当前目录是" + file.getAbsolutePath());
                    }
                    copyFolder(path[i],"/sdcard/LOGS");
                }
            }
        }
        File done=new File(copyDone);
        try {
            if(done.createNewFile()){
                Log.i(TAG, ":done.createNewFile() success");
            }else {
                Log.i(TAG, ":done.createNewFile() failure");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    private void copyFile(String src, String dst) {
        try {
            new File(dst+new File(src).getParent()).mkdirs();
            FileChannel inChannel = new FileInputStream(src).getChannel();
            FileChannel outChannel = new FileOutputStream(dst+File.separator+new File(src).getParent()+File.separator+new File(src).getName()).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
            inChannel.close();
            outChannel.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void copyFolder(String src, String dst) {
        try {
            (new File(dst+src)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a=new File(src);
            String[] file=a.list();
            File temp=null;
            for (int i = 0; i < file.length; i++) {
                //GLog.e(TAG,"File.name="+file.toString());
                if(src.endsWith(File.separator)){
                    temp=new File(src+file[i]);
                }
                else{
                    temp=new File(src+File.separator+file[i]);
                }
                if(temp.isFile()){
                    try {
                        FileChannel inChannel = new FileInputStream(temp).getChannel();
                        FileChannel outChannel = new FileOutputStream(dst+File.separator+temp.getParent()+File.separator+ (temp.getName()).toString()).getChannel();
                        inChannel.transferTo(0, inChannel.size(), outChannel);
                        inChannel.close();
                        outChannel.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                if(temp.isDirectory()){//如果是子文件夹
                    copyFolder(src+File.separator+file[i],dst);
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    private String  doZip(){
        String src="/sdcard/IHU";
        String dst="/sdcard/IHUID"+new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(System.currentTimeMillis())+".zip";
        try {
            ZipFolder(src, dst);
        }catch (Exception e){
            e.printStackTrace();
        }
        return dst;
    }
    private void ZipFiles(String src, String fileName, ZipOutputStream zipOutputSteam)throws Exception{
        if(zipOutputSteam == null){
            Log.e(TAG,":ZipFiles:"+"创建zipOutputSteam失败");
            return;
        }
        File file = new File(src+fileName);
        if (file.isFile()) {
            ZipEntry zipEntry = new ZipEntry(fileName);
            FileInputStream inputStream = new FileInputStream(file);
            zipOutputSteam.putNextEntry(zipEntry);
            int len;
            byte[] buffer = new byte[4096];
            while((len=inputStream.read(buffer)) != -1) {
                zipOutputSteam.write(buffer, 0, len);
            }
            zipOutputSteam.closeEntry();
        }else {
            //文件夹
            String fileList[] = file.list();
            //没有子文件和压缩
            if (fileList.length <= 0) {
                ZipEntry zipEntry = new ZipEntry(fileName+File.separator);
                zipOutputSteam.putNextEntry(zipEntry);
                zipOutputSteam.closeEntry();
            }
            //子文件和递归
            for (int i = 0; i < fileList.length; i++) {
                ZipFiles(src, fileName+ File.separator+fileList[i], zipOutputSteam);
            }
        }
    }
    private void ZipFolder(String src,String dst){
        try {
            ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(dst));
            //创建文件 File
            File file = new File(src);
            //压缩
            ZipFiles(file.getParent() + File.separator, file.getName(), outZip);
            //完成和关闭
            outZip.finish();
            outZip.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        File done=new File(zipDone);
        try {
            done.createNewFile();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

更多相关文章

  1. NPM 和webpack 的基础使用
  2. 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
  3. Android文件读写简单示例
  4. android:parentActivityName
  5. Android利用SQLite制作最简单成语小词典
  6. android获取图片文件头信息
  7. android 控件绘制完成的监听
  8. Android创建文件夹及文件并写入数据
  9. Android读写文件示例

随机推荐

  1. Android(安卓)EditText/TextView使用Span
  2. android 开发之旅
  3. 为什么Android官方废弃SoftRefrerence软
  4. Android中添加思源字体/NotoSansCJK/Sour
  5. 高手速成android开源项目【tool篇】
  6. mono for android 的ADB
  7. Android使用FrameLayout应该注意的地方
  8. Android简明开发教程二十三:发布应用
  9. Android(安卓)嵌套滑动机制(NestedScrolli
  10. Android(安卓)多媒体应用——MediaPlayer