和IOS类似,android中的UI界面更新也只能在主线程中操作。
UI布局时需要注意,android线性布局中
<ImageView
android:layout_height="0dp"
android:layout_width="match_parent"
android:id="@+id/iv1"
android:layout_weight="1"
/>
这里将高度设置为0,同时权重设置为1,那么这种情况下,界面就会充满线性布局中,直到碰到下面的控键。
所以android访问网络图片可以分为下面几个步骤:
(1)
private Bitmap getbitmapfromnework(String urlString){
Bitmap mBitmap = null;
HttpURLConnection urlConnection = null;
try {
URL mUrl = new URL(urlString);
urlConnection = (HttpURLConnection) mUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(5000);
urlConnection.connect();
int responsestate = urlConnection.getResponseCode();
if (responsestate == 200) {
//Toast.makeText(getApplicationContext(), "net加载图片", Toast.LENGTH_SHORT).show();
InputStream mInputStream = urlConnection.getInputStream();
mBitmap = BitmapFactory.decodeStream(mInputStream);
Log.i("ss","");
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}finally{
if (urlConnection !=null) {
urlConnection.disconnect();
}
}
return mBitmap;
}
根据当前URL获取加载图片的bitmap
当点击button按钮之后
public void btaction(View v){
Log.i("123","buttonactio");
final String url=mEditText.getText().toString();
new Thread(new Runnable() {
@Override
publicvoid run() {
// TODO Auto-generated method stub
Bitmap mBitmap = getbitmapfromnework(url);
Message message = new Message();
if (mBitmap !=null) {
message.what = 1;
message.obj = mBitmap;
}else {
message.what = 0;
}
mHandler.sendMessage(message);
}
}).start();
}
利用Handle将数据由子线程传递给UI主线程。所有的这里的UI界面更新在Handle中实现
private Handler mHandler = new Handler(){
@Override
publicvoid handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if (msg.what == 1) {
Toast.makeText(getApplicationContext(),"开始加载图片", Toast.LENGTH_SHORT).show();
mImageView.setImageBitmap((Bitmap) msg.obj);
}else {
Toast.makeText(getApplicationContext(),"图片无法加载", Toast.LENGTH_SHORT).show();
}
}
};
这里我们拿到数据流的时候是直接吧数据流转化为bitmap,其实还可以转化为字符串,比如拿到html文件可能里面是文字:我们拿到html文件先转化为字符串之后还可以进一步获取文字的编码解码方式:下面由一个util:参考代码
private String getStringFromInputStream(InputStream is)throws IOException {
ByteArrayOutputStream mbytes = new ByteArrayOutputStream();
byte[] buffer =newbyte[1024];
int len = -1;
while((len = is.read(buffer)) != -1) {
mbytes.write(buffer, 0, len);
}
is.close();
String html = mbytes.toString();
String charset = "utf-8";
if(html.contains("gbk") || html.contains("gb2312")
|| html.contains("GBK") || html.contains("GB2312")) {
charset = "gbk";
}
html = new String(mbytes.toByteArray(), charset);
mbytes.close();
return html;
}