Android中使用ImageView控件显示网络图片

来源:互联网 发布:天狼星期货软件 编辑:程序博客网 时间:2024/04/30 08:55

在android4.0以后的版本中,为了使得主界面流畅,所以设置了不允许在主线程中访问网络,为了安全,又不允许在其它线程中访问控件,这样就造成了ImageView等需要使用网络的控件更新时的问题,本文以Handler+Runnable的方式实现了ImageView控件显示网络图片.



在android4.0之后,如果在主线程中访问网络,会报一个android.os.networkonmainthreadexception的异常.因为在ui线程中访问网络的话,就要等待网络传输完成,期间就会阻塞线程,使界面卡住.


为了访问网络资源,可以开启一个线程,异步加载.但这个新线程又不具有更新控件的能力,所以就需要一个中间人来完成ui线程和网络线程的联系,本文使用的是消息机制,网络线程发送一个消息,ui线程中收到后执行相应工作.

packagecom.example.netimage;
 
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URL;
 
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.app.Activity;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.view.Menu;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.ImageView;
 
publicclass MainActivity extendsActivity {
     
    privateButton b;
    privateEditText et;
    publicImageView iv;
 
    @Override
    protectedvoid onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        b = (Button)this.findViewById(R.id.button1);
        b.setOnClickListener(newButtonOnClickListener());
         
        iv = (ImageView)this.findViewById(R.id.imageView1);
        et = (EditText)this.findViewById(R.id.editText1);
    }
     
    privateHandler handler = newHandler() { 
        publicvoid handleMessage (Message msg) {// 此方法在ui线程运行 
            switch(msg.what) { 
            case1
                iv.setImageBitmap((Bitmap) msg.obj);// iv 显示从网络获取到的logo   
                break;  
            
        
    };
     
    classdownload implementsRunnable{
         
        @Override
        publicvoid run() {
            // TODO Auto-generated method stub
            String path = et.getText().toString();
            try{
                 
                //byte[] data = ImageService.getImage(path);
                URL url = newURL(path);
                HttpURLConnection con = (HttpURLConnection)url.openConnection();
                con.setConnectTimeout(5000);
                con.setRequestMethod("GET");
                con.connect();
                 
                if(con.getResponseCode() == 200){         
                    InputStream is = con.getInputStream();
                    //byte[] data = StreamTool.readStream(is);
                    Bitmap bitmap = BitmapFactory.decodeStream(is);//(data, 0, data.length);
                    handler.obtainMessage(1,bitmap).sendToTarget();
                }
                //Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                //ImageView iv = (ImageView)con.findViewById(R.id.imageView1);
            }catch(Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             
        }
    }
     
    privateclass ButtonOnClickListener implementsView.OnClickListener{
 
        @Override
        publicvoid onClick(View v) {
            // TODO Auto-generated method stub
            newThread(newdownload()).start();
        }
         
    }
 
    @Override
    publicboolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        returntrue;
    }
 
}

0 0