import
java.io.InputStream;
import
java.net.HttpURLConnection;
import
java.net.URL;
import
android.os.Bundle;
import
android.os.Handler;
import
android.os.Message;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.ImageView;
import
android.widget.Toast;
import
android.app.Activity;
import
android.graphics.Bitmap;
import
android.graphics.BitmapFactory;
/**
* Handler + Thread 实现异步加载图片
* @author ZHF
*
*/
public
class
MainActivity
extends
Activity {
private
static
final
int
MSG_SUCCESS =
0
;
private
static
final
int
MSG_FAILURE =
1
;
public
static
final
String IMG_URL =
"http://images.51cto.com/images/index/Images/Logo.gi"
;
Button btn_handler;
ImageView imageView;
private
DownloadImgThread downloadImgThread;
private
Handler mHandler =
new
Handler(){
public
void
handleMessage(Message msg) {
switch
(msg.what) {
case
MSG_SUCCESS:
imageView.setImageBitmap((Bitmap)msg.obj);
break
;
case
MSG_FAILURE:
Toast.makeText(MainActivity.
this
,
"获取图片失败"
, Toast.LENGTH_LONG);
break
;
}
};
};
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)
this
.findViewById(R.id.imageView);
btn_handler = (Button)
this
.findViewById(R.id.btn_handler);
btn_handler.setOnClickListener(
new
OnClickListener() {
@Override
public
void
onClick(View v) {
downloadImgThread =
new
DownloadImgThread();
downloadImgThread.start();
}
});
}
/**图片下载线程**/
private
class
DownloadImgThread
extends
Thread{
HttpURLConnection conn;
InputStream inputStream;
Bitmap imgBitmap;
@Override
public
void
run() {
try
{
URL url =
new
URL(IMG_URL);
if
(url !=
null
) {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(
2000
);
connection.setDoInput(
true
);
connection.setRequestMethod(
"GET"
);
int
code = connection.getResponseCode();
if
(
200
== code) {
inputStream = connection.getInputStream();
imgBitmap = BitmapFactory.decodeStream(inputStream);
mHandler.obtainMessage(MSG_SUCCESS,imgBitmap).sendToTarget();
}
else
{
mHandler.obtainMessage(MSG_FAILURE).sendToTarget();
}
}
}
catch
(Exception e) {
e.printStackTrace();
}
}
}
}