Android studio 網絡下載圖片並保存sdcard download 文件夾下

第一步在手機中設置存儲sdcard權限

第二步AndroidManifest.xml
   <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

第三步:activity-main.xml
  <SeekBar
        android:id="@+id/seekbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:progress="50"/>
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:scaleType="center"/>

第四步MainActivity.Java

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.SeekBar;


import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;


public class MainActivity extends AppCompatActivity {

    private SeekBar mSeekBar;
    private  final String urlString = "http://192.168.0.134:280/AA.jpg";
    private ImageView mIV;
    private int fileLength;
    private Bitmap mBitmap;

    public static void saveBitmap(Bitmap bitmap,String path) {
        String savePath;
        File filePic;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            savePath = path;
        } else {
            Log.e("tag", "saveBitmap failure : sdcard not mounted");
            return;
        }
        try {
            filePic = new File(savePath);
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            Log.e("tag", "saveBitmap: " + e.getMessage());
            return;
        }
        Log.i("tag", "saveBitmap success: " + filePic.getAbsolutePath());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSeekBar = (SeekBar)findViewById(R.id.seekbar);
        mIV = (ImageView)findViewById(R.id.image);
        new Thread(downloadRunn).start();
    }
    private Runnable downloadRunn = new  Runnable(){
        @Override
        public void run() {
            try {
                String filepath="/sdcard/Download/xxxx20200601.jpg";
                URL url = new URL(urlString);
                URLConnection connection = url.openConnection();
                connection.connect();
                fileLength = connection.getContentLength();
                InputStream in = new BufferedInputStream(connection.getInputStream());
                byte[] arr = readStream(in);
                mBitmap = BitmapFactory.decodeByteArray(arr,0,arr.length);
                //測試保護文件函數代碼
                saveBitmap(mBitmap,filepath);
                //
                connectHanlder.sendEmptyMessage(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    public  byte[] readStream(InputStream in) throws Exception{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while((count = in.read(data))!=-1){
            total+=count;
            mSeekBar.setProgress((int)(total*100)/fileLength);
            bos.write(data,0,count);
        }
        bos.close();
        in.close();
        return bos.toByteArray();
    }
    private Handler connectHanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // 更新UI,顯示圖片
            if (mBitmap != null) {
                mIV.setImageBitmap(mBitmap);// display image
            }
        }
    };
}








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章