android-HttpURLConnection+Handler+Thread下載圖片並顯示
阿新 • • 發佈:2019-02-17
注意:
下載圖片、儲存圖片都需要非同步操作。
java程式碼:
package com.example.administrator.downloadimgdemo;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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.ImageView;
import android.widget.Toast;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class IcsTestActivity extends Activity {
private final static String TAG = "IcsTestActivity";
private final static String ALBUM_PATH = Environment.getExternalStorageDirectory() + "/download_test/" ;
private ImageView mImageView;
private Button mBtnSave;
private ProgressDialog mSaveDialog = null;
private Bitmap mBitmap;
private String mFileName;
private String mSaveMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageView = (ImageView) findViewById(R.id.imgSource);
mBtnSave = (Button) findViewById(R.id.btnSave);
new Thread(connectNet).start();//獲取網路圖片的位元組陣列或者流,轉換成bitmap並顯示圖片
// 下載圖片
mBtnSave.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mSaveDialog = ProgressDialog.show(IcsTestActivity.this, "儲存圖片", "圖片正在儲存中,請稍等...", true);
new Thread(saveFileRunnable).start();
}
});
}
/**
* 儲存檔案
*
* @param bm
* @param fileName
* @throws IOException
*/
public void saveFile(Bitmap bm, String fileName) throws IOException {
File dirFile = new File(ALBUM_PATH);
if (!dirFile.exists()) {
dirFile.mkdir();//建立不存在的目錄
}
File myCaptureFile = new File(ALBUM_PATH + fileName);//將字串轉換成抽象路徑名
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
}
private Runnable saveFileRunnable = new Runnable() {
@Override
public void run() {
try {
saveFile(mBitmap, mFileName);
mSaveMessage = "圖片儲存成功!";
} catch (IOException e) {
mSaveMessage = "圖片儲存失敗!";
e.printStackTrace();
}
messageHandler.sendMessage(messageHandler.obtainMessage());
}
};
private Handler messageHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mSaveDialog.dismiss();
Log.d(TAG, mSaveMessage);
Toast.makeText(IcsTestActivity.this, mSaveMessage, Toast.LENGTH_SHORT).show();
}
};
/*
* 連線網路
* 由於在4.0中不允許在主執行緒中訪問網路,所以需要在子執行緒中訪問
*/
private Runnable connectNet = new Runnable() {
@Override
public void run() {
try {
String filePath = "http://img.my.csdn.net/uploads/201402/24/1393242467_3999.jpg";
mFileName = "test.jpg";
//以下是取得圖片的兩種方法
//////////////// 方法1:取得的是byte陣列, 從byte陣列生成bitmap
byte[] data = getImage(filePath);
if (data != null) {
mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap
} else {
Toast.makeText(IcsTestActivity.this, "Image error!",Toast.LENGTH_LONG).show();
}
////////////////////////////////////////////////////////
//******** 方法2:取得的是InputStream,直接從InputStream生成bitmap :推薦使用***********/
mBitmap = BitmapFactory.decodeStream(getImageStream(filePath));
//********************************************************************/
// 傳送訊息,通知handler在主執行緒中更新UI
connectHanlder.sendEmptyMessage(0);
Log.d(TAG, "set image ...");
} catch (Exception e) {
Toast.makeText(IcsTestActivity.this, "無法連結網路!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
};
private Handler connectHanlder = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "display image");
// 更新UI,顯示圖片
if (mBitmap != null) {
mImageView.setImageBitmap(mBitmap);// display image
}
}
};
/*---------------------------------------------獲取網路圖片-----------------------------------------------*/
/**
* Get image from newwork
*
* @param path The path of image
* @return byte[]
* @throws Exception
*/
public byte[] getImage(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
InputStream inStream = conn.getInputStream();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return readStream(inStream);
}
return null;
}
/**
* Get image from newwork
*
* @param path The path of image
* @return InputStream
* @throws Exception
*/
public InputStream getImageStream(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return conn.getInputStream();
}
return null;
}
/**
* Get byte[] from stream
*
* @param inStream
* @return byte[]
* @throws Exception
*/
public static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}
/*---------------------------------------------------------------------------------------------------------*/
}
佈局:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="儲存圖片" />
<ImageView
android:id="@+id/imgSource"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true" />
</LinearLayout>
</ScrollView>