天天看點

android 運用AsyncTask 擷取圖檔并顯示

為什麼BitmapFactory.decodeByteArray()傳回null問題

activity_main.xml布局裡面一個按鈕跟一個imageView

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="從網絡上下載下傳一張圖檔" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"/>

</LinearLayout>
           

MainActivity.java代碼如下

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class MainActivity extends AppCompatActivity {
    private Button bt;
    private ImageView img;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt = (Button) findViewById(R.id.button);
        img = (ImageView) findViewById(R.id.imageView);
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("提示資訊");
        progressDialog.setMessage("正在下載下傳");
        progressDialog.setCancelable(false);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MyAscyTask().execute();
            }
        });
    }

    public class MyAscyTask extends AsyncTask<String, Integer, byte[]> {

        @Override
        protected byte[] doInBackground(String... params) {
            InputStream ism = null;
            HttpURLConnection con = null;
            BufferedReader read = null;
            try {
                URL url = new URL("http://ww2.sinaimg.cn/mw690/69c7e018jw1e6hd0vm3pej20fa0a674c.jpg");
                con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setReadTimeout();
                con.setConnectTimeout();
                ism = con.getInputStream();
                read = new BufferedReader(new InputStreamReader(ism));
                StringBuffer sb = new StringBuffer();
                String line = null;
                while ((line = read.readLine()) != null) {
                    sb.append(line);
                }
                return sb.toString().getBytes();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (ism != null) {
                        ism.close();
                        ism = null;
                    }
                    if (read != null) {
                        read.close();
                        read = null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();
        }

        @Override
        protected void onPostExecute(byte[] bytes) {
            super.onPostExecute(bytes);
            Log.i("TAG", "onPostExecute: "+bytes.length+"==="+bytes[]);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, , bytes.length);
            img.setImageBitmap(bitmap);
            progressDialog.dismiss();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }
}
}
           

運作結果: 記得運作時權重限,因為通路網絡,不會從網絡得到圖檔,因為BitmapFactory.decodeByteArray方法傳回空

android 運用AsyncTask 擷取圖檔并顯示

修改MainActivity.java

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class MainActivity extends AppCompatActivity {
    private Button bt;
    private ImageView img;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt = (Button) findViewById(R.id.button);
        img = (ImageView) findViewById(R.id.imageView);
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("提示資訊");
        progressDialog.setMessage("正在下載下傳");
        progressDialog.setCancelable(false);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MyAscyTask().execute();
            }
        });
    }

    public class MyAscyTask extends AsyncTask<String, Integer, byte[]> {

        @Override
        protected byte[] doInBackground(String... params) {
            InputStream ism = null;
            HttpURLConnection con = null;
            ByteArrayOutputStream out=new ByteArrayOutputStream();
            try {
                URL url = new URL("http://ww2.sinaimg.cn/mw690/69c7e018jw1e6hd0vm3pej20fa0a674c.jpg");
                con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setReadTimeout();
                con.setConnectTimeout();
                ism = con.getInputStream();
                int size;
                while ((size=ism.read())!=-) {
                    out.write(size);
                }
                return out.toByteArray();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (ism != null) {
                        ism.close();
                        ism = null;
                    }
                    if (out!= null) {
                        out.close();
                        out=null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();
        }

        @Override
        protected void onPostExecute(byte[] bytes) {
            super.onPostExecute(bytes);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, , bytes.length);
            img.setImageBitmap(bitmap);
            progressDialog.dismiss();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }
}
}
           

運作結果:

android 運用AsyncTask 擷取圖檔并顯示

總結:源碼decodeByteArray方法的參數的說明

/**
     * Decode an immutable bitmap from the specified byte array.
     *
     * @param data byte array of compressed image data
     * @param offset offset into imageData for where the decoder should begin
     *               parsing.
     * @param length the number of bytes, beginning at offset, to parse
     * @return The decoded bitmap, or null if the image could not be decoded.
     */
    public static Bitmap decodeByteArray(byte[] data, int offset, int length) {
        return decodeByteArray(data, offset, length, null);
    }
           

再次修改MainActivity,實作邊下載下傳有進度條顯示

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class MainActivity extends AppCompatActivity {
    private Button bt;
    private ImageView img;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt = (Button) findViewById(R.id.button);
        img = (ImageView) findViewById(R.id.imageView);
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("提示資訊");
        progressDialog.setMessage("正在下載下傳");
        progressDialog.setCancelable(false);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MyAscyTask().execute();
            }
        });
    }

    public class MyAscyTask extends AsyncTask<String, Integer, byte[]> {

        @Override
        protected byte[] doInBackground(String... params) {
            InputStream ism = null;
            HttpURLConnection con = null;
            ByteArrayOutputStream out=new ByteArrayOutputStream();
            try {
                URL url = new URL("http://ww2.sinaimg.cn/mw690/69c7e018jw1e6hd0vm3pej20fa0a674c.jpg");
                con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setReadTimeout();
                con.setConnectTimeout();
                ism = con.getInputStream();
                byte[] data = new byte[];
                int size;
                long file_length=con.getContentLength();
                long total_length=;
                int i=;
                while ((size=ism.read(data))!=-) {
                    out.write(data,,size);
                    total_length+=size;
                    int progress=(int)((total_length/(float)file_length) * );
                    Log.i("TAG", "doInBackground: "+total_length+"==="+file_length+
                            "==="+progress);
                    Thread.sleep();
                    publishProgress(progress);
                }
                return out.toByteArray();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (ism != null) {
                        ism.close();
                        ism = null;
                    }
                    if (out!= null) {
                        out.close();
                        out=null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();
        }

        @Override
        protected void onPostExecute(byte[] bytes) {
            super.onPostExecute(bytes);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, , bytes.length);
            img.setImageBitmap(bitmap);
            progressDialog.dismiss();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Log.i("TAG", "onProgressUpdate:....... "+values[]);
            progressDialog.setProgress(values[]);
        }
    }
}