获取图片的网络请求

XML中的代码:

<Button
        android:id="@+id/button"
        android:text="获取图片"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <ImageView
        android:id="@+id/image"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_below="@id/button"
        />

Activity中的代码:

private String lujing="http://img.netbian.com/file/2017/0216/39f11cd4d8270ec2c534dff72c9c6a83.jpg";
    private final int UPDATE_UI=1;
    private ImageView image;
    private Button button;
    @SuppressLint("HandlerLeak")
    private Handler hander=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_UI:
                    image.setImageBitmap((Bitmap) msg.obj);
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = findViewById(R.id.image);
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(
                        new Runnable() {
                            @Override
                            public void run() {
                                huoqu();
                            }
                        }
                ).start();
            }
        });
    }
    private void huoqu(){
        try {
            URL url=new URL(lujing);
            HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            //P判断网络类型
            int shijian;
            if (wangluo()){
                shijian=10000;
            }else{
                shijian=5000;
            }
            urlConnection.setReadTimeout(shijian);
            urlConnection.setConnectTimeout(shijian);
            int responseCode = urlConnection.getResponseCode();
            if (responseCode==200){
                Bitmap bitmap = BitmapFactory.decodeStream(urlConnection.getInputStream());
                hander.sendMessage(hander.obtainMessage(UPDATE_UI,bitmap));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //判断是否是手机网络
    private boolean wangluo(){
        ConnectivityManager cm= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
        return activeNetworkInfo.getType()==ConnectivityManager.TYPE_MOBILE;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值