LogCat: java,lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
代码
public class MainActivity extends Activity {
Handler handler = new Handler(){
//只要消息列队里面有消息,此方法就调用
public void handleMessage(android.os.Message msg) {
//8,显示
ImageView iv = (ImageView) findViewById(R.id.iv);
//把图片设置进ListView
iv.setImageBitmap((Bitmap) msg.obj);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v){
Thread t = new Thread(){
@Override
public void run() {
//请求网址,获取图片
//1,确认网址
String path = "http://192.168.0.102:8080/mm.jpg";
try {
//2,获取URL对象
URL url = new URL(path);
//3,获取连接对象,此时还未建立连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//4,初始化连接对象
conn.setRequestMethod("GET"); //设置请求方法
conn.setReadTimeout(5000); //设置读取超时
conn.setConnectTimeout(5000); //设置连接超时
//5,与服务器建立连接
conn.connect();
//判断是否请求成功,通过请求码对比
if(conn.getReadTimeout() == 200){
//6,拿到服务器返回的流,客户请求的数据就保存在流中
InputStream is = conn.getInputStream();
//7,从流中读取数据,构造成一个图片
Bitmap bm = BitmapFactory.decodeStream(is);
//创建消息对象
Message msg = new Message();
//将bm放入消息中
msg.obj = bm;
//子线程向列队消息发送消息
handler.sendMessage(msg);
}else{
Toast.makeText(MainActivity.this, "请求失败", 0).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
}