Android通过url下载文件到手机本地

  • 这里的demo是一个通过下载地址下载图片文件到手机本地,并在Activity中展示这种图片的例子。

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context="com.example.downFile.MainActivity">

    <ImageView
        android:id="@+id/iv_main"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:src="@color/colorAccent"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="按钮"
        android:onClick="onClick"/>
</LinearLayout>

Activity

package com.example.downFile;

import android.app.DownloadManager;
import android.content.Context;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;

import com.example.downFile.service.DownLoadReceiver;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private String mTag = getClass().getSimpleName();

    private ImageView mIvMain;
    private String mDownLoadPath = "https://www.baidu.com/img/bd_logo1.png";
    private String mFileName = "12.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mIvMain = findViewById(R.id.iv_main);
    }

    public void onClick(View v) {
        if (FileUtils.initPictureDir()) {
            FileUtils.deDuplication(new File(FileUtils.PICTURE_DIR, mFileName));
            downPciture();
        } else {
            Log.d(mTag, "目录初始化失败");
        }

    }

    // 下载
    private void downPciture() {
        // 创建下载任务
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mDownLoadPath));
        // 漫游网络是否可以下载
        request.setAllowedOverRoaming(false);

        // 设置文件类型,可以在下载结束后自动打开该文件
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(mDownLoadPath));
        request.setMimeType(mimeString);

        // 在通知栏中显示,默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setVisibleInDownloadsUi(true);

        // sdcard的目录下的download文件夹,必须设置
        request.setDestinationInExternalPublicDir(TheApplication.getContext().getPackageName()
                + File.separator + "yunli" + File.separator, mFileName);
        //  request.setDestinationInExternalFilesDir(),也可以自己制定下载路径

        // 将下载请求加入下载队列
        DownloadManager downloadManager = (DownloadManager) TheApplication.getContext()
                .getSystemService(Context.DOWNLOAD_SERVICE);
        // 加入下载队列后会给该任务返回一个long型的id,
        // 通过该id可以取消任务,重启任务等等
        long taskId = downloadManager.enqueue(request);

        //注册广播接收者,监听下载状态
        DownLoadReceiver downLoadReceiver = new DownLoadReceiver(TheApplication.getContext(),
                downloadManager, taskId, mFileName, mIvMain);
        registerReceiver(downLoadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
}

BroadcastReceiver

package com.example.downFile.service;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.widget.ImageView;

import com.example.downFile.FileUtils;
import com.example.downFile.LogUtil;
import com.example.downFile.ImageUtils;

import java.io.File;


public class DownLoadReceiver extends BroadcastReceiver {

    private String mTag = getClass().getSimpleName();
    //    private NotificationManager nm;
    //    private Intent mIntent;
    private DownloadManager downloadManager;
    private long mTaskId;
    private Context mContext;
    private String mFileName;
    private ImageView iv_main;

    public DownLoadReceiver(Context context, DownloadManager downloadManager, long taskId, String fileName, ImageView iv_main) {
        this.downloadManager = downloadManager;
        this.mTaskId = taskId;
        this.mContext = context;
        this.mFileName = fileName;
        this.iv_main = iv_main;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // 检查下载状态
        checkDownloadStatus();
    }

    //检查下载状态
    private void checkDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(mTaskId);//筛选下载任务,传入任务ID,可变参数
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                case DownloadManager.STATUS_PAUSED:
                    LogUtil.e(mTag, ">>>下载暂停");
                case DownloadManager.STATUS_PENDING:
                    LogUtil.e(mTag, ">>>下载延迟");
                case DownloadManager.STATUS_RUNNING:
                    LogUtil.e(mTag, ">>>正在下载");
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    LogUtil.e(mTag, ">>>下载完成");
                    File file = new File(FileUtils.PICTURE_DIR, mFileName);
                    Log.d("文件", "存在不:" + file.exists() + "路径" + file.getPath());
                    ImageUtils.ShowPic2View(mContext, file.getPath(), iv_main);
                    c.close();
                    //                    UtilsTools.deleteFile(fileName);
                    //downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + versionName;
                    //                    installAPK(new File(downloadPath));
                    break;
                case DownloadManager.STATUS_FAILED:
                    LogUtil.e(mTag, ">>>下载失败");
                    break;
            }
        }
        c.close();
    }
}

文件工具类

package com.example.downFile;

import android.os.Environment;
import android.util.Log;

import java.io.File;


public class FileUtils {
    /**
     * sdcard
     */
    private static final String SD_ROOT = Environment.getExternalStorageDirectory().getPath();

    /**
     * app根目录
     */
    public static final String PICTURE_DIR = SD_ROOT + File.separator + TheApplication.getContext().getPackageName()
            + File.separator + "yunli" + File.separator;

    private FileUtils() {
    }

