okhttp image loading

Complete the dependency addition according to the previous article: Click to open the link


Drawing the main interface layout


<?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:orientation="vertical"
    android:layout_height="match_parent"
    tools:context="com.example.yls.demoa.MainActivity">

    <Button
        android:id="@+id/btn_start"
        android:text="click"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Initialize the control and set the click event

    private Button button;
    private ImageView imageView;
    private Handler handler;

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

        initViews();

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


Finish writing the getLoadImg() method

private void getLoadImg() {
        String url = "http://crp.gdcp.cn/data/uploadData/2018/440666666/0303//201711972628361.png";
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("Mainactivity", e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream inputStream = response.body().byteStream();
                // display on the page
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                Message message = new Message();
                message.what = GET_IMG;
                message.obj = bitmap;
                handler.sendMessage(message);

                // save local
//                String filePath = getFilesDir().getAbsolutePath()+ File.separator+"down.jpg";
//                FileOutputStream fileOutputStream = new FileOutputStream(filePath);
//                byte[] buffer = new byte[2048];
// int len ​​= 0;
//                while ((len = inputStream.read(buffer)) != -1){
//                    fileOutputStream.write(buffer,0,len);
//                }
//                fileOutputStream.flush();
//                Log.e("mainActivity","save end");
            }
        });
    }




The modified method adopts two ways to complete the loading and downloading functions of pictures, and the message sending mechanism should also be completed in the handle.

Send the information of the downloaded image to the main thread. The following is the initialization code of the handle:


imageView = findViewById(R.id.image);
        button = findViewById(R.id.btn_start);
       
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
               
                if (message.what == GET_IMG){
                    Bitmap bitmap = (Bitmap) message.obj;
                    imageView.setVisibility(View.VISIBLE);
                    imageView.setImageBitmap(bitmap);
                }
                return false;
            }
        });



Accept the image object as Bitmap class, and set the display mode of the image according to setVisibility()   and  setImageBitmap()

Finally, check if you have added network access before running, reducing unnecessary trouble.




Run the program and see the results


(The picture is the picture on the official website of my school, the picture is the teacher of our school, please do not reprint it at will) 





The image loading process is completed, and today's learning task is completed, so I need to organize and review the code again.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324886425&siteId=291194637