网络通信之网络图片获取 并显示屏幕上

本文介绍如何在Android应用中通过输入图片路径,利用自定义工具类从网络获取图片数据,并将其显示在ImageView上。

1.主MainActivity 类代码如下:

public class MainActivity extends Activity {
private EditText editText;
private ImageView imageView;
private static final String TAG="MainActivity";
private Button button;
private byte []data;

private Handler handler = new Handler() { 
public void handleMessage(Message msg) { 
switch (msg.what) { 
case 0: 
Bitmap bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(bitmap);
break; 
} 
}; 
}; 


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

setContentView(R.layout.activity_main);
editText =(EditText) findViewById(R.id.path);
imageView=(ImageView) findViewById(R.id.ImageView); 
button=(Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {	
@Override
public void onClick(View v) {
new Thread() { 
@Override 
public void run() { 
// TODO Auto-generated method stub 
super.run(); 

String path=editText.getText().toString();
try {
data=NetTool.getImage(path);	

} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(MainActivity.this, "获取图片失败", 1).show();
e.printStackTrace();
}	
Message msg = handler.obtainMessage(); 
msg.what = 0; 
handler.sendMessage(msg); 
} 
}.start(); 

}
});
}
}

2.NetTool类代码:

public class NetTool {
	public static byte[] getImage(String path) throws Exception{
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if(conn.getResponseCode() == 200){
			InputStream inStream = conn.getInputStream();
			return read(inStream);
		}
		return null;
	}
	
	public static byte[] read(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while( (len = inStream.read(buffer)) != -1){
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}

}

3.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/path" />

    <EditText
        android:id="@+id/path"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/aa" >
    </EditText>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button" >
    </Button>

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

</LinearLayout>

4.string.xml

<resources>
    <string name="app_name">GetPicture</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
    <string name="path">路径</string>
    <string name="button">获取图片</string>
    <string name="aa">http://a.hiphotos.baidu.com/image/pic/item/94cad1c8a786c9178f04af6fca3d70cf3bc75765.jpg</string>  
</resources>
5.记得在清单文件里加权限:

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

运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值