android 显示 网络图片

<uses-permission android:name="android.permission.INTERNET" />

首先在AndroidManifest.xml添加网络权限

这是java代码

public class MainActivity extends Activity {
 
    private ImageView imageView;
    private String picUrl = "http://a1.eoe.cn/news/2013/0104/20130104080020231.jpg";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imageView);
        getBitmap(picUrl);
    }
 
    Handler handler = new Handler() {
 
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 1:
                imageView.setImageBitmap(bitmap);
                break;
            default:
                break;
            }
            super.handleMessage(msg);
        }
 
    };
    protected Bitmap bitmap;
 
    private void getBitmap(final String url) {
        Thread thread = new Thread() {
 
            @Override
            public void run() {
                URL myFileURL;
                try {
                    myFileURL = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) myFileURL
                            .openConnection();
                    conn.setConnectTimeout(6 * 1000);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                    Message message = handler.obtainMessage();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.run();
            }
        };
        thread.start();
        thread = null;
    }
 
}

你可能感兴趣的:(android,网络图片)