Android移动应用开发----图片查看器(请求连接网络,将图片缓存起来,使用bitmap显示图片等)

本笔记通过学习:https://www.bilibili.com/video/BV1fs411h7sh 视频写下的

设计思路

  1. 设计UI界面
  2. 找到相应的控件,通过按钮的点击事件,进行图片的查询,和联网的操作
  3. 更新UI

效果展示

在这里插入图片描述

代码展示

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.dsl.picturelook.MainActivity">
    <EditText
        android:id="@+id/et_path"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入查看的图片网址"/>
    <Button
        android:onClick="look"
        android:text="查看"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

 <ImageView
     android:id="@+id/iv"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>


</LinearLayout>

MainActivity.class 文件

package com.dsl.picturelook;


import android.app.Activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class MainActivity extends Activity {
    EditText et_path;
    ImageView iv;
//    //创建Handler对象
//    Handler handler = new Handler(){
//        //处理消息
//        @Override
//        public void handleMessage(@NonNull Message msg) {
//            Bitmap bitmap = (Bitmap) msg.obj;
//            iv.setImageBitmap(bitmap);
//        }
//    };
//    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_path = findViewById(R.id.et_path);
         iv = findViewById(R.id.iv);

    }

    //点击按钮进行查看指定路径的图片路径
    public  void look( View v){
       new Thread(){
           @Override
           public void run() {
               try {
                   //获取图片的路径
                   String path = et_path.getText().toString().trim();
                   File file = new File(getCacheDir(), Base64.encodeToString(path.getBytes(),Base64.DEFAULT));
                   if (file.exists()&&file.length()>0){
                       //使用缓存的图片
                       //通过位图工厂获取bitmap
                       final Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                       //显示图片
                       //不管在什么位置上调用action都运行在UI线程里
                       runOnUiThread(new Runnable() {
                           @Override
                           public void run() {
                               //run方法一定执行在UI线程,把bitmap显示到iv上
                               iv.setImageBitmap(bitmap);
                           }
                       });
//                       Message msg = Message.obtain();//使用message的静态方法减少对象的创建
//                       msg.obj = bitmap;
//                       handler.sendMessage(msg);
                       System.out.println("这是缓存的");
                   }else{
                       System.out.println("这是新进的");

                       //创建URL对象
                       URL url = new URL(path);
                       //获取httpURLconnection
                       HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                       //设置请求方式
                       conn.setRequestMethod("GET");
                       //设置超时时间
                       conn.setConnectTimeout(5000);
                       //获取服务器返回的状态码
                       int code = conn.getResponseCode();
                       if (code==200){
                           //获取图片的数据,不管是什么数据,都是以流的形式返回

                           /**
                            * 将图片进行缓存
                            * 谷歌提供了一个缓存目录
                            */
                           InputStream in = conn.getInputStream();
                           FileOutputStream fos = new FileOutputStream(file);
                           byte [] bytes = new byte[1024];
                           int len = -1;
                           while((len = in.read(bytes))!=-1){
                               fos.write(bytes,0,len);
                           }
                           fos.close();
                           in.close();
                           //通过位图工厂获取bitmap
                           final Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                           //不管在什么位置上调用action都运行在UI线程里
                           runOnUiThread(new Runnable() {
                               @Override
                               public void run() {
                                   //run方法一定执行在UI线程,把bitmap显示到iv上
                                   iv.setImageBitmap(bitmap);
                               }
                           });
//                           //显示图片
//                           Message msg = Message.obtain();//使用message的静态方法减少对象的创建
//                           msg.obj = bitmap;
//                           handler.sendMessage(msg);

                       }
                   }

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


    }
}

注意事项:

  1. 从网站获取的图片,同样也是以流的形式进行返回
  2. 将从网站获取的字节输入流用bitmap的静态方法:decodeFile(),传入一个文件的绝对路径
  3. 更新UI时也可以用 runOnUiThread方法,实例化 Runnable,并且实现它的run方法。
  4. 也可以使用 handler 发送消息来更新UI
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

何一平?

你的收获就是我学习的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值