android studio网络图片浏览器
.xml
<?xml version="1.0" encoding="utf-8"?>
,java
package com.example.abc.imageview;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends ActionBarActivity {
protected static final int CHANGE_UI = 1;
protected static final int ERROR = 2;
private EditText et_path;
private ImageView ivPic;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg){
if (msg.what == CHANGE_UI){
Bitmap bitmap = (Bitmap) msg.obj;
ivPic.setImageBitmap(bitmap);
}else if (msg.what == ERROR){
Toast.makeText(MainActivity.this,“显示图片错误”, Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText) findViewById(R.id.et_path);
ivPic = (ImageView) findViewById(R.id.iv_pic);
}
public void click(View view){
final String path = et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)){
Toast.makeText(this,“图片路径不能为空”, Toast.LENGTH_SHORT).show();
}else {
new Thread() {
private HttpURLConnection conn;
private Bitmap bitmap;
public void run() { try { URL url = new URL(path); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); int code = conn.getResponseCode(); if (code == 200) { InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); Message msg = new Message(); msg.what = CHANGE_UI; msg.obj = bitmap; handler.sendMessage(msg); } else { Message msg = new Message(); msg.what = ERROR; handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); Message msg = new Message(); msg.what = ERROR; handler.sendMessage(msg); } conn.disconnect(); } }.start(); }}
}
更多相关文章
- Android的Textview里面夹杂图片
- Android(安卓)图片添加水印
- android 拍照和上传
- android 扫描sdcard下的图片
- Android(安卓)自定义Ratingbar
- android支付宝 KeyFactory PrivateKey
- EditView中插入图片
- HttpHuiApplication--下载图片url,HttpURLConnection,简单版
- clock时钟