    /**
     * 是否存在 SDCard
     *
     * @return 是否存在
     */
    public static boolean sdExist() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public static boolean initPictureDir() {
        if (!sdExist()) {
            return false;
        }
        File picFile = new File(PICTURE_DIR);
        boolean exists = picFile.exists();
        boolean mkdirs = picFile.mkdirs();
        return exists || mkdirs;
    }

    // 获取文件大小
    public static void deDuplication(File file) {
        if (file.exists()) {
            Log.d("fileUtil", "存在了:" + file.getPath());
            boolean isDelete = file.delete();
            Log.d("fileUtil", "删除文件结果:" + isDelete);
        } else {
            Log.d("fileUtil", "文件不存在:" + file.getPath());
        }
    }
}

图片工具类

package com.example.downFile;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.widget.ImageView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 图片相关的工具类
 */
public class ImageUtils {

    /**
     * base64字符串转化成图片
     */
    public static String GenerateImage(Context context, String imgStr) {

        //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) { //图像数据为空
            UtilsTools.MsgBox(context, "图片不能为空");
            return "";
        }

        try {
            //Base64解码
            byte[] b = Base64Utils.decode(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            // 新生成的jpg图片
            // 新图片的文件夹, 如果没有, 就创建
            String dirPath = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/zdgj/";
            File fileDir = new File(dirPath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            // 文件夹现在存在了, 可以在此文件夹下创建图片了
            String imgFilePath = dirPath + System.currentTimeMillis() + ".jpg";
            File file = new File(imgFilePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            SharedPrefUtil.putString(context, "facePic", imgFilePath);
            UtilsTools.MsgBox(context, "图片已保存到本地");
            return imgFilePath;
        } catch (Exception e) {
            UtilsTools.MsgBox(context, e.getMessage());
            return "";
        }
    }


    /**
     * 将图片转换成Base64编码的字符串
     *
     * @param path 图片本地路径
     * @return base64编码的字符串
     */
    public static String imageToBase64(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        InputStream is = null;
        byte[] data;
        String result = null;
        try {
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data, Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


    /**
     * 在ImageView里展示指定路径的图片
     *
     * @param path      本地路径
     * @param imageView ImageView
     */
    public static void ShowPic2View(Context context, String path, ImageView imageView) {
        File localFile = new File(path);
//        if (!localFile.exists()) {
//            UtilsTools.MsgBox(context, path + " is null.");
//        } else {
            try {
                FileInputStream localStream;
                localStream = new FileInputStream(localFile);
                Bitmap bitmap = BitmapFactory.decodeStream(localStream);
                imageView.setImageBitmap(bitmap);
                //                if (localStream != null) {
                localStream.close();
                //                }
            } catch (Exception e) {
                e.printStackTrace();
                UtilsTools.MsgBox(context, e.getMessage());
            }
//        }
    }


    /**
     * 删除手机里指定路径的图片
     *
     * @param context Context
     * @param imgPath 本地路径
     */
    public static void DeletePicFromMobile(Context context, String imgPath) {
        try {
            ContentResolver resolver = context.getContentResolver();
            Cursor cursor = MediaStore.Images.Media.query(resolver, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=?", new String[]{imgPath}, null);
            boolean result;
            if (cursor.moveToFirst()) {
                long id = cursor.getLong(0);
                Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                Uri uri = ContentUris.withAppendedId(contentUri, id);
                int count = context.getContentResolver().delete(uri, null, null);
                result = count == 1;
            } else {
                File file = new File(imgPath);
                result = file.delete();
            }

            if (result) {
                UtilsTools.MsgBox(context, "删除成功");
            }
        } catch (Exception e) {
            UtilsTools.MsgBox(context, e.getMessage());
        }
    }
}

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.downFile">

    <!--用于访问网络-->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CALL_PHONE"/>
    <!--获取手机唯一标识IMEI-->
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <!--获取运营商信息,用于支持提供运营商信息相关的接口-->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.VIBRATE"/>
    <!--用于访问wifi网络信息,wifi信息会用于进行网络定位-->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <!--这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_PHONE_STORAE"/>
    <!-- 用于进行网络定位 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <!-- 用于访问GPS定位 -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <!-- 通讯录权限 -->
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.WRITE_CONTACTS"/>
    <!-- 相机 -->
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_SETTINGS"/>


    <application
        android:name="com.example.downFile.TheApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name="com.example.downFile.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

MyApplication

package com.example.downFile;

import android.app.Application;
import android.content.Context;

import java.lang.ref.WeakReference;


public class TheApplication extends Application {
    private static WeakReference<Context> mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = new WeakReference<>(getApplicationContext());
    }

    /**
     * 全局获取 Context
     *
     * @return ApplicationContext
     */
    public static Context getContext() {
        return mContext.get();
    }
}
发布了130 篇原创文章 · 获赞 16 · 访问量 7万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览