Android请求网络图片得两种方法

Android请求网络图片得两种方法

记得申请网络权限

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

mainActivity.java


import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;

import fengxing.primer.textlink.R;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 异步线程:
 *      Android开发的一大禁忌就是: 禁止在主线程执行耗时操作
 *
 *      AsyncTask的内部实现就是 Thread + Handler
 */
public class AsynctaskActivity extends AppCompatActivity {

    private ImageView iv_async_image;
    private Button bt_async_task;
    private Button bt_async_task2;
    private static final String TAG = "AsynctaskActivity";
    private final int DOWNLOAD_IMAGE = 1;
    private int imageUrlIndex = 0;
    private ProgressDialog progressDialog;
    private String[] imageUrl = new String[]{
            "https://i.loli.net/2019/10/13/Qn1DWLMg9SUeywF.jpg",
            "https://i.loli.net/2019/10/13/BZHl48wLozvIj2N.jpg",
            "https://i.loli.net/2019/10/13/MKQ9VOxqghC8LvF.png"
    };

    /**
     * 第一种:使用handler更新布局
     */
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case DOWNLOAD_IMAGE:
                {
                    byte[] data = (byte[]) msg.obj;
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length);
                    iv_async_image.setImageBitmap(bitmap);
                    progressDialog.dismiss();
                }
                break;
                default:
                    break;
            }
        }
    };
    private Bitmap b ;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_asynctask);
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("提示:");
        progressDialog.setMessage("正在下载,请稍后...");

        bt_async_task =findViewById(R.id.bt_async_task);
        bt_async_task2 =findViewById(R.id.bt_async_task2);
        iv_async_image = findViewById(R.id.iv_async_image);

        bt_async_task.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadNetImageByHandle();
            }
        });

        bt_async_task2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (++imageUrlIndex>imageUrl.length-1){
                    imageUrlIndex=0;
                }
                new MyTask().execute(imageUrl[imageUrlIndex]);
            }
        });

    }

    /**
     * 参数一:网络路径
     * 参数二:进度刻度
     * 参数三:返回结果
     */
    class MyTask extends AsyncTask<String,Void,Bitmap>{

        /**
         * 任务执行之前的操作
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();
        }

        /**
         * 完成耗时操作
         * @param strings
         * @return
         */
        @Override
        protected Bitmap doInBackground(String... strings) {

            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(strings[0]).build();
            Response response = null;
            Bitmap bitmap=null;
            try {
                response = client.newCall(request).execute();
                byte[] data = response.body().bytes();
                bitmap = BitmapFactory.decodeByteArray(data,0,data.length);
            } catch (IOException e) {
                e.printStackTrace();
            }

            return bitmap;
        }

        /**
         * 更新ui操作
         * @param bitmap
         */
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            Toast.makeText(AsynctaskActivity.this,""+imageUrlIndex,Toast.LENGTH_SHORT).show();
            iv_async_image.setImageBitmap(bitmap);
            progressDialog.dismiss();
        }
    }

    private void loadNetImageByHandle() {
        progressDialog.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (++imageUrlIndex>imageUrl.length-1){
                    imageUrlIndex=0;
                }

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(imageUrl[imageUrlIndex]).build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d(TAG, "onFailure: 失败");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.d(TAG, "onResponse: 成功");

                        //返回数据
                        byte[] data = response.body().bytes();

                        Message message = new Message();
                        message.obj = data;
                        message.what = DOWNLOAD_IMAGE;
                        handler.sendMessage(message);
                    }
                });

            }
        }).start();
    }
}

layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">


    <ImageView
        android:layout_centerInParent="true"
        android:src="@drawable/net"
        android:id="@+id/iv_async_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </ImageView>


    <Button
        android:background="@drawable/round_button"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/iv_async_image"
        android:text="handle"
        android:id="@+id/bt_async_task"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </Button>

    <Button
        android:background="@drawable/round_button"
        android:layout_marginTop="10dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/bt_async_task"
        android:text="AsyncTask"
        android:id="@+id/bt_async_task2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Button>


</RelativeLayout>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值