1、 Android获取网络图片
下面来写一个小程序来说明:

首先是资源文件:

<resources>

<string name="app_name">Net</string>

<string name="btn_text">显示网络数据</string>

<string name="error">下载图片失败</string>

</resources>

然后就是布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

<Button

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/btn_text"

android:id="@+id/showImageBtn"/>

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"/>

</LinearLayout>

在就是:Activity

public class NetActivity extends Activity implements OnClickListener {

Button btn;

ImageView imgView;

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.img_layout);

findViews();

}

private void findViews() {

btn = (Button) this.findViewById(R.id.showImageBtn);

imgView = (ImageView) this.findViewById(R.id.imageView);

btn.setOnClickListener(this);

}

public void onClick(View v) {

// 获取图片的地址

String path=

"http://img.nie.163.com/images/2011/12/20/2011-12-20_144791.jpg";

try {

byte data[] = ImageService.getImageData(path);

Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

imgView.setImageBitmap(bitmap);

} catch (Exception e) {

Log.e("TAG",e.toString());

Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();

}

}

}

最后是:ImageService类

public class ImageService {

public static byte[] getImageData(String path)throws Exception{

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");

conn.setConnectTimeout(5000);

InputStream inStream = conn.getInputStream();

ByteArrayOutputStream bos = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len = 0;

while((len=inStream.read(buffer))!=-1){

bos.write(buffer,0,len);

}

byte[] data = bos.toByteArray();

return data;

}

}

效果如图:


更多相关文章

  1. Android studio 不能预览布局文件
  2. Android Studio开发Android(一)——build.gradle文件详解
  3. 读取android根目录下的文件或文件夹
  4. Android选择本地视频文件
  5. android 调用相机拍照 并缩放切割图片
  6. Android使用DefaultHttpClient访问Wap网络
  7. 从J2EE转向Android的第九天-----文件存储

随机推荐

  1. Android(安卓)系统启动流程解析-从开机到
  2. Android(安卓)studio 使用原生自带Downlo
  3. Android(安卓)内存查看常用命令
  4. Android(安卓)app如何正确读写系统sys设
  5. 字节跳动屏幕适配方案解读
  6. Android(安卓)wifi 信号强度单位 dbm
  7. Android屏幕录制并转换gif
  8. android校园二手市场客户端+服务端源代码
  9. Android通过 SharedPreference 实现用户
  10. android widget 开发实例 : 桌面便签程序