1. 程式人生 > >Android studio 多執行緒網路檔案下載

Android studio 多執行緒網路檔案下載

執行結果

執行結果

下載完成

開啟圖片

檔案結構

檔案結構

主要程式碼

MainActivity

package cn.edu.sicnu.threadfiledownload;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import
android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import
java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { EditText editText_url; ListView listView; //heap堆,可以被整個物件所有方法訪問 TextView textView; ProgressBar progressBar; ArrayList<String> arrayList = new
ArrayList<>(); ArrayList<String> localImages = new ArrayList<>(); ArrayAdapter<String> arrayAdapter; MyAsyncTask asyncTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); arrayList.add("http://img2.imgtn.bdimg.com/it/u=500808421,1575925585&fm=200&gp=0.jpg"); arrayList.add("http://img1.imgtn.bdimg.com/it/u=2883138594,3332343437&fm=27&gp=0.jpg"); arrayList.add("http://img0.imgtn.bdimg.com/it/u=2779717376,1807907918&fm=200&gp=0.jpg"); arrayList.add("http://img0.imgtn.bdimg.com/it/u=416447706,3692155938&fm=27&gp=0.jpg"); arrayList.add("http://img3.imgtn.bdimg.com/it/u=2058241956,1502683125&fm=27&gp=0.jpg"); arrayList.add("http://img0.imgtn.bdimg.com/it/u=2779717376,1807907918&fm=200&gp=0.jpg"); arrayList.add("http://img0.imgtn.bdimg.com/it/u=2779717376,1807907918&fm=200&gp=0.jpg"); editText_url = findViewById(R.id.editText_url); listView = findViewById(R.id.listView); arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arrayList); listView.setAdapter(arrayAdapter); textView = findViewById(R.id.textView); progressBar = findViewById(R.id.progressBar); asyncTask = new MyAsyncTask(); } public void add(View view){ arrayList.add(editText_url.getText().toString()); arrayAdapter.notifyDataSetChanged(); } public void download(View view){ switch (asyncTask.getStatus()){ case PENDING: asyncTask.execute(0); break; case RUNNING: break; case FINISHED: asyncTask = new MyAsyncTask(); asyncTask.execute(0); break; } } class MyAsyncTask extends AsyncTask<Integer,Integer,Integer>{ @Override protected void onPreExecute() { super.onPreExecute(); localImages.clear(); } @Override protected Integer doInBackground(Integer... integers) { //在另外一個執行緒裡面!!! for(int i=0;i<arrayList.size();i++){ String s = arrayList.get(i); try { URL url = new URL(s); URLConnection connection = url.openConnection(); int size = connection.getContentLength(); //圖片大小 publishProgress(0,i+1,size); InputStream inputStream = connection.getInputStream(); //流 byte[] bytes = new byte[100]; int len = -1; //準備好外部儲存檔案 File file = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); String filename = file.getAbsolutePath()+"/"+i+".jpg"; FileOutputStream fileOutputStream = new FileOutputStream(filename); while ((len=inputStream.read(bytes))!=-1){ fileOutputStream.write(bytes,0,len); // Thread.sleep(1); publishProgress(1,len); } fileOutputStream.close(); inputStream.close(); localImages.add(filename); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return null; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); switch (values[0]){ case 0: textView.setText("正在下載第"+values[1]+"個檔案!!!"); progressBar.setMax(values[2]); progressBar.setProgress(0); break; case 1: progressBar.incrementProgressBy(values[1]); break; } } @Override protected void onPostExecute(Integer integer) { super.onPostExecute(integer); textView.setText("下載完成!!!"); progressBar.setProgress(0); } } public void showImages(View view){ Intent intent = new Intent(this,Main2Activity.class); intent.putExtra("images",localImages); startActivity(intent); } }

Main2Activity

package cn.edu.sicnu.threadfiledownload;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.ArrayList;

public class Main2Activity extends AppCompatActivity {


    LinearLayout layout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        layout = findViewById(R.id.layout);

        Intent intent = getIntent();
        ArrayList<String> images = (ArrayList<String>) intent.getSerializableExtra("images");
        for(int i=0;i<images.size();i++){
            String imagePath = images.get(i);
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            ImageView imageView = new ImageView(this);
            imageView.setImageBitmap(bitmap);
            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            imageView.setAdjustViewBounds(true);

            layout.addView(imageView);
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="cn.edu.sicnu.threadfiledownload.MainActivity"
    tools:layout_editor_absoluteY="81dp">

    <EditText
        android:id="@+id/editText_url"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:ems="10"
        android:hint="Input image url"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/progressBar" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="4dp"
        android:layout_marginStart="16dp"
        android:onClick="add"
        android:text="add"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/button2"
        app:layout_constraintHorizontal_chainStyle="spread_inside"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_url" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="download"
        android:text="download"
        app:layout_constraintBottom_toBottomOf="@+id/button"
        app:layout_constraintEnd_toStartOf="@+id/button3"
        app:layout_constraintStart_toEndOf="@+id/button" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="17dp"
        android:onClick="showImages"
        android:text="images"
        app:layout_constraintBottom_toBottomOf="@+id/button2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/button2" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="13dp"
        android:layout_marginEnd="9dp"
        android:layout_marginStart="9dp"
        android:layout_marginTop="16dp"
        app:layout_constraintBottom_toTopOf="@+id/progressBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="110dp"
        android:layout_marginEnd="15dp"
        android:layout_marginStart="15dp"
        android:max="100"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginEnd="13dp"
        android:layout_marginStart="13dp"
        android:layout_marginTop="362dp"
        app:layout_constraintBottom_toTopOf="@+id/progressBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

activity_main2.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="cn.edu.sicnu.threadfiledownload.Main2Activity">

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/layout"/>
    </ScrollView>
</android.support.constraint.ConstraintLayout>