简单实现下载图片显示:
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".DownloadActivity" >
<Button
android:id="@+id/downloadPictureBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="下载" />
<ImageView
android:id="@+id/showGetPicture"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
主代码:
1.声明组件:
private Button downloadPictureBtn;
private ImageView showGetPicture;
private String pircturePath = "http://f.hiphotos.baidu.com/image/pic/item/d31b0ef41bd5ad6ee8afceed83cb39dbb6fd3c66.jpg";
private FileOutputStream mFileOutputStream = null;
一 .使用异步任务类从网上下载图片:
public class downloadAnsyncTask_1 extends AsyncTask<String, Void, Bitmap> {
private ProgressDialog mProgressDialog;
@Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(DownloadActivity.this);
mProgressDialog.setTitle("提示");
mProgressDialog.setMessage("正在下载...");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
super.onPreExecute();
}
@Override
protected Bitmap doInBackground(String... arg0) {
ByteArrayOutputStream bos = null;
try {
URL url = new URL(arg0[0]);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");// 设置请求方式为Get
conn.setReadTimeout(5 * 1000);// 设置请求时间
InputStream inputStream = conn.getInputStream();// 拿到输入流
byte[] data = new byte[2 * 1024];
int len = 0;
bos = new ByteArrayOutputStream();
while ((len = inputStream.read(data)) != -1) {
bos.write(data, 0, len);
mFileOutputStream.write(data, 0, len);
}
bos.flush();
bos.close();
mFileOutputStream.flush();
mFileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeByteArray(bos.toByteArray(), 0,
bos.toByteArray().length);
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
showGetPicture.setImageBitmap(result);
mProgressDialog.dismiss();
super.onPostExecute(result);
}
}
点击事件中的代码:
@Override
public void onClick(View arg0) {
new downloadAnsyncTask_1().execute(pircturePath);
}
二:使用HttpClient下载
public class downloadAnsyncTask_2 extends AsyncTask<String, Void, Bitmap> {
private ProgressDialog mProgressDialog;
@Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(DownloadActivity.this);
mProgressDialog.setTitle("提示");
mProgressDialog.setMessage("正在下载...");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
super.onPreExecute();
}
@Override
protected Bitmap doInBackground(String... arg0) {
// 改方法不推荐使用,HttpClient版本变化时,可能访问不了出现403
Bitmap bitmap = null;
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(arg0[0]);
try {
HttpResponse httpResponse = client.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
Log.i("TAG", "statusCode: " + statusCode);
if (statusCode == 200) {
HttpEntity entity = httpResponse.getEntity();
InputStream is = entity.getContent();
bitmap = BitmapFactory.decodeStream(is);
byte[] data = new byte[2 * 1024];
int len = 0;
while ((len = is.read(data)) != -1) {
mFileOutputStream.write(data, 0, len);
}
mFileOutputStream.flush();
mFileOutputStream.close();
Log.i("TAG", "bitmap: " + bitmap);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
showGetPicture.setImageBitmap(result);
mProgressDialog.dismiss();
super.onPostExecute(result);
}
}
三.使用Thread+Handler下载图片
new Thread(new Runnable() {
@Override
public void run() {
ByteArrayOutputStream bos = null;
try {
URL url = new URL(pircturePath);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");// 设置请求方式为Get
conn.setReadTimeout(5 * 1000);// 设置请求时间
InputStream inputStream = conn.getInputStream();// 拿到输入流
byte[] data = new byte[2 * 1024];
int len = 0;
bos = new ByteArrayOutputStream();
while ((len = inputStream.read(data)) != -1) {
bos.write(data, 0, len);
}
bos.flush();
bos.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeByteArray(
bos.toByteArray(), 0, bos.toByteArray().length);
Message message = new Message();
message.obj = bitmap;
message.arg1 = 0x001;
mHandler.sendMessage(message);
}
}).start();
Handler代码:
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.arg1 == 0x001) {
showGetPicture.setImageBitmap((Bitmap) msg.obj);
}
super.handleMessage(msg);
}
};
onCreate中的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
downloadPictureBtn = (Button) findViewById(R.id.downloadPictureBtn);
showGetPicture = (ImageView) findViewById(R.id.showGetPicture);
downloadPictureBtn.setOnClickListener(this);
File file = new File(Environment.getExternalStorageDirectory()
+ "/test.jpg");
try {
mFileOutputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
最终的效果: