手机
当前位置:查字典教程网 >编程开发 >安卓软件开发 >android通过http协议获得图片
android通过http协议获得图片
摘要:android通过图片网址获得图片并显示在imageView中。下面就简单的来说明操作过程:首先必须在布局文件中声明imageView控件:...

android通过图片网址获得图片并显示在imageView中。

下面就简单的来说明操作过程:

首先必须在布局文件中声明imageView控件:

<ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

还必须在清单文件中加入访问网络的权限:

<uses-permission android:name="android.permission.INTERNET" />

其次:用一个service类来实现访问http协议,并且获得链接的返回值这个过程:htmlPath是图片的网络地址

public class PageService {
/**@description:获取图片的数据
* @author:Administrator
* @return:byte[]
* @param htmlpath
* @return
* @throws Exception
*/

public static byte[] getImage(String htmlpath) throws Exception {
byte[] imagearray = null;
URL url = new URL(htmlpath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
// conn.setRequestMethod("GET");
conn.connect();
if (conn.getResponseCode() == 200) {
byte[] buffer = new byte[1024];
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
int len = 0;
InputStream inputStream = conn.getInputStream();
while ((len = inputStream.read(buffer)) != -1) {
arrayOutputStream.write(buffer, 0, buffer.length);
}
imagearray = arrayOutputStream.toByteArray();
}
return imagearray;

}
}
最后在activity中启用一个线程来调用这个业务方法,并在handler中对UI进行更新:(必须实现线程否则会出错,这是和3.0版本之前不同的地方)

public class MainActivity extends Activity {
private EditText strpath;
private TextView htmlcontent;
private ImageView imageview;
Handler handler=new Handler(){

@Override
public void handleMessage(Message msg) {
byte[] data=(byte[])msg.obj;
Bitmap image=BitmapFactory.decodeByteArray(data, 0, data.length);
imageview.setImageBitmap(image);}


下面是线程中的内容:

private final class ImageThread extends Thread {

@Override
public void run() {
String htmlpath=strpath.getText().toString();
htmlpath="/img/shouye_b5486898c692066bd2cbaeda86d74448.gif";
byte[] htmlarray=null;
try {
htmlarray=PageService.getImage(htmlpath);
} catch (Exception e) {
e.printStackTrace();
}
Message msg=new Message();
msg.obj=htmlarray;
msg.what=1;
handler.sendMessage(msg);
}

}

最后用点击一个button来触发获取图片的事件:

private final class ButtonClickListener implements View.OnClickListener {

@Override
public void onClick(View v) {
ImageThread thread=new ImageThread();
thread.start();
}
}

好了,介绍完毕。

最后如果获取的内容为html页面的内容的话,如果内容过长,就需要用滚动条来显示:

可以在TextView外面加上ScollView加载滚动条:

<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<TextView
android:id="@+id/htmlcontent"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</ScrollView>

【android通过http协议获得图片】相关文章:

android广播接收者实例

Android开发之线性布局

android+json+php+mysql实现用户反馈功能方法解析

android 放大镜ShapeDrawable妙用分享

Android开场动画实例类Java代码

Android开发之动画实现方法

Android裁剪图片为圆形图片的实现原理与代码

刷新android中的媒体库

Android开发笔记之:Splash的实现详解

Android通话记录备份实现代码

精品推荐
分类导航