栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

安卓下载文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

安卓下载文件

下载文件

1,伙伴们,在这里我是下载的 .zip文件到本地,添加到了 进度条显示,具体代码如下:

2,首先是 布局吧:





    

    

    

    

3,然后 呢 是点击事件 和具体代码:

package com.example.myviewtwo.study.six.downLoadZip;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.content.pm.PackageManager;
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.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myviewtwo.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class DownLoadZipActivity extends AppCompatActivity {


    //    第二种方法
    public static final int EXTERNAL_STORAGE_REQ_CODE = 10 ;
    private static final String Path="https://storage.googleapis.com/flutter_infra_release/releases/stable/windows/flutter_windows_2.2.1-stable.zip";
    private static String fileName = "flutter_windows_2.2.1-stable.zip";
    private static String filePath= "/download/";
    private ProgressBar progressBar;
    private TextView textView;
    private Button button;
    private int FileLength;
    private int DownedFileLength=0;
    private InputStream inputStream;
    private URLConnection connection;


    private Handler handler=new Handler() {
        public void handleMessage(Message msg)
        {
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {
                    case 0:
                        progressBar.setMax(FileLength);
                        Log.i("info","文件总长度----------->"+ progressBar.getMax()+"");
                        break;
                    case 1:
                        int  percent = (int) (((float) DownedFileLength / FileLength) * 100);
                        Log.d("info","下载进度更新=="+percent +" 总长度是=="+FileLength);
                        progressBar.setProgress(percent);
                        textView.setText(percent+"%");
                        break;
                    case 2:
                        Log.d("info","下载完成了");
                        Toast.makeText(getApplicationContext(), "下载完成", Toast.LENGTH_LONG).show();
                        break;

                }
            }
        }

    };




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


        int permission = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_REQ_CODE);

        }


        progressBar=(ProgressBar) findViewById(R.id.download_main_progressBarlist);
        textView=(TextView) findViewById(R.id.download_main_Text);
        button=(Button) findViewById(R.id.download_main_Button);


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DownedFileLength=0;
                Thread thread=new Thread(){
                    public void run(){
                        try {
                            DownFile(Path);//下载 zip文件包
                        } catch (Exception e) { }
                    }
                };
                thread.start();
            }
        });



    }




    private void DownFile(String urlString) {

        
        try {

            URL url = new URL(urlString);
            connection = url.openConnection();
            if (connection.getReadTimeout() == 5) {
                Log.i("info", "当前网络有问题");
                return;
            }
            if(connection==null){
                Log.i("info", "当前连接失败");
                return;
            }

            inputStream = connection.getInputStream();

        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        
        String savePAth = Environment.getExternalStorageDirectory() + filePath;
        File file1 = new File(savePAth);
        if (!file1.exists()) {
            file1.mkdir();
        }
        String savePathString = Environment.getExternalStorageDirectory() + filePath + fileName;
        File file = new File(savePathString);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        Message message = new Message();
        try {
            FileLength = connection.getContentLength();
            Log.d("info","文件的总长度是=="+FileLength);
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rwd");
            randomAccessFile.setLength(FileLength);
            byte[] buf = new byte[1024 * 4];
            message.what = 0;
            handler.sendMessage(message);

            int length = 0;
            while ((length = inputStream.read(buf)) != -1) {
                randomAccessFile.write(buf, 0, length);
                DownedFileLength += length;
                Log.i("info", "正在下载的文件长度是==="+DownedFileLength + "");
                Message message1 = new Message();
                message1.what = 1;
                handler.sendMessage(message1);
            }
            inputStream.close();
            randomAccessFile.close();
            Message message2 = new Message();
            message2.what = 2;

            handler.sendMessage(message2);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

OK 最后把,就是这样,大家都是 大神一看便知。谢谢收看 哈哈哈

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/602651.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号