一:Mainactivity
public class MainActivity extends AppCompatActivity{
protected static final int CHANGE_UI=1;
protected static final int ERROR=2;
private EditText et_path;
private ImageView iv;
//主线程创建消息处理器
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==CHANGE_UI){
Bitmap bitmap=(Bitmap) msg.obj;
iv.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);
iv=(ImageView)findViewById(R.id.iv);
}
public void click(View view){
final String path=et_path.getText().toString().trim();
if(TextUtils.isEmpty(path)){//如果path为空
Toast.makeText(this,"图片路径不能为空",Toast.LENGTH_SHORT).show();
}else {
//子线程连接服务器,发送请求
new Thread(){
private HttpURLConnection conn;
private Bitmap bitmap;
public void run(){
//连接服务器 get请求,获取图片
try{
//创建URL对象
URL url=new URL(path);
//根据url发送http的请求
conn=(HttpURLConnection) url.openConnection();
//设置请求的方式
conn.setRequestMethod("GET");
//设置超时时间
conn.setConnectTimeout(5000);
conn.setRequestProperty("User-Agent","Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1;"+"SV1;.NET4.0C;.NET CLR 2.0.50727;"+".NET CLR 3.0.4506.2152;.NET CLR 3.5.30729;Shuame)");
int code=conn.getResponseCode();
if(code==200){
//获取输入流
InputStream is=conn.getInputStream();
//将流转换成Bitmap对象
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);
}
};
}.start();
}
}
}
二、布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="cn.edu.bzu.a18lab12.MainActivity">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1000"
android:background="@mipmap/ic_launcher"
android:id="@+id/iv" />
<EditText
android:hint="请输入图片的路径:"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:id="@+id/et_path"/>
<Button
android:text="浏览"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="click" />
</LinearLayout>
因为没有模拟器所以无法演示程序