基于xutils3的单文件下载

开篇都不知道要叨叨啥,唉~,直接进入正题——>go!!

界面就是一个button,就不贴了。

MainActivity 

package com.fun.downloaduploaddemo;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    private Button buttonDownloadFile;
    private DownLoadModel model = new DownLoadModel();
    private static final String BASE_PATH = Environment.getExternalStorageDirectory().getPath() + File.separator + "aqsc" + File.separator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttonDownloadFile = (Button) findViewById(R.id.bt_downloadFile);
        if (model.fileIsExists(BASE_PATH + "在三国杀怪升级当战神.txt")) {
            buttonDownloadFile.setText("文件已经下载");
        }
        buttonDownloadFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://txt.bookben.com/c_down/2018/03/139675/在三国杀怪升级当战神(书本网www.bookben.com).txt";
                if (model.fileIsExists(BASE_PATH + "在三国杀怪升级当战神.txt")) {
                    Toast.makeText(MainActivity.this, "文件已经存在,正在打开文件!", Toast.LENGTH_SHORT).show();
                    File file = new File(BASE_PATH + "在三国杀怪升级当战神.txt");
                    model.openFile(MainActivity.this, file);
                } else {
                    model = new DownLoadModel(MainActivity.this, url, "在三国杀怪升级当战神.txt");
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (model.fileIsExists(BASE_PATH + "在三国杀怪升级当战神.txt")) {
            buttonDownloadFile.setText("文件已经下载");
        } else {
            buttonDownloadFile.setText("文件下载");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        buttonDownloadFile.setText("文件已经下载");
    }
}

onResume方法中检查在下载目录中是否存在该文件,存在更改button的text为已经下载,下载完成后直接打开文件,Activity进入onPause方法,重写onPause方法更改button状态。

DownLoadModel 

package com.fun.downloaduploaddemo;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;


public class DownLoadModel {
    private Context context;
    private String url;
    private String fileName;

    private ProgressDialog progressDialog;

    private static final String BASE_PATH = Environment.getExternalStorageDirectory().getPath() + File.separator + "aqsc" + File.separator;

    public DownLoadModel(Context context, String url, String fileName) {
        this.context = context;
        this.url = url;
        this.fileName = fileName;
        verifyStoragePermissions((Activity) context);
        String path = BASE_PATH + fileName;
        downloadFile(url, path);
    }

    public DownLoadModel() {
    }

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    /**
     * 检查应用程序是否允许写入存储设备
     * 如果应用程序不允许那么会提示用户授予权限
     *
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);


        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

    private void downloadFile(final String url, final String path) {
        progressDialog = new ProgressDialog(context);
        RequestParams requestParams = new RequestParams(url);
        requestParams.setSaveFilePath(path);
        x.http().get(requestParams, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {
            }

            @Override
            public void onStarted() {
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.setMessage("亲,努力下载中。。。");
                progressDialog.show();
                progressDialog.setMax((int) total);
                progressDialog.setProgress((int) current);
            }

            @Override
            public void onSuccess(File result) {
                Toast.makeText(context, "下载成功", Toast.LENGTH_SHORT).show();
                Log.e("result", "result=" + result);
                progressDialog.dismiss();
                openFile(context, result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                Toast.makeText(context, "下载失败,请检查网络和SD卡", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    /**
     * 根据文件后缀名匹配MIMEType
     *
     * @param file
     * @return
     */
    private static String getMIMEType(File file) {
        String type = "*/*";
        String name = file.getName();
        int index = name.lastIndexOf('.');
        if (index < 0) {
            return type;
        }

        String end = name.substring(index, name.length()).toLowerCase();
        if (TextUtils.isEmpty(end)) return type;

        for (int i = 0; i < MIME_MapTable.length; i++) {
            if (end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }

    /**
     * 打开文件
     *
     * @param context
     * @param file    文件
     */
    public void openFile(Context context, File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        String type = getMIMEType(file);
        //设置intent的data和Type属性。
        intent.setDataAndType(Uri.fromFile(file), type);
        context.startActivity(intent);
    }

    /**
     * 自动安装apk文件
     *
     * @param context
     * @param file
     */
    public static void openApk(Context context, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    //判断文件是否存在
    public boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    private static final String[][] MIME_MapTable = {
            {".3gp", "video/3gpp"},
            {".apk", "application/vnd.android.package-archive"},
            {".asf", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".bin", "application/octet-stream"},
            {".bmp", "image/bmp"},
            {".c", "text/plain"},
            {".class", "application/octet-stream"},
            {".conf", "text/plain"},
            {".cpp", "text/plain"},
            {".doc", "application/msword"},
            {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {".xls", "application/vnd.ms-excel"},
            {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {".exe", "application/octet-stream"},
            {".gif", "image/gif"},
            {".gtar", "application/x-gtar"},
            {".gz", "application/x-gzip"},
            {".h", "text/plain"},
            {".htm", "text/html"},
            {".html", "text/html"},
            {".jar", "application/java-archive"},
            {".java", "text/plain"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".js", "application/x-javascript"},
            {".log", "text/plain"},
            {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"},
            {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"},
            {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"},
            {".mov", "video/quicktime"},
            {".mp2", "audio/x-mpeg"},
            {".mp3", "audio/x-mpeg"},
            {".mp4", "video/mp4"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".mpe", "video/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"},
            {".mpg4", "video/mp4"},
            {".mpga", "audio/mpeg"},
            {".msg", "application/vnd.ms-outlook"},
            {".ogg", "audio/ogg"},
            {".pdf", "application/pdf"},
            {".png", "image/png"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
            {".prop", "text/plain"},
            {".rc", "text/plain"},
            {".rmvb", "audio/x-pn-realaudio"},
            {".rtf", "application/rtf"},
            {".sh", "text/plain"},
            {".tar", "application/x-tar"},
            {".tgz", "application/x-compressed"},
            {".txt", "text/plain"},
            {".wav", "audio/x-wav"},
            {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".wps", "application/vnd.ms-works"},
            {".xml", "text/plain"},
            {".z", "application/x-compress"},
            {".zip", "application/x-zip-compressed"},
            {"", "*/*"}
    };
}

因为http post请求目标网站会出现  405 Not Allowed 的错误,原因为是Apache、IIS、Nginx等绝大多数web服务器,都不允许静态文件响应POST请求,所以我用的是x.http().get(requestParams, new Callback.ProgressCallback<File>()),没用x.http().post(requestParams, new Callback.ProgressCallback<File>())方法。

小白一枚有什么问题请多多包涵,不过一定要告诉我,继续写bug!!!



猜你喜欢

转载自blog.csdn.net/lala_peng/article/details/79629897