// 创建一个新线程,用于从网络上获取文件
new Thread(new Runnable() {
public void run() {try {
URL url = new URL(“http://img0.bdstatic.com/img/image/shouye/sheying0717.jpg”); // 创建下载地址对应的URL对象
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection(); // 创建一个连接
InputStream is = urlConn.getInputStream(); // 获取输入流对象
if (is != null) {
String expandName = sourceUrl.substring(
sourceUrl.lastIndexOf(".") + 1,
sourceUrl.length()).toLowerCase(); // 获取文件的扩展名
String fileName = sourceUrl.substring(
sourceUrl.lastIndexOf("/") + 1,
sourceUrl.lastIndexOf(".")); // 获取文件名
File file = new File("/sdcard/"
+ fileName + "." + expandName); // 在SD卡上创建文件
FileOutputStream fos = new FileOutputStream(
file); // 创建一个文件输出流对象
byte buf[] = new byte[128];// 创建一个字节数组
// 读取文件到输出流对象中
while (true) {
int numread = is.read(buf);
if (numread <= 0) {
break;
} else {
fos.write(buf, 0, numread);
}
}
}
is.close(); // 关闭输入流对象
urlConn.disconnect(); // 关闭连接
flag = true;
} catch (MalformedURLException e) {
e.printStackTrace(); // 输出异常信息
flag = false;
} catch (IOException e) {
e.printStackTrace(); // 输出异常信息
String message = e.getMessage();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
flag = false;
}
Message m = handler.obtainMessage(); // 获取一个Message
handler.sendMessage(m); // 发送消息
}
}).start(); // 开启线程