android 使用HTTP下载网络图片并保存到Sdcard卡
本文实现了两个功能:
1、从网络下载图片。
2、将图片保存到Sdcard卡。
文件目录:
效果图:
先创建两个类,分别实现两个功能。
HTTP类,从网络下载图片:
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class HTTP {
/**
* 从path下载数据并且返回
* @param path
* @return
*/
public static byte[] httpData(String path){
//获取HttpClient类
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(path);
byte[] data = null;
try {
HttpResponse response = client.execute(get);
//是否连接成功
if(response.getStatusLine().getStatusCode() == 200){
data = EntityUtils.toByteArray(response.getEntity());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
}
Save类,保存数据到Sdcard卡:
该类实现了从程序存储数据到SD卡,以及从SD卡读取数据到程序。
Log.i(“Save”, “—>>” + file);//输出文件保存目录,可以在File Explorer 中对应目录查找文件是否保存成功。
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.os.Environment;
import android.util.Log;
public class Save {
/**
* 存取数据到内存卡
*
* @param fileName
* @param data
* @return
*/
public static boolean saveFileToSdcard(String fileName, byte[] data) {
boolean flag = false;
//保存数据到Sdcard步凑:
//1、获取Sdcard卡的目录
File file = Environment.getExternalStorageDirectory();
FileOutputStream outputStream = null;
Log.i("Save", "--saveFileToSdcard->>");
//2、判断Sdcard的状态是否为挂载
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Log.i("Save", "--if->>");
try {
//3、使用Sdcard目录和需要保存文件的文件名实例化一个File对象,使用该对象创建一个文件输出流
outputStream = new FileOutputStream(new File(file, fileName));
//4.将需要保存的数据写入输出流
outputStream.write(data, 0, data.length);
flag = true;
Log.i("Save", "--->>" + file);//输出文件保存目录
//5.关闭流
outputStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("Save", "--catch->>");
}
}
return flag;
}
/**
* 从sdcard读取指定文件
*
* @param fileName
* @return
*/
public static byte[] readFileToSdcard(String fileName) {
byte[] data = new byte[1024];
int len = 0;
//读取数据和写数据步凑类似
File root = Environment.getExternalStorageDirectory();
FileInputStream fileInputStream = null;
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
try {
fileInputStream = new FileInputStream(new File(root, fileName));
while ((len = fileInputStream.read(data)) != -1) {
arrayOutputStream.write(data, 0, len);
}
fileInputStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return arrayOutputStream.toByteArray();
}
}
MainActivity类文件:
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import com.example.class_storage_sdcard1.HTTP.HTTP;
import com.example.class_storage_sdcard1.SAVE.Save;
public class MainActivity extends Activity {
private final String PATH = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png";//下载图片的地址
private ProgressDialog dialog;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new ProgressDialog(this);//建立一个进度条对话框
dialog.setTitle("提示!");
dialog.setMessage("正在下载图片并保存到本地……");
dialog.setCancelable(false);
imageView = (ImageView)findViewById(R.id.imageView1);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
//按键触发下载
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new MyTast().execute(PATH);//使用下载地址创建一个线程
}
});
}
//自定义一个线程,在线程中完成下载操作
class MyTast extends AsyncTask<String, Void, byte[]> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.show();//弹出对话框
}
@Override
protected byte[] doInBackground(String... params) {
// TODO Auto-generated method stub
return HTTP.httpData(params[0]);//调用HTTP工具类下载数据并且返回
}
@Override
protected void onPostExecute(byte[] result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Save.saveFileToSdcard("logo.png", result);//将数据保存到Sdcard
Bitmap bm = BitmapFactory.decodeByteArray(Save.readFileToSdcard("logo.png"), 0, result.length);
//使用位图工厂将创建位图
//从Sdcard读取图片数据,并且加载到ImagerView
imageView.setImageBitmap(bm);
dialog.dismiss();
}
}
}
XML布局文件:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#cccccc">
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="38dp"
android:src="@drawable/ic_launcher" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="92dp"
android:text="下载" />
</RelativeLayout>
还有非常重要的两点:
1、要操作Sdcard,要清单文件中需要加载权限。
2、连接网络需要在清单文件中加载权限。
清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.class_storage_sdcard1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="18" />
<!-- 网络权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- 外部存储器 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.class_storage_sdcard1.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>