效果图示例:
步骤 -- 在配置清单添加完联网权限后
1、res/layout界面布局
代码
<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" >
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/bt_download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="图片下载"
android:onClick="Image_Download" />
</LinearLayout>
====================
2、有2个类一个操作SDCARD的文件工具类(FileUtil)另外一个MainActivity类
FileUtil类
代码
//操作SDCARD的文件工具类
public class FileUtil {
private static final String CACHE_DIR = Environment.getExternalStorageDirectory() + "/my_caches/images";
private static int COMP_JPG = 0;
private static int COMP_PNG = 1;
//判断sdcard 是否挂载(是否有sdcard)
public static boolean isMounted(){
String state = Environment.getExternalStorageState();
return state.equals(Environment.MEDIA_MOUNTED);
}
//获取sdcard文件 根路径的绝对路径
public static String getSDCARD(){
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
//获取文件名
public static String getFilename(String url){
return url.substring(url.lastIndexOf('/') + 1);
}
//保存文件 方法1
public static void sava1(String url,byte[] data){
//判断是否有sdcard
if(!isMounted()){
return ;
}
//有sdcard
//判断是否有缓存文件夹
File dir = new File(CACHE_DIR);
if(!dir.exists()){
//不存在缓存文件夹 创建文件夹用来保存文件
dir.mkdirs();
}
//把文件 数据存到sdcard
File file = new File(dir,getFilename(url));
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//保存文件 方法2
public static void sava2(String url,Bitmap bitmap,int format){
//判断 是否有sdcard
if(!isMounted()){
return ;
}
File dir = new File(CACHE_DIR);
if(!dir.exists()){
dir.mkdirs();
}
//把 文件数据 写到 sdcard
File file = new File(dir,getFilename(url));
try {
FileOutputStream fos = new FileOutputStream(file);
//把图片文件写入缓存
bitmap.compress((format == COMP_JPG?CompressFormat.JPEG:CompressFormat.PNG), 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//读取图片
public static Bitmap readImage(String url){
if(!isMounted()){
return null;
}
File file = new File(CACHE_DIR,getFilename(url));
if(file.exists()){
return BitmapFactory.decodeFile(file.getAbsolutePath());
}
return null;
}
//清空 缓存目录
public void clearCaches(){
File dir = new File(CACHE_DIR);
File[] file_datas = dir.listFiles();
for(File file : file_datas){
file.delete();
}
}
}
==============
MainActivity类
代码
public class MainActivity extends Activity {
private ImageView imageview;
private String url = "http://b.hiphotos.baidu.com/image/pic/item/d1160924ab18972bf5f68cc8e0cd7b899f510ae7.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageview = (ImageView) this.findViewById(R.id.imageview);
//设置默认图片
imageview.setImageResource(R.drawable.ic_launcher);
}
//图片下载 按钮 点击事件 监听
public void Image_Download(View view){
//判断本地是否有图片
Bitmap bitmap = FileUtil.readImage(url);
if(bitmap != null){
imageview.setImageBitmap(bitmap);
}else{
//没有图片 就发送联网请求
new MyAsyncTask().execute(url);
}
}
//联网工具类
public class MyAsyncTask extends AsyncTask<String, Void, byte[]>{
@Override
protected byte[] doInBackground(String... params) {
HttpGet get = new HttpGet(params[0]);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
try {
response = client.execute(get);
if(response.getStatusLine().getStatusCode() == 200){
byte[] data = EntityUtils.toByteArray(response.getEntity());
FileUtil.sava1(params[0], data);
return data;
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(byte[] result) {
super.onPostExecute(result);
if(result != null){
Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
imageview.setImageBitmap(bitmap);
}
}
}
}