案例1 _网络图片查看器

来源:互联网 发布:大数据平台有哪些 编辑:程序博客网 时间:2024/05/01 09:44

一、任务描述

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


二、任务实现

1、完成效果

运行程序,在网络上找张图片,拷贝其路径,点击浏览按钮(本次实验中,采用固定地址的方式)

2、实验步骤

①、UI设计:如图界面,ImageView水平居中显示,EditText,Button居中显示

②、访问网络,从网络中获取图片

Android2.2模拟器上运行是否正常?

   如果不正常,原因是什么?

若在Android2.2上可以运行了,那么在Android4.0以上模拟器上运行能否正常运行呢?

   若不正常,报什么错误?

③、原因分析

ANRApplication Not Responding):应用程序无响应,如果应用程序不能响应用户输入

的话,系统会显示ANR。主线程也是UI线程本身就干了很多事情,绘制界面响应事件等。如果里面再直接放入一些耗时的操作,如连接网络进行IO操作,就会阻塞主线程,带来较差的用户体验。

④、修改程序

⑤Android消息处理机制

⑥进一步修改程序


3、核心代码

MainActivity.java

@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imageview = (ImageView) findViewById(R.id.iv);etUrl = (EditText) findViewById(R.id.etPath);handler = new Handler(){public void handleMessage(android.os.Message msg) {switch(msg.what){case SHOW_IMAGE:Bitmap bitmap = (Bitmap) msg.obj;imageview.setImageBitmap(bitmap);break;default:break;}};};}public void showImage(View view){ final String path = etUrl.getText().toString();if(TextUtils.isEmpty(path)){Toast.makeText(this, "图片路径不能为空", Toast.LENGTH_SHORT).show();}else{new Thread(){public void run(){//连接服务器try{URL url = new URL(path);//发出http请求HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();httpURLConnection.setRequestMethod("GET");//设置连接超时时间httpURLConnection.setConnectTimeout(5000);int responsecode = httpURLConnection.getResponseCode();if(responsecode == 200){InputStream is = httpURLConnection.getInputStream();Bitmap bitmap = BitmapFactory.decodeStream(is);Message msg = new Message();msg.what = SHOW_IMAGE;msg.obj=bitmap;handler.sendMessage(msg);//imageview.setImageBitmap(bitmap);}else{Toast.makeText(MainActivity.this, "图片显示失败", Toast.LENGTH_SHORT).show();}} catch (MalformedURLException e){e.printStackTrace();}catch (IOException e) {e.printStackTrace();}};}.start();}}

在AndroidManifest.xml中增加访问网络的权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="cn.bzu.tong.internetimage"    android:versionCode="1"    android:versionName="1.0" >    ... <uses-permission android:name="android.permission.INTERNET" />    ... 
</manifest>

4、体会感悟

要学会Bitmap、handler等的使用,要熟悉使用网络的编程手法。

                                             
0 0
原创粉丝点击