实现效果图
逻辑代码--MainActivity
package com.example.week4_day2_handledemo1;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
//声明显示图片的的ImageView
private ImageView image;
private Button btn;
//要下载的图片得地址
private static final String path="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superplus/img/logo_white_ee663702.png";
//声明进度框
private ProgressDialog dialog;
private static final int OK=1;
private static final int ERROR=OK+1;
//handle接收子线程发送的信息,更新UI
private Handler handler = new Handler() {
//重写handleMessage方法
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case OK:
Bitmap bm = (Bitmap) msg.obj;
image.setImageBitmap(bm);
//图片显示时关闭进度框
dialog.dismiss();
break;
case ERROR:
String str = (String) msg.obj;
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
dialog.dismiss();
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.image);
btn = (Button) findViewById(R.id.btn);
//得到进度框的对象
dialog=new ProgressDialog(MainActivity.this);
//设置进度框
dialog.setTitle("下载图片");
dialog.setIcon(R.drawable.ic_launcher);
dialog.setMessage("正在下载图片.............");
//注册监听器
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//显示进度框
dialog.show();
/**
* 子线程
*/
new Thread() {
public void run() {
/**
* 判断是否有网络
*/
if(HttpIntenet.isNet(getApplicationContext())){
//调用网络下载,返回字节数组
byte[] buffer = HttpIntenet.httpintent(path);
if(buffer!=null&&buffer.length>0){
Bitmap maBitmap=BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
// 得到消息对象
Message map = Message.obtain();
map.obj=maBitmap;
map.what=OK;
// 将消息传递过去
handler.sendMessage(map);
}
}else{
Message message=Message.obtain();
message.obj="世界上最遥远的距离就是没网络";
message.what=ERROR;
//传递消息
handler.sendMessage(message);
}
};
}.start();
}
});
}
}
网络下载图片工具类
package com.example.week4_day2_handledemo1;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
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 android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class HttpIntenet {
/**
* 判断是否有网络
*/
public static boolean isNet(Context context) {
// 得到网络管理者
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null) {
return true;
} else {
return false;
}
}
/**
* 开启网络连接,下载图片
*
* @param path
* @return
*/
public static byte[] httpintent(String path) {
HttpClient httpclient = new DefaultHttpClient(); // 创建http请求客户端
HttpGet httpget = new HttpGet(path); // 设置get请求
ByteArrayOutputStream out = new ByteArrayOutputStream();// 把得到的内容放入输出流中
try {
HttpResponse httpresponse = httpclient.execute(httpget);// 执行请求
if (httpresponse.getStatusLine().getStatusCode() == 200) { // 判断网络请求是否成功
InputStream inputStream = httpresponse.getEntity()// 得到内容--输入流
.getContent();
byte[] buffer = new byte[1024];
int tmp = 0;
while ((tmp = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, tmp);// 读取tmp字节存入输出流中
out.flush();// 刷新流
}
}
return out.toByteArray();// 返回一个byte[]数据
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
布局文件
<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"
>
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#00ff00"
/>
<Button
android:id="@+id/btn"
android:layout_below="@id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击下载图片"/>
</RelativeLayout>
配置文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.week4_day2_handledemo1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<!-- 获取网络权限 和 网络状态权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.week4_day2_handledemo1.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>