package com.xypower.mpmaster.sms;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadFileTask extends AsyncTask <String, Integer, String> {

    private Context mContext;

    public DownloadFileTask(Context context) {
        mContext = context;
    }

    @Override
    protected String doInBackground(String... params) {
        String fileUrl = params[0];
        String fileName = params[1];
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // 获取文件大小
            int fileLength = connection.getContentLength();

            // 创建输入流
            InputStream input = new BufferedInputStream(url.openStream());

            // 创建输出流
            OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + fileName);

            byte[] data = new byte[1024];
            int total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                // 发布进度信息
                publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }

            // 关闭流
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
            return "下载失败";
        }
        return "下载成功";
    }

    @Override
    protected void onPostExecute(String result) {




//        Toast.makeText(mContext, result, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        // 更新下载进度
//        Log.d("Download progress", progress[0] + "%");
    }
}
