asynctask下载文件 保存到本地

下载文件 保存到本地

状态栏提示

package com.polyguide.Kindergarten.util;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.RemoteViews;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.polyguide.Kindergarten.R;
import com.polyguide.Kindergarten.activity.BaseActivity;
import com.polyguide.Kindergarten.network.HttpClientEntity;
import com.polyguide.Kindergarten.preferences.Preferences;
import org.apache.http.Header;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownLoadUtil {


    private static final String TAG = "DownLoadUtil";
    private Context context;
    private NotificationManager manager = null;
    private Notification notification = null;
    private int notification_id = 10093;
    private int total = 100;
    private int written = 0;
    private String downloadUrl = "";
    private FileUtils fileUtils;
    private String downloadingStr;
    private int flag = 0;

    public String fileName = "kindergarten.apk";//apk名称
    public String oldFileName = "kindergarten.apk";//apk名称
    public static DownLoadUtil instance;
    //执行asynctask
    private DownloadFileAsync downloadFileAsync;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    //synsDownload();
                    downloadFileAsync.execute();
                    break;
                case 1:
                    Utils.showLog(TAG, "更新");
                    updateProgress();
                    break;
                case 2:
                    Utils.showLog(TAG, "取消");
                    downloadFileAsync.cancel(true);
                    manager.cancel(notification_id);
                    break;
            }
        }
    };

    public static DownLoadUtil getInstance() {
        if (null == instance) {
            instance = new DownLoadUtil();
        }
        return instance;

    }


    public void Download(Context context, String downloadUrl, String fileName) {
        this.context = context;
        this.downloadUrl = downloadUrl;
        this.fileName = fileName;

        fileUtils = new FileUtils(context, 1);
        downloadingStr = context.getString(R.string.mst_progress_downloading);
        initNotification();
        downloadFileAsync = new DownloadFileAsync();
        Utils.showLog(TAG, "下载");

        handler.sendEmptyMessage(0);
    }

    public boolean isDownLoading() {
        if (null != downloadFileAsync) {
            boolean cancelled = downloadFileAsync.isCancelled();
            Utils.showLog(TAG, "正在下载 downloadFileAsync = " + downloadFileAsync);
            Utils.showLog(TAG, "判断是否正在下载 downloadFileAsync.isCancelled() = " + !cancelled);
            return !cancelled;
        }
        return false;
    }


    private void initNotification() {
        Utils.showLog(TAG, "初始化通知栏");

        if (manager == null) {

            manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        }
        if (notification == null) {

            notification = new Notification();
        }

        int icon = android.R.drawable.stat_sys_download;
        notification.icon = icon;
        notification.flags = Notification.FLAG_ONGOING_EVENT;
        notification.when = System.currentTimeMillis();
        notification.tickerText = context.getString(R.string.mst_update_title);
        notification.contentView = new RemoteViews(context.getPackageName(), R.layout.download_notification);
        notification.contentView.setProgressBar(R.id.probar, total, 0, false);
        Intent intent = new Intent(context, BaseActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
        notification.contentIntent = contentIntent;
        Utils.showLog(TAG, "各个参数 = context=" + context);
        Utils.showLog(TAG, "各个参数 = manager=" + manager);
        Utils.showLog(TAG, "各个参数 = notification=" + notification);
        Utils.showLog(TAG, "各个参数 = notification.when=" + notification.when);
        Utils.showLog(TAG, "各个参数 = tickerText=" + notification.tickerText);
    }


    //下载进度通知
    private void updateProgress() {

// Utils.showLog(TAG, "下载进度 总的" + total);
// Utils.showLog(TAG, "下载进度 当前的==========" + written);
        if (total == written) {

            return;
        } else {
            StringBuffer strbuffer = new StringBuffer(downloadingStr);
            int rate = written * 100 / total;
            if (rate > flag) {
                flag = rate;
                String rateStr = String.valueOf(rate);
                strbuffer.append(" " + rateStr);
                strbuffer.append("%");
                notification.contentView.setProgressBar(R.id.probar, total, written, false);
                notification.contentView.setTextViewText(R.id.ProgressText, strbuffer.toString());
                manager.notify(notification_id, notification);
            }
        }
    }

    public void renameFile(String oldname, String newname) {
        if (!oldname.equals(newname)) {//新的文件名和以前文件名不同时,才有必要进行重命名
            File oldfile = new File(fileUtils.sd_card + "/" + oldname);
            File newfile = new File(fileUtils.sd_card + "/" + newname);
            if (!oldfile.exists()) {
                return;//重命名文件不存在
            }
            if (newfile.exists())
            //若在该目录下已经有一个文件和新文件名相同,则不允许重命名
            {
                Utils.showLog("已经存在!");
                oldfile.delete();
            } else {
                oldfile.renameTo(newfile);
            }
        } else {
            Utils.showLog("新文件名和旧文件名相同...");
        }
    }

    public void stopDownLoad() {
        Utils.showLog(TAG, "取消下载handler = ");
        downloadFileAsync.cancel(true);
        manager.cancel(notification_id);
    }

    /** * 下载 */
    class DownloadFileAsync extends AsyncTask<String, String, String> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }


        @Override
        protected String doInBackground(String... strings) {
            try {
                Utils.showLog(TAG, "正式下载 url[" + downloadUrl + "]");
                URL url = new URL(downloadUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                int fileSize = connection.getContentLength();
                Utils.showLog(TAG, "fileSize == " + fileSize);
                InputStream inputStream = connection.getInputStream();
                saveFileToSDCard(inputStream, fileSize);
                handler.sendEmptyMessage(2);
                if (total == written) {
                    renameFile(oldFileName, fileName);
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(Uri.fromFile(new File(fileUtils.sd_card + fileName)),
                            "application/vnd.android.package-archive");
                    context.startActivity(intent);
                    downloadFileAsync = null;
                }
            } catch (Exception e) {
                Utils.showLog(TAG, "有异常 " + e.toString());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {

            // total = Integer.parseInt(progress[0]);
            Utils.showLog(TAG, "onProgressUpdate progress" + values);
// written = Integer.parseInt(values[0]);
// handler.sendEmptyMessage(1);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(String s) {
            //不执行
            Utils.showLog(TAG, "返回数据 result" + s);
            if (null != s) {

            } else {
                stopDownLoad();
            }
            //handler.sendEmptyMessage(2);

            super.onPostExecute(s);
        }
    }

    private void saveFileToSDCard(InputStream inputStream, int fileSize) {
        String filePath = fileUtils.sd_card + oldFileName;

        int readFileLength = 0;
        OutputStream outputStream = null;
        File file = new File(filePath);

        try {
            file.createNewFile();
            outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[10 * 1024];
            int length = 0;
            while (-1 != (length = inputStream.read(buffer))) {
                outputStream.write(buffer, 0, length);
                readFileLength += length;

                written = readFileLength;
                total = fileSize;
                updateProgress();
            }
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

你可能感兴趣的:(android,下载)