首先让APP有联网能力,必须在Manifest设置对应的权限
<uses-permission android:name="android.permission.INTERNET"/>
下载前判断网络状况是否可用:
public NetworkInfo getActiveNetworkInfo() {
ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo;
}
public void checkConnectivity(){
NetworkInfo networkInfo = getActiveNetworkInfo();
if (networkInfo == null || !networkInfo.isConnected()
|| (networkInfo.getType() != ConnectivityManager.TYPE_WIFI
&& networkInfo.getType() != ConnectivityManager.TYPE_MOBILE)) {
//不执行下载,可提示“请检查网络”
}
}
NetworkInfo是ConnectivityService管理的网络实例,Active的网络不为空仅表示该网络已经成功建立,但不能保证这个网络在当时一定可以访问到外网(例如假WiFi或者信号很差的移动网络),只是当做是最基本的网络检查。
确认网络连上后,执行下载和显示图片:
代码中使用HttpURLConnection,从指定url下载一张图片:
private Bitmap downloadImage(URL url) throws IOException {
InputStream stream = null;
HttpURLConnection connection = null;
String result = null;
Bitmap bitmap = null;
try {
connection = (HttpURLConnection) url.openConnection();
// 设置读取超时
connection.setReadTimeout(3000);
// 设置连接超时
connection.setConnectTimeout(3000);
// 设置GET方法
connection.setRequestMethod("GET");
// 开始连接
connection.connect();
//读取连接结果
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) { //服务器是否返回200
throw new IOException("HTTP error code: " + responseCode);
}
stream = connection.getInputStream();
if (stream != null) {
// 获取输入流,以读取服务器返回的消息体内容
stream = new BufferedInputStream(connection.getInputStream());
//使用BitmapFactory方法解析出Bitmap
bitmap = BitmapFactory.decodeStream(is);
}
} finally {
// 清理inputStream和Connection
if (stream != null) {
stream.close();
}
if (connection != null) {
connection.disconnect();
}
}
return bitmap;
}
HttpURLConnection对应定义了所有HTTP的状态码,可以用于定位连接问题:
public static final int HTTP_OK = 200;
public static final int HTTP_BAD_REQUEST = 400;
public static final int HTTP_UNAUTHORIZED = 401;
public static final int HTTP_FORBIDDEN = 403;
public static final int HTTP_NOT_FOUND = 404;
public static final int HTTP_INTERNAL_ERROR = 500;
...
效果:
点击Button后下载并显示出图片。
Google sample
Google sample有一个比较好的简单范例,演示如何使用AsyncTask配合HttpURLConnection进行下载:
https://github.com/googlesamples/android-NetworkConnect
如果进行时间较长的下载,可以使用原生提供的AsyncTaskLoader或IntentService类配合。