获取网络上图片

来源:互联网 发布:手机淘宝网怎么发链接 编辑:程序博客网 时间:2024/04/30 19:31
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private ImageView imageView;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0){
                Bitmap bitmap = (Bitmap) msg.obj;
                //设置显示
                imageView.setImageBitmap(bitmap);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //快捷键:...alt+enter....ctrl+alt+F抽取成员变量
        imageView = (ImageView) findViewById(R.id.image_view);
    }

    /**
     * 获取图片的点击事件
     *
     * 1.android.os.NetworkOnMainThreadException网络操作放在了主线程....android中所有的耗时操作应该放在子线程
     *
     * 网络访问的操作,,io流读取大文件,,,,android规定主线程被阻塞超过5秒钟就会出现ANR的异常
     *
     * ANR = application not response应用程序无响应
     *
     * 2.java.lang.SecurityException安全异常: Permission denied拒绝了权限 (missing INTERNET permission?)
     *
     * 3.android.view.ViewRootImpl$CalledFromWrongThreadException方法在错误的线程被调用的异常:
     * Only the original thread主线程 that created a view hierarchy can touch its views只有主线程才能更新UI
     *
     * @param view
     */
    public void getPic(View view){

        new Thread(){
            @Override
            public void run() {
                //1.要有图片的地址
                String path = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1503854327078&di=08bdf32f7a117deafd580ca006b80a67&imgtype=0&src=http%3A%2F%2Fnews.k618.cn%2Fpic%2Fdmyx%2F201505%2FW020150501335817970176.jpg";

                //2.把一个字符串类型的地址转换为网络上的路径
                try {
                    URL url = new URL(path);

                    //3.使用url路径打开一个连接....使用的是HttpURLConnection,,,对父类进行了扩展,,,遵循http协议
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //4.对connnection进行设置
                    //4.1设置请求方式...默认是get方式,并且get方式是使用最多的
                    connection.setRequestMethod("GET");//POST
                    connection.setConnectTimeout(5000);//设置连接超时
                    connection.setReadTimeout(5000);//设置读取超时

                    //5.获取
                    //5.1获取一个响应的状态码200请求成功,,,404资源找不到,,500服务器内部异常,,,302重定向,,,304/307使用缓存
                    int responseCode = connection.getResponseCode();
                    if (responseCode == 200){//请求成功
                        //5.2获取服务器返回的字节流
                        InputStream inputStream = connection.getInputStream();//此时这个流里面是一张图片

                        //把流转换为一张图片....encode编码,,,,decode解码
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);


                        //imageView.setImageBitmap(bitmap);//更新界面的操作应该放在主线程
                        Message message = Message.obtain();
                        message.what = 0;
                        message.obj = bitmap;
                        handler.sendMessage(message);

                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();




    }
}

原创粉丝点击