您的位置:首页 > 理论基础 > 计算机网络

查看网络图片

2015-07-03 08:55 441 查看
本次试验内容:

输入网络图片的地址,点击浏览按钮可以显示网络中的图片。

实验分为三个步骤实现:

**1.从输入框中获取URL,在主线程中创建消息处理器,发送http请求。

2.在创建的子线程中连接服务器利用get获取图片;

3.在主线程中捕获从子线程中发送回来的消息,并解析数据,更新UI。**

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
protected static final int CHANGE_UI = 1; //更改UI
protected static final int ERROR = 2;
private EditText et_path;
private ImageView iView;
//1.在主线程中创建消息处理器
private Handler handler=new Handler(){

//获得子线程传过来的消息进行 UI更新
public void handleMessage(android.os.Message msg) {
//重写handlemessage方法
if (msg.what==CHANGE_UI) {
Bitmap bitmap= (Bitmap)msg.obj;
iView.setImageBitmap(bitmap);
}
else if (msg.what==ERROR) {
Toast.makeText(MainActivity.this,"获取图片失败", 0).show();
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path=(EditText)findViewById(R.id.et);
iView=(ImageView)findViewById(R.id.iv);
}
public void onClick(View view) {
//获取文件路径
final String path=et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(MainActivity.this,"图片路径不为空", 0).show();
} else {
new Thread(){
public void run() {
//连接服务器get获取图片
try {
URL url=new URL(path);
HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection(); //发送http请求
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5000);
int code=urlConnection.getResponseCode();
if (code==200) {
InputStream iStream=urlConnection.getInputStream();
Bitmap bitmap=BitmapFactory.decodeStream(iStream); //把流转换为Bitmap
iView.setImageBitmap(bitmap);
//2. 子线程到主线程更改UI,内容bitmap
Message msg=new Message();
msg.what=CHANGE_UI;
msg.obj=bitmap;
handler.sendMessage(msg);
}else {
Toast.makeText(MainActivity.this, "显示图片失败", 0).show();
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);
//Toast.makeText(MainActivity.this, "获取图片失败", 0).show();
}
}
}.start();
}

}

}


添加网络访问权限:

Android2.X直接在主线程中获取服务器数据,这样如果任务变多,主线程就会崩溃 4.0之后舍弃此方法。Android4.0新开辟子线程,在子线程中访问服务器获取数据。




试验到这里结束了,谢谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: