Android Studio —— 下载网络图片显示

效果


简介

     加入线程进行下载,下载完毕后显示。

源码

CSDN下载源码


代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        tools:layout_editor_absoluteX="20dp">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="网络图片URL" />

        <EditText
            android:id="@+id/URL"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName"
            android:text="https://c-ssl.duitang.com/uploads/item/201608/03/20160803105616_MkGNs.jpeg" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="getImage"
            android:text="下载"
            tools:ignore="MissingConstraints" />
    </LinearLayout>

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="400dp"
        android:layout_height="400dp"
        android:layout_marginTop="100dp"
        android:src="@drawable/test" />


</LinearLayout>
package com.example.jxdapplication;

import android.app.Activity;

 import android.app.ProgressDialog;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
 import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
 import android.widget.Toast;

 import androidx.appcompat.app.AppCompatActivity;

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

 import java.net.URL;

public class MainActivity extends AppCompatActivity {

    // 图片地址
    //private final String PATH = "https://img2.baidu.com/it/u=2933352910,1027168372&fm=26&fmt=auto";
    private String PATH = "";

    // 成功标识
    private final int SUCCESS = 200;

    // 失败标识
    private final int ERROR = 404;

    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.imageView2);
    }

    /**
     * 定义Handler,用于接收子线程发过来的信息
     */
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCESS:
                    imageView.setImageBitmap((Bitmap) msg.obj);
                    break;
                case ERROR:
                    Toast.makeText(MainActivity.this, "下载失败,请检查原因", Toast.LENGTH_LONG).show();
                    break;
            }

            if (null != progressDialog)
                progressDialog.dismiss();
        }
    };

    private ProgressDialog progressDialog = null;

    /**
     * 获取图片 按钮
     * @param view
     */
    public void getImage(View view) {
        EditText url = findViewById(R.id.URL);
        PATH = url.getText().toString();

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("正在下载...");
        progressDialog.show();

        // 开启子线程 下载图片
        /**
         * 执行此方法才去启动线程下载
         */
        new Thread(new DownloadImage()).start();
    }

    class DownloadImage implements Runnable {

        /**
         * 发送Handler
         */
        public void showUiImage(int responseCode, Bitmap bitmap) {
            Message message = mHandler.obtainMessage(responseCode); // 拿系统消息池的消息, 不要 new Message();
            message.obj = bitmap;
            mHandler.sendMessageDelayed(message, 2000);
        }

        @Override
        public void run() {
            try {
                // 封装成网络地址
                URL url = new URL(PATH);

                // 打开一个连接
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

                // 设置连接时长
                httpURLConnection.setConnectTimeout(10000);

                // 设置请求方式
                httpURLConnection.setRequestMethod("GET");

                /**
                 * 注意:⚠️ 不要肤浅的任务 打开连接对象 设置连接时长 设置请求方式 就向服务器发送Http请求了
                 *          是要执行httpURLConnection.getResponseCode()才会向服务器发送Http请求
                 */
                if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    // 得到服务器返回过来的流对象
                    InputStream inputStream = httpURLConnection.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    showUiImage(SUCCESS, bitmap);
                } else {
                    showUiImage(ERROR, null);
                }

            } catch (Exception e) {
                e.printStackTrace();
                showUiImage(ERROR, null);
            }
        }
    }
}


注意

     * AndroidManifest.xml 配置网络权限

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


参考文章

     ANDROID-下载网上图片

关注

笔者 - jxd

微信公众号搜索 “码农总动员” 或 微信扫描下方二维码,了解更多你不知道的XX,O(∩_∩)O

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

信必诺

嗨,支持下哥们呗。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值