权限 <uses-permission android:name="android.permission.INTERNET" />
package com.example.net;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity2 extends Activity {
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap((Bitmap) msg.obj);
break;
case 2:
//toast也需要在主线程中更新
Toast.makeText(MainActivity2.this,"网络出错",Toast.LENGTH_LONG).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v) {
new Thread() {
@Override
public void run() {
Bitmap bm = null;
//图片的地址
String path = "http://192.168.0.101/news/images/image1.jpg";
//获取缓存文件(getCahcheDir()获取在data/data/包名/cache下的文件)
File file = new File(getCacheDir(), getFileName(path));
Message msg = handler.obtainMessage();
if (file.exists()) {
System.out.println("读取缓存..");
//file.getAbsolutePath()获取文件的绝对路径
bm = BitmapFactory.decodeFile(file.getAbsolutePath());
msg.obj = bm;
msg.what=1;
} else {
try {
System.out.println("网络下载的..");
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.connect();
if (conn.getResponseCode() == 200) {
FileOutputStream fos = new FileOutputStream(file);
InputStream is = conn.getInputStream();
int len = 0;
byte[] b = new byte[1024];
//将获取的图片写入缓存文件夹中
while ((len = is.read(b)) != -1) {
fos.write(b, 0, len);
}
//读取从缓存文件夹下的文件
bm = BitmapFactory.decodeFile(file.getAbsolutePath());
msg.obj = bm;
msg.what=1;
}else{
//网络读取出错
msg.what=2;
}
} catch (Exception e) {
e.printStackTrace();
}
}
handler.sendMessage(msg);
}
}.start();
}
/**
* 截取文件名
* @param path
* @return
*/
public String getFileName(String path) {
int index = path.lastIndexOf("/");
return path.substring(index, path.length());
}
}
布局
<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">
<Button
android:onClick="click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载图片" />
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>