您的位置:首页 > 理论基础 > 计算机网络

android加载网络图片,并下载

2016-07-15 16:54 197 查看
看了别人写的,自己总结一下。

直接上代码:

private String imgPath=
"https://bbsstaticoss.hoopchina.com.cn/aHR0cDovL2h1cHUtaTFpNS5pbWctY24taGFuZ3pob3UuYWxpeXVuY3MuY29tL3RvdWNoLzQ5MC8yODE1MDQ5MC90b3VjaF9iYnNfdGhyZWFkX2ltZ18yODE1MDQ5MF8xNDY4NTUwMDA1LjI0NTQuanBlZw";
//图片是否已加载
boolean isLoadImg = false;
private Bitmap mBitmap;

String mFileName = "test.jpg";
String filePath = Environment.getExternalStorageDirectory()+ "/download_test/";

//Handler更新UI
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what) {
case 0:
if (mBitmap != null) {
img.setImageBitmap(mBitmap);
isLoadImg = true;
} else {
isLoadImg = false;
}
break;
}
}
}

//图片点击事件启动一个线程去加载图片
img.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
new Thread(loadingImage).start();
}
));
//这里直接写一个图片长按监听在下载图片
img.setOnLongClickListener(new OnLongClickListener(){
@Override
public boolean onLongClick(View v){
DownLoadImg();
}
//true:不加短按;false:加入短按.
return true;
});

Runnable loadingImage = new Runnable(){
@Override
try{
//方法一:取得byte[],从byte[]中生成bitmap;
byte[] data = getImage(imgPath);
if (data != null) {
mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
} else {
Toast.makeText(MainActivity.this, "image error", Toast.LENGTH_SHORT).show();
}

//方法二:取得InputStream,直接从InputStream生成Bitmap;
mBitmap = BitmapFactory.decodeStream(getImageStream(imgPath));
//通知Handler更新UI
mHandler.sendEmptyMessage(0);
}catch(Exception e){
e.printStackTrace();
}
}
}

/**
* get image from network
*
* @param path
*            of image
* @return InputStream
* @throws Exception
*/
public InputStream getImageStream(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setRequestMethod("GET");
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
return con.getInputStream();
}
return null;
}

/**
* get image from network
*
* @param path
* @return byte[]
* @throws Exception
*/
public byte[] getImage(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(50000);
con.setRequestMethod("GET");
InputStream inputStream = con.getInputStream();
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
return readStream(inputStream);
}
return null;
}

/**
* get data from Stream
*
* @param inputStream
* @return byte[]
* @throws Exception
*/
public static byte[] readStream(InputStream inputStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
inputStream.close();
return outStream.toByteArray();
}

private void DownloadImg() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("是否下载图片?")
.setCancelable(true)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getApplicationContext(), "正在保存图片...",
Toast.LENGTH_SHORT).show();
new Thread(downLoadRun).start();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}

Runnable downLoadRun = new Runnable() {

@Override
public void run() {
try {
saveFile(mBitmap, mFileName);
mHandler.sendEmptyMessage(1);
} catch (IOException e) {
mHandler.sendEmptyMessage(2);
e.printStackTrace();
}
}
};

/**
* saveFile
*
* @param mBitmap
* @param mFileName
*/
private void saveFile(Bitmap mBitmap, String mFileName) throws IOException {
File dirFile = new File(filePath);
if (!dirFile.exists()) {
// 如果文件路径不存在,就创建
dirFile.mkdir();
}
File file = new File(filePath + mFileName);
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
mBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
}


呃呃呃,就这么多,有几个地方还是要注意的:

网络请求需要写子线程里面,更新UI只能在主线程里面操作,所以需要Handler来更新UI;

流用完记得close();

加入权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: