Android 实现文件下载以及断点续传

2020-12-28  本文已影响0人  牧区叔叔

文件下载思路
1.首先获取手机或者设备目录
2.创建一个新的目录
3.往新建目录写数据流
4.关闭流

下载.gif

首先获取根目录 创建新目录 (代码在下面复制)

image.png
image.png
getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();

 private void downLoad(String urlAddress,String downAdress) {
        try {

            File file = new File(downAdress+"/downAPK");
            Log.i(TAG, "file path: "+file.getAbsolutePath());
            if (!file.exists()){
                file.mkdirs();
                Log.i(TAG, "file path on create ");
            }
        }catch (Exception ex){

        }
    }

以上走完我们查看log,发现已经创建成功。我们在模拟器上查下位置!


image.png image.png

接下来就是写IO流的一些操作

 private void downLoad(String urlAddress, String downAdress) {
        try {
            HttpURLConnection coon = (HttpURLConnection) new URL(urlAddress).openConnection();
            coon.setConnectTimeout(6000);
            String fileAddress = coon.getURL().getFile();
            String fileName = fileAddress.substring(fileAddress.lastIndexOf(File.separatorChar) + 1);
            
            File file = new File(downAdress );
            if (!file.exists()) {
                file.mkdirs();
                Log.i(TAG, "file path on create ");
            }
            file = new File(file+fileName);
            if (!file.exists()){
                file.delete();
            }
            InputStream is = coon.getInputStream();
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] bytes = new byte[1024];
            int size;
            int len = 0;
            while ((size = bis.read(bytes)) != -1) {
                len += size;
                fos.write(bytes, 0, size);
                Log.i(TAG, "下载进度: " + len * 100 / coon.getContentLength() + "%");
                Message mg = Message.obtain();
                mg.obj =len * 100 / coon.getContentLength();
                downHandler.sendMessage(mg);
            }
            fos.close();
            bis.close();
            is.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

下载部分全部代码如下

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.filedownload">
    <uses-permission android:name="android.permission.INTERNET"/>

    <uses-permission android:name="android.permission.READ_SETTINGS" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    
    <application
        android:usesCleartextTraffic="true"
        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=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

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

    <Button
        android:id="@+id/bt_download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="btOnClick"
        android:text="文件下载" />

    <Button
        android:id="@+id/bt_pause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="btOnClick"
        android:text="暂停" />

    <Button
        android:id="@+id/bt_goon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="btOnClick"
        android:text="继续下载" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ProgressBar
            android:id="@+id/pb"
            style="@style/Widget.AppCompat.ProgressBar.Horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:layout_toLeftOf="@id/tv_jindu" />

        <TextView
            android:id="@+id/tv_jindu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:text="20%" />
    </RelativeLayout>
</LinearLayout>
package com.test.filedownload;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private ProgressBar pb;
    private TextView tvJindu;
    private static String TAG = "main";
    private Handler downHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            int  str= (int) msg.obj;
            pb.setProgress(str);
            tvJindu.setText(str+"%");

        }
    };
    private String absolutePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        absolutePath = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        String rootFilePath = getRootFilePath();
        Log.i(TAG, "onCreate: "+ absolutePath);
        Log.i(TAG, "onCreate: "+rootFilePath);
    }

    public void btOnClick(View view) {
        switch (view.getId()){
            case R.id.bt_download:
               new DownLoadThread(absolutePath,downHandler).start();
                break;
            case R.id.bt_pause:
                break;
            case R.id.bt_goon:
                break;
        }
    }

    private void initView() {
        pb = (ProgressBar) findViewById(R.id.pb);
        tvJindu = (TextView) findViewById(R.id.tv_jindu);
    }

    //找到手机中内置存储卡的根目录
    public static String getRootFilePath() {
        /***
         *  getExternalStorageDirectory()  返回主共享/外部存储目录
         *  getAbsolutePath()  返回此文件的绝对路径
         *  getDataDirectory()  返回用户数据目录
         */
        if (hasSDCard()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath() + "";
        } else {
            return Environment.getDataDirectory().getAbsolutePath() + "/data";
        }
    }

    //上面需要判断用的方法
    public static boolean hasSDCard() {
        /***
         *   Environment  提供对环境变量的访问。
         *   getExternalStorageState() 返回主共享/外部存储介质的当前状态。
         *   Environment.MEDIA_MOUNTED  mounted  安装
         */
        String status = Environment.getExternalStorageState();
        Log.i(TAG, "status---->>: " + status);
        if (!status.equals(Environment.MEDIA_MOUNTED)) {
            return false;
        }
        return true;
    }
}
package com.test.filedownload;

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

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Handler;

public class DownLoadThread extends Thread {
//    private String urlAddress = "http://192.168.0.110/ChaoyangHygiene.apk";
    private String urlAddress = "http://192.168.1.12/ChaoyangHygiene.apk";//这个地址你换成自己的就行


    private String downAddress;
    private Handler downHandler;
    private String TAG = "down";

    public DownLoadThread(String downAdress, Handler downHandler) {
        this.downAddress = downAdress;
        this.downHandler = downHandler;
    }



    @Override
    public void run() {
        super.run();
       
        downLoad(urlAddress, downAddress);
       
    }
    private void downLoad(String urlAddress, String downAdress) {
        try {
            HttpURLConnection coon = (HttpURLConnection) new URL(urlAddress).openConnection();
            coon.setConnectTimeout(6000);
            String fileAddress = coon.getURL().getFile();
            String fileName = fileAddress.substring(fileAddress.lastIndexOf(File.separatorChar) + 1);

            File file = new File(downAdress );
            if (!file.exists()) {
                file.mkdirs();
                Log.i(TAG, "file path on create ");
            }
            file = new File(file+fileName);
            if (!file.exists()){
                file.delete();
            }
            InputStream is = coon.getInputStream();
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] bytes = new byte[1024];
            int size;
            int len = 0;
            while ((size = bis.read(bytes)) != -1) {
                len += size;
                fos.write(bytes, 0, size);
                Log.i(TAG, "下载进度: " + len * 100 / coon.getContentLength() + "%");
                Message mg = Message.obtain();
                mg.obj =len * 100 / coon.getContentLength();
                downHandler.sendMessage(mg);
            }
            fos.close();
            bis.close();
            is.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

接下来是断点续传部分----待定 元旦后更新 近期工作较忙

上一篇 下一篇

猜你喜欢

热点阅读