descargar archivo
1. Amigos, aquí descargué el archivo .zip localmente y lo agregué a la barra de progreso, el código específico es el siguiente:
2. Primero está el diseño:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".study.six.downLoadZip.DownLoadZipActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:layout_margin="20dp"
android:textSize="20sp"
android:text="第二种方法 下载 zip文件 "></TextView>
<ProgressBar
android:id="@+id/download_main_progressBarlist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:min="0"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
style="?android:attr/progressBarStyleHorizontal"
/>
<TextView
android:id="@+id/download_main_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/download_main_progressBarlist"
android:layout_below="@+id/download_main_progressBarlist"
android:layout_marginTop="20dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:text="当前进度" />
<Button
android:id="@+id/download_main_Button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginRight="15dp"
android:layout_marginLeft="15dp"
android:layout_alignLeft="@+id/download_main_Text"
android:layout_below="@+id/download_main_Text"
android:layout_marginTop="39dp"
android:text="下载zip文件" />
</LinearLayout>
3. Luego están los eventos de clic y códigos específicos:
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();
}
/*
* 文件的保存路径和和文件名其中Nobody.mp3是在手机SD卡上要保存的路径,如果不存在则新建
*/
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();
}
}
/*
* 向SD卡中写入文件,用Handle传递线程
*/
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();
}
}
}
Bueno, finalmente, eso es todo, todo el mundo es un maestro y lo puede saber de un vistazo. Gracias por ver jajaja