展会信息港展会大全

android开发通过http协议获得图片
来源:互联网   发布日期:2016-01-19 12:18:23   浏览:2458次  

导读:android通过图片网址获得图片并显示在imageView中。下面就简单的来说明操作过程:首先必须在布局文件中声明imageView控件:ImageViewandroid:id=@+id imageandroid:layout_width=fill_parentandroid:layout ...

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="http://www.baidu.com/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>

赞助本站

人工智能实验室

相关热词: http协议 android开发

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港